diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 00000000..7b7c9bdc --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,8 @@ +# actionlint 1.7.12, the newest, does not know the reference `$/` to an +# action of the repo that holds the workflow, at the workflow's own commit, +# which GitHub documents and runners have from 2.336.0. Drop this when an +# actionlint that knows it is pinned. +paths: + .github/workflows/**/*.yml: + ignore: + - 'specifying action "\$/[^"]+" in invalid format because ref is missing' diff --git a/.github/actions/turbo-cache/action.yml b/.github/actions/turbo-cache/action.yml new file mode 100644 index 00000000..3a86796b --- /dev/null +++ b/.github/actions/turbo-cache/action.yml @@ -0,0 +1,100 @@ +name: Turbo cache server +description: >- + Starts the Turbo remote cache server a job needs, on loopback, against the + tenant's shared or trusted bucket, and tells the repo's turbow where it is. + +# A step for the jobs of the reusable workflows, which call it as +# `uses: $/.github/actions/turbo-cache`: from this repo at the commit of the +# workflow that calls it, never a version behind or ahead of it. One cache per +# job: a job that runs check and test starts the shared one, a job that runs +# build or e2e the trusted one, and never the two together, so that nothing the +# shared bucket supplied enters a build written to the trusted bucket. +# +# The vault items it reads, in the vault `-ci` unless `vault` names +# another, each with the fields endpoint, region, access-key-id and +# secret-access-key of an S3 store: +# +# bucket-turbo the shared bucket -ci-turbo +# bucket-turbo-trusted the trusted bucket -ci-turbo-trusted +# +# The server is brunojppb/turbo-cache-server, bound to 127.0.0.1 whatever the +# job's environment holds (its HOST), path-style against the bucket, with a +# token minted for the job and on the first free port from 8585 up +# (turbo-cache.sh says why). The keys go to the server alone and never to the +# job's environment; what the job's later steps get is the server's address +# and token, in the variables turbow reads. +# +# A job without vault credentials, whose vault item could not be read, or +# whose server did not come up, runs on without that remote cache, and says +# why in one line of the log and in one warning on the run; a tenant without +# the bucket on purpose gets the same warning. The step itself still fails the +# job where it cannot run at all, as without openssl, which the environment +# image carries. A server that comes up and cannot use its bucket is not +# probed: Turbo's own warning in the job's log says so. + +inputs: + cache: + description: "`shared`, the bucket -ci-turbo, for check and test; `trusted`, the bucket -ci-turbo-trusted, for build and e2e." + required: true + vault: + description: The vault the keys are read from (§ 3 PLX-Secrets). Default -ci. + required: false + default: '' + op-service-account-token: + description: The vault's service account token; not needed on a slot of a runner host, which reads the vault through its Connect server. + required: false + default: '' + +runs: + using: composite + steps: + - name: Plan the cache server + id: plan + shell: bash + env: + CACHE: ${{ inputs.cache }} + OWNER: ${{ github.repository_owner }} + VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} + SERVICE_ACCOUNT: ${{ inputs.op-service-account-token != '' }} + run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" plan' + # A failed read is a tenant without the bucket, or a vault that cannot be + # read: the job runs on without the remote cache, and announce says so. + - name: Load the bucket's keys from the vault + id: keys + if: ${{ steps.plan.outputs.read == 'true' }} + continue-on-error: true + uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + env: + # On a slot the Connect server alone, as both would warn. + OP_SERVICE_ACCOUNT_TOKEN: ${{ steps.plan.outputs.connect != 'true' && inputs.op-service-account-token || '' }} + ENDPOINT: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/endpoint + REGION: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/region + ACCESS_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/access-key-id + SECRET_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/secret-access-key + # A server that does not come up does not fail the job: announce says so. + - name: Start the cache server + id: server + if: ${{ steps.keys.outcome == 'success' }} + continue-on-error: true + uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 + env: + HOST: 127.0.0.1 + PORT: ${{ steps.plan.outputs.port }} + TURBO_TOKEN: ${{ steps.plan.outputs.token }} + S3_ENDPOINT: ${{ steps.keys.outputs.ENDPOINT }} + S3_REGION: ${{ steps.keys.outputs.REGION }} + S3_BUCKET_NAME: ${{ steps.plan.outputs.bucket }} + S3_ACCESS_KEY: ${{ steps.keys.outputs.ACCESS_KEY }} + S3_SECRET_KEY: ${{ steps.keys.outputs.SECRET_KEY }} + S3_USE_PATH_STYLE: 'true' + - name: Tell turbow where the server is + id: announce + shell: bash + env: + CACHE: ${{ inputs.cache }} + KEYS: ${{ steps.keys.outcome || 'skipped' }} + SERVER: ${{ steps.server.outcome }} + VAULT: ${{ steps.plan.outputs.vault }} + PORT: ${{ steps.plan.outputs.port }} + TOKEN: ${{ steps.plan.outputs.token }} + run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" announce' diff --git a/.github/actions/turbo-cache/turbo-cache.sh b/.github/actions/turbo-cache/turbo-cache.sh new file mode 100755 index 00000000..410051b6 --- /dev/null +++ b/.github/actions/turbo-cache/turbo-cache.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# The two phases of the step turbo-cache (action.yml beside this file) that +# are its own, around the vault's read and the server's start, which are +# actions of their own: +# +# plan Which bucket and vault item the cache (CACHE, `shared` or +# `trusted`) names for the owner (OWNER), and whether the job can +# read the vault (VAULT): through the runner's Connect server +# (OP_CONNECT_HOST and OP_CONNECT_TOKEN, as a slot of a runner host +# has them) or with the service account (SERVICE_ACCOUNT, `true` +# when the caller passed its token). For the server: the first +# free port from 8585 up, since the slots of a runner host share +# its loopback, and a token minted for this job, masked in the log, +# without which another job on the host could read and write the +# bucket through the server. Outputs: read, connect, vault, item, +# bucket, port, token. +# announce Tells turbow (repo-turbo) where the server is, through the job's +# environment: PLX_TURBO_SHARED or PLX_TURBO_TRUSTED with the +# server's address and PLX_TURBO__TOKEN with the job's token +# when the keys were read (KEYS, the outcome of the read: `success`) +# and the server came up (SERVER, the outcome of its start) on PORT +# with TOKEN; else the variable is `none`, and the step says why the +# job runs without that remote cache, in one line of the log and in +# one warning on the run: no vault to read (`skipped`), an item it +# could not read (`failure`, the step above says why), or a server +# that did not come up. In these three the job runs on. +# +# Run by hand, a phase needs only GITHUB_OUTPUT and GITHUB_ENV to name files. +set -euo pipefail + +case ${CACHE:-} in + shared) item=bucket-turbo suffix='' var=PLX_TURBO_SHARED ;; + trusted) item=bucket-turbo-trusted suffix=-trusted var=PLX_TURBO_TRUSTED ;; + *) + echo "::error::The cache is shared or trusted, not '${CACHE:-}'." + exit 1 + ;; +esac + +case ${1:-} in + plan) + connect=false + if [ -n "${OP_CONNECT_HOST:-}" ] && [ -n "${OP_CONNECT_TOKEN:-}" ]; then connect=true; fi + read=$connect + if [ "${SERVICE_ACCOUNT:-false}" = true ]; then read=true; fi + port=8585 + while (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; do port=$((port + 1)); done + token=$(openssl rand -hex 32) + echo "::add-mask::$token" + { + echo "read=$read" + echo "connect=$connect" + echo "vault=$VAULT" + echo "item=$item" + echo "bucket=$OWNER-ci-turbo$suffix" + echo "port=$port" + echo "token=$token" + } >>"$GITHUB_OUTPUT" + ;; + announce) + if [ "${KEYS:-}" = success ] && [ "${SERVER:-}" = success ]; then + { + echo "$var=http://127.0.0.1:${PORT:?}" + echo "${var}_TOKEN=${TOKEN:?}" + } >>"$GITHUB_ENV" + echo "The $CACHE remote cache: a server on 127.0.0.1:$PORT." + exit 0 + fi + case ${KEYS:-} in + skipped) cause="This job has no vault to read the item $item from." ;; + success) cause="The cache server did not come up on 127.0.0.1:${PORT:-} (the step above says why)." ;; + *) cause="The step could not read the item $item from the vault ${VAULT:-} (the step above says why)." ;; + esac + echo "$var=none" >>"$GITHUB_ENV" + echo "Turbo runs without the $CACHE remote cache: $cause" + echo "::warning title=Turbo runs without the $CACHE remote cache::$cause" + ;; + *) + echo "usage: turbo-cache.sh plan|announce" >&2 + exit 2 + ;; +esac diff --git a/.github/workflows/_changeset.yml b/.github/workflows/_changeset.yml index b001cf26..2d966dc3 100644 --- a/.github/workflows/_changeset.yml +++ b/.github/workflows/_changeset.yml @@ -67,7 +67,7 @@ jobs: changeset: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || 'ci-small' }} # mise install points core.hooksPath at hk; its hooks would run the repo's - # checks on this one commit, which the caller's verify job already does. + # checks on this one commit, which the caller's test job already does. env: HK_SKIP_HOOK: pre-commit,pre-push steps: @@ -115,7 +115,16 @@ jobs: ref: ${{ github.head_ref }} fetch-depth: 0 token: ${{ steps.app.outputs.token }} + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install - run: plx -y changeset --base 'origin/${{ inputs.base }}' - run: | git add .changeset diff --git a/.github/workflows/_check.yml b/.github/workflows/_check.yml index b9fc5031..e1c434b4 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_check.yml @@ -1,16 +1,20 @@ name: _check -# Mounts `check` (§§ 1 and 2 PLX-Delivery): the steps that ascertain code -# quality and need no machine in particular, repo-wide. In an app repo that -# is lint, typecheck and the pure tests, the part of verify that gates -# everything else: a commit that fails here builds and launches nothing. A -# repo without images to build passes `tasks: verify`, its whole contract -# verb. The incantations are the repo's own mise tasks. +# Mounts the test job (§§ 1 and 2 PLX-Delivery): the repo's own mise tasks, +# by default `test`, which runs `check` first, repo-wide, on a medium runner, +# in a checkout of the repo exactly as a developer runs them. It needs no +# built app and no Docker daemon, and gates everything after it: a commit that +# fails here plans, builds and launches nothing. Every repo mounts it, on +# every commit and every pull request; a repo with other verbs to run in the +# same job names them in `tasks`. # -# With `turbo-cache`, Turbo's remote cache (§ 8 PLX-Delivery): a cache server -# for the length of the job, on loopback, backed by the bucket -# -ci-turbo, whose keys are read from the vault; a task whose inputs -# did not change is replayed from any earlier job on any runner. +# Turbo's shared remote cache (§ 8 PLX-Delivery), for every repo: a cache +# server for the length of the job, on loopback, backed by the bucket +# -ci-turbo, started by the step turbo-cache of this repo at the +# commit of this workflow; a task whose inputs did not change is replayed from +# any earlier job or machine that wrote the bucket. A tenant without the +# bucket runs without it. This job never starts the trusted cache: what the +# shared bucket supplied stays out of every build that ships (_e2e.yml). on: workflow_call: @@ -30,15 +34,10 @@ on: type: string default: medium tasks: - description: The repo's mise tasks to run, in order, separated by spaces. `check` includes `lint` by contract (`PLX-Repo/SubVerbs`). + description: The repo's mise tasks to run, in order, separated by spaces; `test` runs `check` first. required: false type: string - default: check - turbo-cache: - description: Use Turbo's remote cache in the tenant's bucket; needs the vault's token. - required: false - type: boolean - default: false + default: test private-packages: description: >- The repo installs private packages of the tenant's from the forge's @@ -54,76 +53,24 @@ on: default: '' secrets: op-service-account-token: - description: The vault's service account token; needed with `turbo-cache` only. + description: The vault's service account token, for the cache's keys where the runner has no Connect server. required: false # No permissions of its own: the job has what its caller grants, `contents: # read` and, with `private-packages`, `packages: read`. A block here would # have to name the larger set, and every caller would then have to grant it. -env: - VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} - jobs: check: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || format('ci-{0}', inputs.size) }} steps: - # How the job reads the vault (§ 8 PLX-Delivery): a slot of a runner host - # carries its Connect server's address and token (actions_runners), and - # every other runner gets the service account's. Never both: each read - # would warn, and a slot's job has no use for the service account. - - name: How the vault is read - if: ${{ inputs.turbo-cache }} - env: - TOKEN: ${{ secrets.op-service-account-token }} - run: | - if [ -n "${OP_CONNECT_HOST:-}" ] && [ -n "${OP_CONNECT_TOKEN:-}" ]; then - echo "Through the runner's Connect server." - else - echo "OP_SERVICE_ACCOUNT_TOKEN=$TOKEN" >> "$GITHUB_ENV" - echo "With the service account." - fi - uses: actions/checkout@v7 - - name: Load the Turbo cache bucket's keys from the vault - if: ${{ inputs.turbo-cache }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + - name: Start the shared cache server + uses: $/.github/actions/turbo-cache with: - export-env: true - env: - TURBO_CACHE_ENDPOINT: op://${{ env.VAULT }}/bucket-turbo/endpoint - TURBO_CACHE_REGION: op://${{ env.VAULT }}/bucket-turbo/region - TURBO_CACHE_ACCESS_KEY: op://${{ env.VAULT }}/bucket-turbo/access-key-id - TURBO_CACHE_SECRET_KEY: op://${{ env.VAULT }}/bucket-turbo/secret-access-key - # The server's token is minted here and never leaves the machine; the - # port is the first free one, since the slots of a runner host share - # its network. - - name: Prepare the Turbo remote cache - id: turbo-cache - if: ${{ inputs.turbo-cache }} - run: | - port=8585 - while (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; do port=$((port + 1)); done - token=$(openssl rand -hex 32) - echo "::add-mask::$token" - { - echo "port=$port" - echo "bucket=${GITHUB_REPOSITORY_OWNER}-ci-turbo" - } >> "$GITHUB_OUTPUT" - { - echo "TURBO_API=http://127.0.0.1:$port" - echo "TURBO_TOKEN=$token" - echo "TURBO_TEAM=${GITHUB_REPOSITORY//\//-}" - } >> "$GITHUB_ENV" - - uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 - if: ${{ inputs.turbo-cache }} - env: - PORT: ${{ steps.turbo-cache.outputs.port }} - S3_ENDPOINT: ${{ env.TURBO_CACHE_ENDPOINT }} - S3_REGION: ${{ env.TURBO_CACHE_REGION }} - S3_BUCKET_NAME: ${{ steps.turbo-cache.outputs.bucket }} - S3_ACCESS_KEY: ${{ env.TURBO_CACHE_ACCESS_KEY }} - S3_SECRET_KEY: ${{ env.TURBO_CACHE_SECRET_KEY }} - S3_USE_PATH_STYLE: 'true' + cache: shared + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} # The tenant's private packages (§ 5 PLX-Delivery): the job's own token # in a user-level npmrc of the job's own, which pnpm and npm read beside # the scope's registry in pnpm-workspace.yaml. The repo holds no token, @@ -135,8 +82,17 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 - - name: Check + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install + - name: Test env: TASKS: ${{ inputs.tasks }} run: for task in $TASKS; do mise run "$task"; done diff --git a/.github/workflows/_deploy-targets.yml b/.github/workflows/_deploy-targets.yml index f5b62980..8582cbbd 100644 --- a/.github/workflows/_deploy-targets.yml +++ b/.github/workflows/_deploy-targets.yml @@ -35,7 +35,16 @@ jobs: matrix: ${{ steps.run.outputs.matrix }} steps: - uses: actions/checkout@v7 + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install - id: run # The assignment is a line of its own so that a failing verb fails the step. run: | diff --git a/.github/workflows/_deploy.yml b/.github/workflows/_deploy.yml index 3f6627ea..85f626c8 100644 --- a/.github/workflows/_deploy.yml +++ b/.github/workflows/_deploy.yml @@ -5,8 +5,8 @@ name: _deploy # pinned in the caller's mise.toml), never here; the caller supplies the host # and the environment. The caller is the app's SOURCE repo, because the verb # reads apps//docker/compose.yaml from the checkout and renders it onto -# the host with the image ref pinned: an app repo's release after the -# publish, or the platform repo's deploy.yml for a third-party app, whose +# the host with the image ref pinned: an app repo's _publish-deploy.yml after +# the publish, or the platform repo's deploy.yml for a third-party app, whose # compose.yaml pins its own image (no image-ref). # # The keys come from the vault `-ci` (§ 3 PLX-Secrets), read with its @@ -131,8 +131,16 @@ jobs: # The caller's repo (the app's source repo) — cwd for the verb, which # reads apps// relative here. Same SHA the image was built from. - uses: actions/checkout@v7 - # The caller's tools, plx among them. + # The caller's tools, plx among them, and its [env] for the later steps: + # on the forge's runners from mise-action; in the environment image of a + # slot or an instance (actions_runners), which carries mise and the + # common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_verify.yml b/.github/workflows/_e2e.yml similarity index 63% rename from .github/workflows/_verify.yml rename to .github/workflows/_e2e.yml index bb1a6f72..ce073130 100644 --- a/.github/workflows/_verify.yml +++ b/.github/workflows/_e2e.yml @@ -1,41 +1,69 @@ -name: _verify +name: _e2e -# Mounts `verify` for an app repo (§§ 1, 2 and 8 PLX-Delivery): build every -# app's image and test it, for the whole repo and run. The tenant's on_pr.yml -# and on_push.yml run it after _check.yml, which gates it: a commit that -# fails the check builds and launches nothing. The logic is plx-ci's -# (@plexus-ms/cli-ci, pinned in the caller's mise.toml); every step here is +# Mounts the e2e job of an app repo (§§ 1, 2 and 8 PLX-Delivery), and the plan +# in front of it: per app, on a large runner, the app's build and the suites +# that need it, the repo's own `mise run build `, then `mise run e2e +# `, against the trusted cache. The tenant's on_pr.yml and on_push.yml +# run it after _check.yml, which gates it: a commit that fails its test plans, +# builds and launches nothing. The logic is plx-ci's (@plexus-ms/cli-ci, +# pinned in the caller's mise.toml) and the repo's verbs; every step here is # one invocation. # -# plan small the build and test hashes from one Turbo dry run, the look-ups, -# the matrix; under hybrid, one instance per app that owes something -# build-and-test large per app, on one machine: `build`, the image from the pruned -# context, pushed to the registry as build-; then `test`, the -# app's compose stack on the candidate, its tests, the tag test- -# cleanup small hybrid only: delete what this run launched +# plan small every app's build hash from one Turbo dry run with the +# trusted cache named, its image looked up in the forge's +# registry, the matrix of the apps with work; under hybrid, +# one instance per app in it +# e2e large per app: `mise run build `, the browser of its suite +# where it has one, `mise run e2e ` +# cleanup small hybrid only: delete what this run launched # -# The large job carries two verbs because they want the same machine: a test -# starts when its own build ends, no second machine boots or idles meanwhile, -# and a failed build tests nothing. Which of the two a leg owes is the plan's: -# both, the test alone where the registry holds the build, or the build alone -# for an app without tests. The job's name is fixed, `build, test`, whatever a -# leg owes; the plan's log and the steps that run say which. +# Uploaded where a suite fails, as an artifact of the run for five days and +# readable by whoever can read the repository: the suite's test-results/, as +# generated each failed test's error, its spec's source and a snapshot of the +# page's text, and with the repo's own Playwright settings also traces, +# screenshots and videos. +# +# An app gets an e2e job where it has work: the plan asks the trusted cache, +# in its dry run, whether it holds the tasks the job would run, and gives the +# job to an app with suites whose build or the e2e of any of whose suites is a +# MISS, and to an app without a suite, built from the output, whose image is +# missing and whose build is a MISS; an app with a Dockerfile of its own and +# no suite gets none +# (plx-ci's core/plan.ts states the rule). What the plan cannot find out, as +# where the cache step announced no server or a pull request from a fork has +# no secrets, counts as work, and its log says why. A run in which no app has +# work has an empty matrix: the e2e job is skipped by its `if`, since a matrix +# with no entry is no job, the workflow still succeeds, and publish runs and +# tags. The build runs first in the job, also for an app without a suite, so +# that the trusted cache holds the build output its publish restores from there +# (_publish-deploy.yml); the workflow's output `apps` is every app, which +# publish fans out over, the ones without an e2e job among them. +# +# The plan job is within § 5.3: it starts the trusted cache alone, and its dry +# run only asks it, a HEAD request per task, restoring and writing nothing; it +# installs mise's tools (node, plx-ci) and no package of the repo, runs no +# verb, check or test, and builds nothing, so no output of any cache enters +# its tree, and its result is hashes and statuses. It runs the checkout's +# ./turbow, which names the trusted cache, with the server's address and the +# job's token in its environment. +# +# The e2e job neither checks +# nor tests (the test job did) and reaches the trusted cache alone, from a +# fresh checkout, so that nothing the shared cache supplied enters a build +# that is written to the trusted cache or shipped. CI is the trusted cache's +# boundary, a pull request's jobs included; a pull request from a fork gets +# no secrets and so no cache. The job needs no Docker daemon. The app's +# server-actions key reaches its build alone, which puts it into the output. # # Where a job of a size runs is the strategy's (`strategy`): the forge's # runners, the slots of the tenant's runner hosts, or, for a large job under -# hybrid, an instance of its own. Where the candidates live is `registry`: -# the pair on the tenant's object storage, or the forge's registry. -# -# A decision comes from a content hash, never from a diff: the same inputs -# are built once and tested once, and a run whose hashes all hit has no -# large job at all. +# hybrid, an instance of its own. # # The caller's secrets are one: the vault's service account token. # Everything else is read from the vault `-ci` (§ 3 PLX-Secrets): the -# apps' build-time keys always; the object-storage keys with a registry of -# the tenant's own; the cloud keys, the relay and the GitHub App under -# hybrid; the App also where the run plans a deploy, to read the operations -# repo's inventory. +# trusted cache's keys and the apps' server-actions keys always; the cloud +# keys, the relay and the GitHub App under hybrid; the App also where the run +# plans a deploy, to read the operations repo's inventory. on: workflow_call: @@ -49,19 +77,14 @@ on: required: false type: string default: github - registry: - description: "Where the candidates live: `ghcr`, the forge's registry, beside the published images; `own`, the registry pair on the tenant's object storage." - required: false - type: string - default: ghcr deploy: - description: Plan the deploys too, for the release that follows on an environment branch; a pull request deploys nowhere. + description: Plan the deploys too, for the publish and deploy that follow on an environment branch; a pull request deploys nowhere. required: false type: boolean default: false environment: description: >- - With `deploy`: the environment the run releases into. Empty derives + With `deploy`: the environment the run deploys into. Empty derives it from the branch (main → production, develop → staging, else none), which is the rule; a caller sets it only to stand in for an environment branch. @@ -115,25 +138,24 @@ on: required: true outputs: apps: - description: Every app planned, with its hashes, JSON; what _release.yml publishes. + description: Every app planned, with its build hash and what its publish does, JSON; what _publish-deploy.yml publishes. value: ${{ jobs.plan.outputs.apps }} deploys: - description: With `deploy`, the deploys of the release, JSON, for _release.yml; `[]` without an environment. + description: With `deploy`, the deploys of the run, JSON, for _publish-deploy.yml; `[]` without an environment. value: ${{ jobs.plan.outputs.deploys }} environment: - description: With `deploy`, the environment the run releases into; empty for none. + description: With `deploy`, the environment the run deploys into; empty for none. value: ${{ jobs.plan.outputs.environment }} permissions: contents: read - packages: write + packages: read actions: read env: EXO_VERSION: 1.103.2 CRANE_VERSION: 0.22.1 CI_STRATEGY: ${{ inputs.strategy }} - CI_REGISTRY: ${{ inputs.registry }} MAIL_TO: ${{ inputs.alerts-email }} VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} IMAGE_PREFIX: ${{ inputs.image-prefix || format('ghcr.io/{0}', github.repository_owner) }} @@ -162,10 +184,27 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # The plan asks the trusted cache which large jobs have work; the step + # announces the server to turbow, which the plan asks through. + - name: Start the trusted cache server + uses: $/.github/actions/turbo-cache + with: + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} + # mise, the repo's pins and its [env] for the later steps, PLX_PLATFORM + # among them, also in a trial of unreleased tooling, whose plx-ci comes + # first on the PATH: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -183,16 +222,6 @@ jobs: pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - run: plx-ci --version - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - name: Load the App's key from the vault if: ${{ inputs.deploy || inputs.strategy == 'hybrid' }} uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 @@ -224,27 +253,24 @@ jobs: - name: Read the relay's port from the vault if: ${{ inputs.strategy == 'hybrid' }} run: echo "SMTP_PORT=$(op read "op://${VAULT}/smtp-relay/port")" >> "$GITHUB_ENV" - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo - if: ${{ inputs.strategy == 'hybrid' }} + if: ${{ runner.environment == 'github-hosted' && inputs.strategy == 'hybrid' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install crane - if: ${{ inputs.registry == 'ghcr' }} + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane - name: Log in to the forge's registry - if: ${{ inputs.registry == 'ghcr' }} env: GITHUB_TOKEN: ${{ github.token }} run: printf '%s' "$GITHUB_TOKEN" | crane auth login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - - name: The registry - run: plx-ci registry # Where each app deploys is the operations repo's inventory # (PLX-Environment), checked out with the tenant's App. - name: A token that may read the operations repo @@ -268,7 +294,7 @@ jobs: env: DEPLOY: ${{ inputs.deploy && 'yes' || '' }} ENVIRONMENT: ${{ inputs.environment }} - run: plx-ci plan --test ${DEPLOY:+--deploy --environment "$ENVIRONMENT" --inventory operations/inventory} + run: plx-ci plan ${DEPLOY:+--deploy --environment "$ENVIRONMENT" --inventory operations/inventory} # Hybrid: one instance per leg, created at once, each waited for until # its runner is online. One that misses is kept, stopped and mailed # about, and replaced once. @@ -290,18 +316,19 @@ jobs: INSTANCE_TYPE: ${{ inputs.instance-type }} # Minutes after boot, each a timer the user-data arms (userData.ts). NO_JOB_MINUTES: 10 # no job started by then: the instance deletes itself, no mail - DEATH_MINUTES: 45 # a few minutes past build-and-test's timeout-minutes: a mail, then self-delete + DEATH_MINUTES: 45 # a few minutes past e2e's timeout-minutes: a mail, then self-delete POWEROFF_MINUTES: 50 # the last resort after the death deadline: power-off, the sweep removes it run: plx-ci hybrid create-instances "$MATRIX" - # One job per leg of the plan, an app that owes something, and one machine - # for it: the build where `matrix.build` says so, then the test where - # `matrix.test` carries its hash. A build that fails ends the job, so its - # test never starts; the other apps' legs run on (fail-fast off). The name - # is fixed: the forge does not evaluate `matrix` for a job it skips, and - # most runs owe nothing. What a leg owes is in the plan's log and its steps. - build-and-test: - name: build, test + # One job per app of the plan, on one machine: the app's build, the browser + # of its suite, its suites. The other apps' jobs run on when one fails + # (fail-fast off), and every publish of the run waits for all of them. The + # name is fixed: the forge does not evaluate `matrix` for a job it skips. + # PLX_PLATFORM reaches the build here and `plx-ci plan` in the plan job from + # the same place, the repo's mise.toml, through the mise steps of each job, + # so that the plan's hash is the build's. + e2e: + name: e2e needs: plan if: ${{ needs.plan.outputs.matrix != '[]' }} strategy: @@ -326,58 +353,13 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} - with: - install_args: node npm:@plexus-ms/cli-ci - - uses: actions/checkout@v7 - if: ${{ inputs.tooling-ref != '' }} - with: - repository: plexus-ms/tooling - ref: ${{ inputs.tooling-ref }} - path: .plx-ci - - uses: actions/setup-node@v7 - if: ${{ inputs.tooling-ref != '' }} - with: - node-version-file: .plx-ci/mise.toml - - name: plx-ci from the unreleased tooling - if: ${{ inputs.tooling-ref != '' }} - run: | - cd .plx-ci && corepack enable && pnpm install --frozen-lockfile --ignore-scripts >/dev/null - pnpm --filter @plexus-ms/cli-ci... run build >/dev/null - mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - # A step output, not the job's environment: the key is the build's, and - # the test that follows on this machine has no business with it. - - name: The app's fixed Next key - id: key - if: ${{ matrix.build }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - env: - NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' && inputs.strategy != 'hybrid' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + - name: Start the trusted cache server + uses: $/.github/actions/turbo-cache with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # plx-ci test finds the candidate with crane, which reads the login - # docker writes below; into the job's home, as in plan. - - name: Install crane - if: ${{ inputs.registry == 'ghcr' && matrix.test != '' }} - run: | - mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" - curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane - - name: Log in to the forge's registry - if: ${{ inputs.registry == 'ghcr' }} - env: - GITHUB_TOKEN: ${{ github.token }} - run: printf '%s' "$GITHUB_TOKEN" | docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - # The tenant's private packages (§ 5 PLX-Delivery), for the test's install - # and, as a BuildKit secret, for the image's (plx-ci build): the job's own token + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} + # The tenant's private packages (§ 5 PLX-Delivery): the job's own token # in a user-level npmrc of the job's own, which pnpm and npm read beside # the scope's registry in pnpm-workspace.yaml. The repo holds no token, # and the package grants this repo's workflows read access on the forge. @@ -388,41 +370,58 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" - - name: The registry - run: plx-ci registry - # The specs and their dependencies, the app's own; Chromium's headless - # shell, which is all a headless spec launches, with its system libraries - # at the Playwright version the lockfile pins. Started here in the - # background, so that it runs beside the build, and awaited below. - - name: Start installing the app's dependencies and the browser - if: ${{ matrix.test != '' }} - run: | - { - set +e - ( - set -e - corepack enable - pnpm install --frozen-lockfile --filter "{./apps/${{ matrix.app }}}..." - pnpm --filter "./apps/${{ matrix.app }}" exec playwright install --with-deps --only-shell chromium - ) - echo $? > "$RUNNER_TEMP/install.exit" - } > "$RUNNER_TEMP/install.log" 2>&1 & - echo $! > "$RUNNER_TEMP/install.pid" + # mise, all of the repo's pins and its [env] for the later steps: on the + # forge's runners from mise-action; in the environment image of a slot + # or an instance (actions_runners), which carries mise and the common + # tools, from its ci-mise-install. + - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install + # A step output, not the job's environment: the key is the build's. + - name: The app's server-actions key + id: key + uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + env: + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key - name: Build - if: ${{ matrix.build }} env: + APP: ${{ matrix.app }} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} - run: plx-ci build "${{ matrix.app }}" "${{ matrix.hash }}" "$GITHUB_SHA" - # The install's log, to its end, and its outcome; an install that died - # without one has failed. - - name: Install the app's dependencies and the browser - if: ${{ matrix.test != '' }} - run: | - tail --pid="$(cat "$RUNNER_TEMP/install.pid")" -n +1 -f "$RUNNER_TEMP/install.log" - exit "$(cat "$RUNNER_TEMP/install.exit" 2>/dev/null || echo 1)" - - name: Test - if: ${{ matrix.test != '' }} - run: plx-ci test "${{ matrix.app }}" "${{ matrix.hash }}" "${{ matrix.test }}" + run: mise run build "$APP" + # Chromium at the version each suite's Playwright pins, in each suite's + # directory, since two suites may pin two versions, whose browsers + # differ; into the cache the medium and large slots share; with its + # system libraries on the forge's runners (the environment image carries + # them). + - name: The suites' browsers + if: ${{ join(matrix.suites, '') != '' }} + env: + SUITES: ${{ join(matrix.suites, ' ') }} + WITH_DEPS: ${{ runner.environment == 'github-hosted' && 'yes' || '' }} + run: for suite in $SUITES; do (cd "$suite" && pnpm exec playwright install ${WITH_DEPS:+--with-deps} chromium); done + - name: E2E + id: e2e + env: + APP: ${{ matrix.app }} + run: mise run e2e "$APP" + # Only where the E2E step ran and failed: its conclusion is `skipped` + # where an earlier step failed and `success` on a green run, and + # failure() lifts the default success(); the job stays failed. One + # artifact per app and attempt, which holds each suite's results under + # the suite's directory name. Hidden files stay out, Playwright's + # .last-run.json among them, so a suite that wrote nothing else adds + # nothing, and a run with nothing to keep uploads nothing. + - name: Keep the failed suites' results + if: ${{ failure() && steps.e2e.conclusion == 'failure' }} + uses: actions/upload-artifact@v7 + with: + name: e2e-${{ matrix.app }}-attempt-${{ github.run_attempt }} + path: e2e/*/test-results/ + if-no-files-found: ignore + retention-days: 5 # Hybrid: delete what this run launched, whatever the jobs ended in: an # instance a failed job left, or a runner that never took one. Skipped @@ -432,7 +431,7 @@ jobs: # fails the run: what it leaves, the instances' own deadlines and the # daily housekeeping remove. cleanup: - needs: [plan, build-and-test] + needs: [plan, e2e] if: >- ${{ always() && inputs.strategy == 'hybrid' && needs.plan.result != 'skipped' && !(needs.plan.result == 'success' && needs.plan.outputs.matrix == '[]') }} @@ -454,10 +453,18 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -492,9 +499,10 @@ jobs: owner: ${{ github.repository_owner }} repositories: ${{ github.event.repository.name }} permission-administration: write - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo diff --git a/.github/workflows/_housekeeping.yml b/.github/workflows/_housekeeping.yml index 6dc15324..35cb352e 100644 --- a/.github/workflows/_housekeeping.yml +++ b/.github/workflows/_housekeeping.yml @@ -4,16 +4,12 @@ name: _housekeeping # schedule where the thing kept lives. Logic lives in plx-ci # (@plexus-ms/cli-ci, pinned in the caller's mise.toml), never here. # -# hybrid the last layer under the instances: delete every one that is stopped or -# past its death deadline and mail about it; one kept after a missed boot -# is spared, mailed about again after seven days, deleted after fourteen -# registry own the week's buckets: this week's exists, the one from two weeks ago goes -# registry ghcr the candidates of this repo's apps older than thirty days go +# hybrid the last layer under the instances: delete every one that is stopped or +# past its death deadline and mail about it; one kept after a missed boot +# is spared, mailed about again after seven days, deleted after fourteen # -# The instances and the buckets are the tenant's, not one app repo's, so the -# platform repo mounts the first two; the packages are the app repo's, and -# only its own workflow token may delete their versions, so the app repo -# mounts the third. +# The instances are the tenant's, not one app repo's, so the operations repo +# mounts it. Outside `hybrid` the workflow does nothing. on: workflow_call: @@ -27,11 +23,6 @@ on: required: false type: string default: github - registry: - description: "Which retention to run: `own`, the registry buckets; `ghcr`, the candidates of the caller's apps in the forge's registry; `none`, neither." - required: false - type: string - default: none vault: description: The vault CI reads (§ 3 PLX-Secrets). Default -ci. required: false @@ -57,12 +48,11 @@ on: default: '' secrets: op-service-account-token: - description: The vault's service account token; needed under hybrid and with a registry of the tenant's own. + description: The vault's service account token; needed under hybrid. required: false permissions: contents: read - packages: write env: EXO_VERSION: 1.103.2 @@ -89,10 +79,18 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -122,29 +120,13 @@ jobs: SMTP_USER: op://${{ env.VAULT }}/smtp-relay/username SMTP_PASSWORD: op://${{ env.VAULT }}/smtp-relay/password MAIL_FROM: op://${{ env.VAULT }}/smtp-relay/from - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo - if: ${{ inputs.strategy == 'hybrid' }} + if: ${{ runner.environment == 'github-hosted' && inputs.strategy == 'hybrid' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo - name: Sweep the instances if: ${{ inputs.strategy == 'hybrid' }} run: plx-ci ${{ inputs.dry-run && '-n' || '' }} hybrid sweep-instances - - name: Rotate the registry - if: ${{ inputs.registry == 'own' || inputs.registry == 'ghcr' }} - env: - CI_REGISTRY: ${{ inputs.registry }} - GITHUB_TOKEN: ${{ github.token }} - run: plx-ci ${{ inputs.dry-run && '-n' || '' }} registry rotate diff --git a/.github/workflows/_plx-update.yml b/.github/workflows/_plx-update.yml index 02956fe2..514f0150 100644 --- a/.github/workflows/_plx-update.yml +++ b/.github/workflows/_plx-update.yml @@ -128,7 +128,16 @@ jobs: - uses: actions/checkout@v7 with: token: ${{ steps.app.outputs.token }} + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install - run: command -v gh >/dev/null || mise use --global gh@latest - run: plx -y update ${{ inputs.version != '' && format('--to {0}', inputs.version) || '' }} ${{ inputs.now && '--now' || '' }} env: diff --git a/.github/workflows/_release.yml b/.github/workflows/_publish-deploy.yml similarity index 62% rename from .github/workflows/_release.yml rename to .github/workflows/_publish-deploy.yml index 1fa5f8d1..7d45d27f 100644 --- a/.github/workflows/_release.yml +++ b/.github/workflows/_publish-deploy.yml @@ -1,34 +1,50 @@ -name: _release +name: _publish-deploy -# Mounts `release` for an app repo (§§ 1, 2 and 8 PLX-Delivery): publish -# every app's tested image under its commit and deploy it into the run's -# environment. The tenant's on_push.yml runs it after _check.yml and -# _verify.yml on a push to an environment branch, and hands it what the -# verify planned: the apps, the environment, and where each app deploys. +# Mounts publish and deploy for an app repo (§§ 1, 2, 4 and 8 PLX-Delivery): +# every app's image under its commit in the forge's registry, then each +# deployed into the run's environment. The tenant's on_push.yml runs it on a +# push to an environment branch after _check.yml and _e2e.yml, whose jobs it +# needs, and hands it what the plan of _e2e.yml said: the apps, the +# environment, and where each app deploys. # -# publish small the tested manifest under its commit in the forge's registry +# publish small per app: tag the image the registry holds, or +# build it from the app's build output, restored +# from the trusted cache, and push it # display-versions small what each app shows as its version, and the version production cuts # deploy small _deploy.yml per app with a target in the environment # tag-display-version small the cut version's tag and GitHub Release, once every deploy is green # +# That a published image was tested is the order of the jobs, and nothing +# records it. The gate is the caller's: on_push.yml of repo-turbo calls this +# workflow with `needs: [test, e2e]`, so it runs only once the run's test job +# and every e2e job have passed, an app's image is published from content +# whose test and e2e passed in the same run, and a failed e2e of one app +# publishes nothing. This workflow has no job that waits on them itself. +# A publish that builds reaches the trusted cache alone, from a fresh checkout, +# where the app's e2e job left the build output, and builds the image through +# the runner host's BuildKit service where the slot has BUILDKIT_HOST (on-prem +# and hybrid), else through the runner's Docker (github; plx-ci publish says +# how). One whose image exists, +# a promotion's or a change to tests alone, builds nothing, adds the commit's +# tag, and its deploy leaves the app running where the host serves that image. +# # The two display-version jobs run only with the input `display-versions`; -# without it the release is publish and deploy and nothing else. A repo that +# without it this workflow is publish and deploy and nothing else. A repo that # turns it on states `major:` in its PLEXUS.md, grants this workflow # `contents: write` (the tag and the Release), uses ${PLEXUS_DISPLAY_VERSION} -# in the compose files of the apps that show it, and serializes its release -# job (a concurrency group per ref that cancels nothing), so that two pushes -# to main never take the same number. plx-ci's display-versions states how -# the versions are read from the tags and the registry (PLX-Releases). +# in the compose files of the apps that show it, and serializes the job that +# calls this workflow (a concurrency group per ref that cancels nothing), so +# that two pushes to main never take the same number. plx-ci's +# display-versions states how the versions are read from the tags and the +# registry (PLX-Releases). # -# Every deploy is handed the commit released, display versions or not: an +# Every deploy is handed the commit deployed, display versions or not: an # app whose compose file uses ${PLEXUS_COMMIT_SHA} shows the commit it was # started from, and one that does not is deployed as before. # -# A promotion never builds: a commit whose images the registry holds is -# published from them and deployed. Without an environment (a run by hand on -# a branch that names none) nothing is released. A release once started runs -# to its end: the caller cancels a superseded check or verify, never this -# (§ 2 PLX-Delivery). +# Without an environment (a run by hand on a branch that names none) nothing +# is published or deployed. Once started it runs to its end: the caller +# cancels a superseded test or e2e, never this (§ 2 PLX-Delivery). on: workflow_call: @@ -42,26 +58,21 @@ on: required: false type: string default: github - registry: - description: "Where the candidates live: `ghcr`, the forge's registry, beside the published images; `own`, the registry pair on the tenant's object storage." - required: false - type: string - default: ghcr overlay: description: "How a deploy reaches the hosts: `netbird`, over the tenant's overlay, which the job joins itself where its runner is not on it; `none`, as named." required: false type: string default: none apps: - description: The apps to publish, with their hashes, JSON; _verify.yml's output `apps`. + description: The apps to publish, with their hashes and what each publish does, JSON; _e2e.yml's output `apps`. required: true type: string deploys: - description: The deploys, JSON; _verify.yml's output `deploys`. + description: The deploys, JSON; _e2e.yml's output `deploys`. required: true type: string environment: - description: The environment released into; _verify.yml's output `environment`. Empty releases nothing. + description: The environment deployed into; _e2e.yml's output `environment`. Empty publishes and deploys nothing. required: true type: string image-prefix: @@ -82,9 +93,17 @@ on: display-versions: description: >- Give every deployed app a display version, PLEXUS_DISPLAY_VERSION, - and cut a version tag with a GitHub Release when a production release - changes an app (PLX-Releases). Off: the release neither computes nor - tags anything. + and cut a version tag with a GitHub Release when a deploy to production + changes an app (PLX-Releases). Off: nothing computes or tags a version. + required: false + type: boolean + default: false + private-packages: + description: >- + The repo installs private packages of the tenant's from the forge's + package registry (§ 5 PLX-Delivery): a publish that builds logs in to + it with the job's own token, which needs `packages: read` from the + caller. required: false type: boolean default: false @@ -109,14 +128,13 @@ on: env: CRANE_VERSION: 0.22.1 CI_STRATEGY: ${{ inputs.strategy }} - CI_REGISTRY: ${{ inputs.registry }} CI_OVERLAY: ${{ inputs.overlay }} VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} IMAGE_PREFIX: ${{ inputs.image-prefix || format('ghcr.io/{0}', github.repository_owner) }} jobs: publish: - if: ${{ inputs.environment != '' }} + if: ${{ inputs.environment != '' && inputs.apps != '[]' }} permissions: contents: read packages: write @@ -141,10 +159,38 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # Only where publish builds from the output: the restore of `mise run + # build ` reads the trusted cache, where the app's e2e job left it. + - name: Start the trusted cache server + if: ${{ matrix.build && matrix.context == 'output' }} + uses: $/.github/actions/turbo-cache + with: + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} + # The tenant's private packages (§ 5 PLX-Delivery), for the restore's + # install and, as a BuildKit secret, for a Dockerfile of the app's own: + # the job's own token in a user-level npmrc of the job's own. + - name: Log in to the forge's package registry + if: ${{ inputs.private-packages && matrix.build }} + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" + echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" + # mise, the repo's pins and its [env] for the later steps, PLX_PLATFORM + # among them, also in a trial of unreleased tooling, whose plx-ci comes + # first on the PATH: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -161,19 +207,18 @@ jobs: cd .plx-ci && corepack enable && pnpm install --frozen-lockfile --ignore-scripts >/dev/null pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} + # A step output, not the job's environment: the key is the build's, where + # the restore misses the cache, or a Dockerfile of the app's own's. + - name: The app's server-actions key + id: key + if: ${{ matrix.build }} uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install crane + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -181,12 +226,13 @@ jobs: env: GITHUB_TOKEN: ${{ github.token }} run: printf '%s' "$GITHUB_TOKEN" | crane auth login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - - name: The registry - run: plx-ci registry - name: Publish env: - TEST: ${{ matrix.test }} - run: plx-ci publish "${{ matrix.app }}" "${{ matrix.hash }}" "$GITHUB_SHA" ${TEST:+--test "$TEST"} + APP: ${{ matrix.app }} + HASH: ${{ matrix.hash }} + CONTEXT: ${{ matrix.context }} + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} + run: plx-ci publish "$APP" "$HASH" "$GITHUB_SHA" --context "$CONTEXT" # One deploy per app with a target in the environment; an app without a # record there has no deployment there, which the plan said. The nested @@ -209,10 +255,18 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -230,6 +284,7 @@ jobs: pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - name: Install crane + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -273,7 +328,7 @@ jobs: op-service-account-token: ${{ secrets.op-service-account-token }} # The version names a state of production that happened: only once every - # deploy of the release is green, and only when it cut one. A re-run of the + # deploy of the run is green, and only when it cut one. A re-run of the # failed deploys gets here with the same number. tag-display-version: needs: [display-versions, deploy] @@ -283,10 +338,18 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_publish-package.yml b/.github/workflows/_publish-package.yml index fe5af06e..68bbb103 100644 --- a/.github/workflows/_publish-package.yml +++ b/.github/workflows/_publish-package.yml @@ -51,7 +51,7 @@ jobs: # hk, so hk's hooks would fire on anything changesets/action commits or # pushes through the git CLI. Wrong in both directions: pre-push cannot # resolve the tag objects `changeset publish` creates, and re-running - # the checks here only repeats what the check job already ran. + # the checks here only repeats what the test job already ran. env: HK_SKIP_HOOK: pre-commit,pre-push steps: @@ -79,7 +79,16 @@ jobs: printf '@%s:registry=https://npm.pkg.github.com\n' "$scope" } > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install - run: pnpm install --frozen-lockfile # Build every package in dependency order before publishing: `changeset # publish` runs the packages' `prepack` hooks alphabetically, so a diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index d668d3a2..61fc72af 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -1,14 +1,15 @@ name: runner-image -# Builds the runner image of a runner host's slots (the Dockerfile actions_runners -# ships, ansible/ci/roles/actions_runners/files/ci-runner, § 8 -# PLX-Delivery) and pushes it to ghcr.io/plexus-ms/ci-runner with a provenance -# attestation. On the version's GitHub release it is tagged with the version -# number, which is the pin actions_runners carries; run by hand on a branch it -# is tagged `sha-`, which is how a host tries an unreleased image -# before the version (the role's `actions_runners_image`). A tag already in the -# registry is pushed again, from the same source: the Plexus version names one -# commit. +# Builds the environment image a CI job runs in, on a runner host's slots and +# on the hybrid strategy's instances (the Dockerfile actions_runners ships, +# ansible/ci/roles/actions_runners/files/ci-runner, § 8 PLX-Delivery), and +# pushes it to ghcr.io/plexus-ms/ci-runner with a provenance attestation. On +# the version's GitHub release it is tagged with the version number, which is +# the pin actions_runners carries and the image plx-ci's instances pull; run +# by hand on a branch it is tagged `sha-`, which is how a host or an +# instance (RUNNER_IMAGE) tries an unreleased image before the version (the +# role's `actions_runners_image`). A tag already in the registry is pushed +# again, from the same source: the Plexus version names one commit. on: release: @@ -32,6 +33,19 @@ jobs: attestations: write steps: - uses: actions/checkout@v7 + # The image installs plx-ci at the version from npm (its mise.toml), which + # release.yml publishes from the same release, at the same time as this. + - name: Wait for the version's plx-ci on npm + if: ${{ github.event_name == 'release' }} + env: + VERSION: ${{ github.event.release.tag_name }} + run: | + for _ in $(seq 1 60); do + npm view "@plexus-ms/cli-ci@$VERSION" version >/dev/null 2>&1 && exit 0 + sleep 30 + done + echo "@plexus-ms/cli-ci@$VERSION is not on npm after half an hour" >&2 + exit 1 - name: Which tag id: tag env: @@ -54,7 +68,7 @@ jobs: labels: | org.opencontainers.image.source=https://github.com/${{ github.repository }} org.opencontainers.image.revision=${{ github.sha }} - org.opencontainers.image.description=GitHub Actions runner for the container slots of actions_runners + org.opencontainers.image.description=The environment a CI job runs in, on the slots of actions_runners and on plx-ci's instances org.opencontainers.image.licenses=GPL-3.0-or-later - uses: actions/attest-build-provenance@v4 with: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..016e65a6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,29 @@ +name: test + +# Mounts the verbs on this repo's own events (§ 2 PLX-Delivery), through this +# repo's own reusable _check.yml with the verbs as its tasks: `test` on every +# push, which includes `check` (`mise test` runs it first) and is the same +# `mise test` the pre-push hook runs, and on a pull request `test`, then `e2e`, +# the newborn tests, which need the network, a local registry and Docker. The +# tasks run in one job, in order, and a failing `test` stops it before `e2e` +# (the step runs under `bash -e`). On a pull request `test` runs on the merge +# commit, so a pull request from a fork gets it too. +# Every push includes the update bot's branches, whose pull requests merge +# unattended only once a check is green, and the version's bookkeeping commits. + +on: + push: + pull_request: + +permissions: + contents: read + +concurrency: + group: test-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + uses: ./.github/workflows/_check.yml + with: + tasks: ${{ github.event_name == 'pull_request' && 'test e2e' || 'test' }} diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml deleted file mode 100644 index 91fca7c4..00000000 --- a/.github/workflows/verify.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: verify - -# Mounts the verify verb on every push (§ 2 PLX-Delivery): the same `mise -# verify` the pre-push hook runs, through this repo's own reusable _check.yml -# with the whole contract verb as its task. -# Every push includes the update bot's branches, whose pull requests merge -# unattended only once a check is green, and the version's bookkeeping commits. - -on: - push: - -permissions: - contents: read - -concurrency: - group: verify-${{ github.ref }} - cancel-in-progress: true - -jobs: - verify: - uses: ./.github/workflows/_check.yml - with: - tasks: verify diff --git a/PLEXUS.md b/PLEXUS.md index 2045c323..b9550beb 100644 --- a/PLEXUS.md +++ b/PLEXUS.md @@ -1,6 +1,4 @@ --- -plexus: 0.101.0 -modules: [PLX-Repo, PLX-JS, PLX-Updates] --- - `tooling` ships the methodology's primitives (§ 1.6 PLX): the four `plexus.*` Ansible collections under `ansible//` (host, platform, infrastructure, ci; § 2 PLX-Platform), the reusable workflows under `.github/workflows/_*.yml`, the Plexus-versioned packages `@plexus-ms/{cli,cli-ci,cli-template,lib}` under `packages/`, and the shared Renovate preset under `renovate/`. diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index a04b5dfb..f9a5c3d3 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -13,17 +13,14 @@ # under on-prem all three, under hybrid small and medium, since the large # jobs then run on instances the plan launches. # -# A small or medium slot has no Docker socket: its jobs need none, and a -# socket would be root on this host. It runs with the host's network, so it -# reaches the registry pair on localhost and the overlay's names the host -# resolves. A large slot runs the jobs that need Docker (build, test) and -# has a daemon of its own inside its container, with its data on a volume -# that goes with the container: the job meets an empty machine, as on a -# launched instance, takes its layers from the registry, and leaves nothing -# on the host. That container is privileged, which is root on this host, and -# has a network of its own, so that the two daemons do not share one. Every -# slot holds the job's secrets in flight like any runner: one host serves -# one tenant and runs nothing else (§ 1 PLX-Tenancy). +# Every slot, whatever its size, runs the same container of the environment +# image (files/ci-runner), the one a launched instance runs too: no Docker +# socket, since no job needs a daemon and a socket would be root on this +# host, no privileges, and the host's network, so that it reaches the +# registry pair on localhost and the overlay's names the host resolves. The +# size decides the memory limit and which caches the slot shares (below). +# Every slot holds the job's secrets in flight like any runner: one host +# serves one tenant and runs nothing else (§ 1 PLX-Tenancy). # # The host needs Docker before this role (docker). The role opens no # port: the runner polls the forge, and the registry pair listens on loopback. @@ -46,10 +43,10 @@ actions_runners_runner_group: Default # The slots, by size: `small: { count: 4 }` is the units ci-runner@small-1 # to ci-runner@small-4, each registering with the label ci-small (§ 8 # PLX-Delivery: plan, publish, deploy, cleanup and housekeeping are small, -# check is medium, build and test are large). `memory` is the limit of one +# test is medium, e2e is large). `memory` is the limit of one # slot's container, as `docker run --memory` takes it; under it a job is -# killed rather than the host starved, and for a large slot it covers the -# daemon inside and everything the job starts there. Empty, or left out, +# killed rather than the host starved, and it covers everything the job +# starts, a browser and a test database included. Empty, or left out, # is no limit. A size with count 0, or dropped, stops and disables its units. # The sum of count × memory is the host's to afford; one large slot per host # is the layout that keeps two builds from contending. @@ -87,8 +84,7 @@ actions_runners_app_private_key: "{{ lookup('env', 'CI_APP_PRIVATE_KEY') | defau # 127.0.0.1:5000 against this week's bucket, read-write, and on :5001 # against the previous week's, read-only, as a job elsewhere starts them # for itself (`plx-ci registry`, which finds them answering here and starts -# nothing; a large slot, with a network of its own, starts its own pair on -# the same buckets). The buckets are `-ci-registry-`; the +# nothing). The buckets are `-ci-registry-`; the # housekeeping creates this week's when it is missing and moves the pair to # the new buckets at the week change. Set false for a tenant on GHCR alone. actions_runners_registry: true @@ -101,9 +97,38 @@ actions_runners_registry_region: "{{ lookup('env', 'REGISTRY_REGION') | default( actions_runners_registry_access_key: "{{ lookup('env', 'REGISTRY_ACCESS_KEY') | default('', true) }}" actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | default('', true) }}" -# The caches shared by every slot, bind-mounted into each container: the -# pnpm store, built for concurrent writers (content-addressed, files added -# by atomic rename). Owned by the image's runner user. +# The caches the medium and large slots share, bind-mounted into their +# containers (ci-runner-slot), each safe for concurrent jobs: +# +# pnpm-store the pnpm store, content-addressed, files added by atomic +# rename +# mise mise's data, state and cache directories, where a repo's +# pins the image lacks install, its node and its +# PostgreSQL among them (mise locks a version while it +# installs it) +# corepack corepack's downloads of the pnpm a repo names, each moved +# into place whole +# ms-playwright Playwright's browsers, whose version follows each repo +# (Playwright locks the directory while it installs) +# +# A cache one job writes and another runs from is a way for the first to +# plant code in the second. That holds for the pnpm store too: pnpm checks a +# cached file against the hash its index records, which catches corruption, +# not a job that rewrites both, and its documentation (storeDir, +# verifyStoreIntegrity) keeps a store to mutually trusted jobs. So which +# slots share follows the secrets their jobs hold (the maintainer's +# decision). A small slot runs plan, publish, deploy and housekeeping, the +# jobs that hold the deploy and publish secrets: it mounts none of these, +# runs only what the image carries, read-only, and installs a repo's pin or +# its packages it needs into its own container, which goes with the job. +# The medium and large slots run test and e2e and share all four among +# themselves, a job there able to change what a later one runs: accepted, +# since none of them holds the deploy or publish secrets, though an e2e job +# holds the keys of the trusted cache, in the cache server it starts, and the +# app's server-actions key, so a test or e2e job can change what a later e2e +# job runs while it writes the trusted cache. Nothing prunes the caches: a +# version no repo pins any more stays until removed by hand. Owned by the +# image's runner user. actions_runners_cache_dir: /var/cache/ci-runner actions_runners_runner_uid: 1001 @@ -130,7 +155,8 @@ actions_runners_connect_image_api: 1password/connect-api:1.8.4 actions_runners_connect_image_sync: 1password/connect-sync:1.8.4 # The user the containers run as, which owns the credentials file. actions_runners_connect_uid: 999 -# The API's port on loopback and on the Docker bridge's gateway. +# The API's port, on loopback, where every slot reaches it over the host's +# network, and on the Docker bridge's gateway, which no slot uses. actions_runners_connect_port: 8080 # Housekeeping, hourly: the registry pair onto this week's buckets, the @@ -138,3 +164,98 @@ actions_runners_connect_port: 8080 # and so mails through mail, when the root file system is fuller # than this afterwards. actions_runners_disk_alert_percent: 85 + +# The BuildKit service (§ 8 PLX-Delivery): one buildkitd on the host, the +# systemd unit ci-buildkit, through which the publish job of a small or +# medium slot builds and pushes its image without a Docker daemon of its +# own, with buildx's remote driver: +# +# docker buildx create --name --driver remote tcp://127.0.0.1: +# docker buildx build --builder --platform linux/amd64 --push … +# +# It listens on 127.0.0.1 alone, without TLS. Every slot shares the host's +# network and reaches it there. No slot gains a socket or a privilege for +# it. The registry credentials travel from the job's +# ~/.docker/config.json through the build's session; the service holds +# none. Its state is /var/lib/buildkit, bounded by BuildKit's own garbage +# collection, which runs when the daemon starts and after builds; the +# hourly housekeeping leaves it alone. A run restarts the daemon whenever +# its binary, configuration or unit on disk changed after it started, also +# after an earlier run that failed halfway; a publish job in flight does +# not survive that. It goes by the files' change time, so a file touched +# without a change restarts the daemon once, and a clock stepped back after +# the daemon started can hide a later change. Under the strategy `github` +# there is no runner host and so no service: the publish job uses the +# runner's Docker. +# +# Nothing removes the service from a host once this role ran there: a host +# dropped from the group `ci`, or a tenant that switches to `github`, keeps +# it running until someone runs `systemctl disable --now ci-buildkit` and +# deletes the unit, /etc/buildkit, /var/lib/buildkit and the binaries. The +# bridge buildkit0, its route and its NAT rules (iptables chains CNI-*) +# outlive a stop of the service until a reboot or `ip link delete +# buildkit0` and the removal of those rules. +# +# One service for every job of every repo the host serves is accepted as it +# behaves, inside the one tenant the host serves (§ 1 PLX-Tenancy): +# - The layer cache is shared across jobs and repos. A step that used a +# secret mount (RUN --mount=type=secret) is reused from it by another job +# with the first job's secret, since the secret is not part of the cache +# key; a Dockerfile never bakes a secret into a layer. +# - Any job that reaches the endpoint can list and prune the whole cache. +# - A RUN step runs as root in its container with runc's default +# capabilities, raw sockets among them, so it sees all traffic of its +# network namespace. That namespace is its own, on BuildKit's bridge +# buildkit0 (a route on the host, actions_runners_buildkit_subnet), +# with the internet through NAT and iptables, which Docker brings: a step +# reaches neither the host's loopback nor its traffic, and reaches the +# host itself only at the bridge's address, through the host firewall's +# input rules; steps of builds running at the same time share the bridge. +# RUN --network=host is refused, since the network.host entitlement is +# not granted. The pulls and the push are the daemon's, on the host's +# network. +# +# buildkitd runs as root, as dockerd does; its RUN steps are containers +# without privileges, since it grants no insecure entitlement such as +# security.insecure. Its rootless mode is not used. BuildKit's +# documentation for it puts the build steps on the daemon's network and +# recommends isolating the daemon's network namespace from the host's +# through RootlessKit; the daemon would then no longer listen on the host's +# loopback, where the slots reach it. It needs RootlessKit, which the +# release does not ship, newuidmap and a subuid range on the host, and no +# one has run it on a runner host. + +# The release, from github.com/moby/buildkit/releases for linux-amd64, by +# version and the tarball's SHA-256 (the asset's digest on the release page); +# the two move together, by hand, since no update bot can rewrite the +# checksum of a download. buildkitd, buildkit-runc, the bridge's CNI +# plugins (buildkit-cni-*) and buildctl go to /usr/local/bin; buildctl is +# the operator's on the host, as in `buildctl --addr tcp://127.0.0.1:1234 du`. +actions_runners_buildkit_version: v0.35.1 +actions_runners_buildkit_sha256: b248c2b91698aafef11818fe8b681dc5e341581f7d5676709ff45ca1f29b0408 +# The port on 127.0.0.1, which the role hands every slot as BUILDKIT_HOST, where +# the publish job names it in its remote driver. +actions_runners_buildkit_port: 1234 +# The most disk the cache may use, BuildKit's maxUsedSpace: bytes with a +# unit (10GB, as base 1024) or a percentage of the disk (20%); what is above +# it the garbage collection reclaims. +actions_runners_buildkit_cache_max: 10GB +# The memory of the daemon and every build step it runs, together, as +# systemd's MemoryMax= takes it (4G), with no swap beside it; empty is no +# limit. A build runs in the service, not in the slot that asked for it, so +# a slot's limit does not bound it. Over this one the kernel kills a +# process of the service rather than starve the slots: a build step, whose +# build fails, or the daemon itself, which systemd starts again, failing +# every build in flight. A publish of the template's Dockerfile only copies +# the build output onto the base image and needs little; an app with a +# Dockerfile of its own builds inside it and needs what its build needs. +# The sum of the slots' limits and this one is the host's to afford. +actions_runners_buildkit_memory: 4G +# The subnet of the build steps' bridge buildkit0, BuildKit's bridgeSubnet +# (in its source, not its documentation); empty is BuildKit's default, +# 10.10.0.0/16. A host that routes a network overlapping it sets another. +# buildkitd does not readdress a bridge that exists: a change takes +# `systemctl stop ci-buildkit && ip link delete buildkit0` before the run, +# or the daemon fails to start ("buildkit0" already has an IP address +# different from …) and the run with it. +actions_runners_buildkit_subnet: "" diff --git a/ansible/ci/roles/actions_runners/files/ci-connect-refresh b/ansible/ci/roles/actions_runners/files/ci-connect-refresh index a9f5c52d..4b902ff3 100755 --- a/ansible/ci/roles/actions_runners/files/ci-connect-refresh +++ b/ansible/ci/roles/actions_runners/files/ci-connect-refresh @@ -14,7 +14,8 @@ set -eu # shellcheck source=/dev/null . /etc/op-connect/connect.env stamp=$(sha256sum "$CREDENTIALS" | cut -c1-16) -# The host's address on the default bridge, for the large slot's own network. +# The host's address on the default bridge, where the API listens too; no +# slot uses it, since every slot shares the host's network. gateway=$(docker network inspect bridge --format '{{ (index .IPAM.Config 0).Gateway }}') ensure() { diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index bc8c2ef3..97ec2b3d 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -15,10 +15,10 @@ set -eu # The pinned image, present before the next slot container needs it. [ "$PULL" != true ] || docker pull --quiet "$IMAGE" >/dev/null -# The slots run with --rm and start no containers on this daemon (a small -# or medium slot has no socket, a large one a daemon of its own), so a -# stopped container is one a crash left, and so is a volume nothing uses: a -# large slot's daemon data goes with its container otherwise. Every image +# The slots run with --rm and start no containers on this daemon (no slot +# has a socket), so a stopped container is one a crash left, and a volume +# nothing uses is no slot's: a slot's container mounts directories of the +# host and no volume. Every image # but the pinned runner image and the registry's is a previous pin's; the # pinned one is kept although a slot between two containers leaves it unused # for a moment, and an image a container still uses refuses removal. @@ -28,10 +28,13 @@ docker image ls --format '{{.Repository}}:{{.Tag}} {{.ID}}' | while read -r ref case "$ref" in "$IMAGE" | "$REGISTRY_IMAGE") continue ;; esac docker image rm "$id" >/dev/null 2>&1 && echo "removed the image $ref" || true done +# The BuildKit service (ci-buildkit) keeps its cache in /var/lib/buildkit, +# outside this daemon, and bounds it by its own garbage collection; nothing +# here touches it, since a build may be using it. used=$(df --output=pcent / | tail -1 | tr -dc '0-9') echo "root file system ${used}% used" if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store) and docker system df" >&2 + echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the medium and large slots' caches: the pnpm store, mise, corepack, Playwright), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 exit 1 fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index c7f90dc7..6b87a5eb 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -1,16 +1,30 @@ #!/bin/sh # Runs the container of one slot for one job (ExecStart of -# ci-runner@.service). Managed by Ansible (actions_runners). The slot's size -# is the part of its name before the last dash, and decides the container: +# ci-runner@.service). Managed by Ansible (actions_runners). Every size gets +# the same container of the environment image (files/ci-runner): the host's +# network (the registry pair and the Connect server on localhost, the +# overlay's names), no Docker socket, no privileges, since no job needs a +# Docker daemon. The size is the part of the slot's name before the last +# dash and decides the memory limit and whether the container shares the +# caches, bind-mounted from CACHE_DIR: # -# small, medium the host's network (the registry pair on localhost, the -# overlay's names), no Docker socket, no privileges -# large privileged, a network of its own, and a Docker daemon -# inside with its data on a volume removed with the -# container (ci-runner-dind, in the image): the jobs that -# need Docker meet an empty machine +# small nothing +# medium, large the pnpm store, and the directories of executables a job +# installs and a later job runs: mise's data, state and +# cache directories, where a repo's pins install (its node, +# its PostgreSQL), all three so that two jobs installing +# one version wait on mise's own lock; corepack's downloads +# of pnpm; and Playwright's browsers # -# From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from +# A small slot mounts no directory another job can write (the maintainer's +# decision): its jobs, plan, publish, deploy and housekeeping, hold the +# deploy and publish secrets, so they run only what the image carries, +# read-only, and install a repo's pin or its packages they need into their +# own container, which goes with the job. The medium and large slots run +# test and e2e, which hold none of those secrets, and share the caches among +# themselves (tests/runner-slot-mounts.sh holds the mounts of each size). +# +# From /etc/ci-runner/slot.env: IMAGE, CACHE_DIR and BUILDKIT_HOST; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for # none. The slot's runner config is /run/ci-runner/.env, minted by # ci-runner-jit before this. Hand-runnable as root, after ci-runner-jit: @@ -25,36 +39,27 @@ MEMORY= # shellcheck source=/dev/null . "/etc/ci-runner/size-$size.env" -set -- --rm --init --name "ci-runner-$instance" \ - --env-file "/run/ci-runner/$instance.env" \ - -e pnpm_config_store_dir=/cache/pnpm-store \ - -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" +home=/home/runner +set -- --rm --init --name "ci-runner-$instance" --network host \ + --env-file "/run/ci-runner/$instance.env" +if [ "$size" != small ]; then + set -- "$@" \ + -e pnpm_config_store_dir=/cache/pnpm-store \ + -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" \ + -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ + -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ + -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ + -v "$CACHE_DIR/corepack:$home/.cache/node/corepack" \ + -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" +fi [ -z "$MEMORY" ] || set -- "$@" --memory "$MEMORY" +# The host's BuildKit service, which a publish job builds its image through. +[ -z "${BUILDKIT_HOST:-}" ] || set -- "$@" -e "BUILDKIT_HOST=$BUILDKIT_HOST" # The host's Connect server, where the role runs one (/etc/ci-runner/connect.env: -# OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. A -# small or medium slot reaches it on loopback; the large slot, on a network -# of its own, at Docker's host gateway. -connect_host= +# OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. if [ -f /etc/ci-runner/connect.env ]; then # shellcheck source=/dev/null . /etc/ci-runner/connect.env - set -- "$@" --env-file /etc/ci-runner/connect.env - connect_host=127.0.0.1 - [ "$size" != large ] || connect_host=host.docker.internal - set -- "$@" -e "OP_CONNECT_HOST=http://$connect_host:$OP_CONNECT_PORT" + set -- "$@" --env-file /etc/ci-runner/connect.env -e "OP_CONNECT_HOST=http://127.0.0.1:$OP_CONNECT_PORT" fi -case "$size" in - large) - # The daemon inside starts as root and hands over to the runner user; - # a privileged container is root on the host already, so the engine's - # no-new-privileges buys nothing here and is lifted, which lets a job - # install system packages as it would on a machine of its own. - set -- "$@" --privileged --security-opt no-new-privileges=false --user 0 \ - --add-host host.docker.internal:host-gateway \ - -v /var/lib/docker "$IMAGE" ci-runner-dind - ;; - *) - set -- "$@" --network host "$IMAGE" ./run.sh - ;; -esac -exec /usr/bin/docker run "$@" +exec /usr/bin/docker run "$@" "$IMAGE" ./run.sh diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index 3b06da0a..8fdbd85c 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -1,38 +1,139 @@ -# The runner image of a runner host's container slots (§ 8 PLX-Delivery, -# actions_runners), one image for every size: the official runner image plus -# what the jobs expect of GitHub's runners and the official image leaves -# out. One container runs one job and is removed after it; nothing here is a -# cache or a secret. Built and pushed by runner-image.yml as -# ghcr.io/plexus-ms/ci-runner at the Plexus version, with provenance, or built -# on the host itself (actions_runners_image_build); Renovate moves the base. +# The environment image (§ 8 PLX-Delivery, actions_runners): the one machine +# a CI job runs in, on a runner host's slots, on the hybrid strategy's +# throwaway instances (plx-ci's user-data), and on an agent's Linux machine. +# One container runs one job and is removed after it; nothing here is a cache +# or a secret, and the token for a tenant's private packages is the job's to +# give. Built and pushed by runner-image.yml as ghcr.io/plexus-ms/ci-runner at +# the Plexus version, with provenance, or built on the host itself +# (actions_runners_image_build); Renovate moves the pins. # -# The tools the jobs install themselves (mise and what it pins, exo, crane, -# the 1Password CLI) stay the jobs' business: a slot runs the same steps as -# a GitHub runner, and a version here would be a second pin of each. +# Built on the runtime base of the app-nextjs template, digest and all, so +# that what a job builds here runs in the image that ships: the same Debian +# release, glibc and node (tests/runner-image-base.sh holds the two equal). +# What it holds: # -# A large slot runs a Docker daemon inside its container (ci-runner-dind). -# The official image carries Docker's static binaries, the daemon among -# them, and buildx; what the daemon and the jobs need beyond is here: -# iptables for the daemon's networks, and the compose plugin for the test -# stacks. -FROM ghcr.io/actions/actions-runner:2.338.2@sha256:6d0b2d80d80f143f77dcb676e50920100bbb547e39e883454d57f45ab8c31300 - -USER root -# git for actions/checkout (without it the action downloads a tarball and -# later git commands fail), jq and unzip for the jobs' own steps and the -# 1Password action, zstd for the cache actions, gnupg for apt keys, iptables -# for the daemon of a large slot, libatomic1 for node 26 and later, which -# mise installs for plx-ci where the repo pins no node (an operations repo). +# the runner GitHub's Actions runner and the libraries it needs, run +# as the user runner (1001), with sudo where the engine +# allows it (a slot's no-new-privileges does not) +# node, pnpm node from the base; pnpm and yarn through corepack, at +# the version a repo's packageManager names, downloaded +# into ~/.cache/node/corepack +# mise and, from mise.toml beside this file (mise's system +# config), plx-ci at the Plexus version, the vault's CLI, +# gh, crane and exo, the tools the small jobs installed +# for themselves; ci-mise-install beside it is a job's +# mise-action here +# docker's client with buildx, for an image build against a BuildKit +# elsewhere; no daemon, since no job here needs one +# packages git for actions/checkout, jq, unzip, zstd for the cache +# actions, xz and bzip2 for archives mise unpacks, +# libatomic1 for a node 26 mise installs, openssl, by +# which Prisma picks its engine at build time, and the +# libraries a Chromium needs, as Playwright lists them +# +# A repo's own pin of a tool wins once the job has run `mise install`: mise.toml +# here is the lowest of mise's configs, its tools sit in mise's system +# directory, which mise searches after its data directory, and the shims of +# both dispatch by the config of the directory a command runs in. A version +# the image lacks installs into mise's directories under ~/.local/share, +# ~/.local/state and ~/.cache. A runner host shares those between its medium +# and large slots, which run test and e2e, all three, so that two jobs +# installing one version wait on mise's own lock, and corepack's and +# Playwright's downloads and the pnpm store the same way. A small slot, +# whose jobs hold the deploy and publish secrets, and an instance, which runs +# one job, share none of them, the pnpm store included: there the image's +# own tools run, and a pin or a package they lack installs into the container +# and goes with it (actions_runners' ci-runner-slot). +# +# mise loads a project's config only under ~/_work, where the runner checks +# a job's repo out: mise.toml turns on paranoid mode for config, which ends +# mise's trust of everything under CI and of whatever a command it runs +# would trust implicitly, and MISE_TRUSTED_CONFIG_PATHS names _work. Any +# other config is refused at once, with no prompt and no trust recorded. +# +# Left out on purpose: +# +# browsers their version follows each repo's Playwright; a repo installs +# them into ~/.cache/ms-playwright, which a runner host shares +# between its medium and large slots like mise's directories +# PostgreSQL its version follows each repo's pin, which mise installs into +# its data directory +# libvips sharp brings its own; a system libvips at or above the +# minimum of a repo's sharp makes sharp compile itself, and the +# install fails +FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c + +ENV DEBIAN_FRONTEND=noninteractive +# The runner's own, as in the official runner image: it handles SIGTERM +# itself, and prints its worker log, which a slot's journal keeps. +ENV RUNNER_MANUALLY_TRAP_SIG=1 ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=1 + RUN apt-get update \ - && apt-get install -y --no-install-recommends ca-certificates curl git gnupg iptables jq libatomic1 unzip zstd \ + && apt-get install -y --no-install-recommends \ + bzip2 ca-certificates curl git gnupg jq libatomic1 openssl sudo unzip xz-utils zstd \ && rm -rf /var/lib/apt/lists/* -# renovate: datasource=github-releases depName=docker/compose -ARG COMPOSE_VERSION=v5.7.0 -ARG COMPOSE_SHA256=7758048ad38e580f22559603312874fec8bb638d021a9e64182385fc17cc12a2 -RUN curl -fsSL -o /usr/local/lib/docker/cli-plugins/docker-compose \ - "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-linux-x86_64" \ - && echo "${COMPOSE_SHA256} /usr/local/lib/docker/cli-plugins/docker-compose" | sha256sum -c - \ - && chmod 0755 /usr/local/lib/docker/cli-plugins/docker-compose -COPY --chmod=0755 ci-runner-dind /usr/local/bin/ci-runner-dind + +# renovate: datasource=github-releases depName=actions/runner +ARG RUNNER_VERSION=2.338.2 +ARG RUNNER_SHA256=baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40 +RUN useradd --create-home --uid 1001 --shell /bin/bash runner \ + && echo 'runner ALL=(ALL) NOPASSWD:ALL' >/etc/sudoers.d/runner \ + && cd /home/runner \ + && curl -fsSL -o runner.tgz \ + "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz" \ + && echo "${RUNNER_SHA256} runner.tgz" | sha256sum -c - \ + && tar -xzf runner.tgz && rm runner.tgz \ + && apt-get update && ./bin/installdependencies.sh && rm -rf /var/lib/apt/lists/* \ + && mkdir -p .local/share/mise .local/state/mise .cache/mise .cache/ms-playwright .cache/node/corepack \ + && chown -R runner:runner /home/runner + +# renovate: datasource=github-releases depName=docker/cli +ARG DOCKER_VERSION=29.10.1 +ARG DOCKER_SHA256=061642059fa7f2ed9b2f04a327a951cff4249585cf04b2661c2a6539197c9962 +# renovate: datasource=github-releases depName=docker/buildx +ARG BUILDX_VERSION=v0.39.1 +ARG BUILDX_SHA256=903090816da68f8bc1a2ff5346dd163a5adacfce4548d003c75df42cd47a9bf4 +RUN curl -fsSL -o /tmp/docker.tgz "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" \ + && echo "${DOCKER_SHA256} /tmp/docker.tgz" | sha256sum -c - \ + && tar -xzf /tmp/docker.tgz -C /usr/local/bin --strip-components 1 docker/docker && rm /tmp/docker.tgz \ + && mkdir -p /usr/local/lib/docker/cli-plugins \ + && curl -fsSL -o /usr/local/lib/docker/cli-plugins/docker-buildx \ + "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.linux-amd64" \ + && echo "${BUILDX_SHA256} /usr/local/lib/docker/cli-plugins/docker-buildx" | sha256sum -c - \ + && chmod 0755 /usr/local/lib/docker/cli-plugins/docker-buildx + +# The libraries alone: install-deps never downloads a browser. +# renovate: datasource=npm depName=playwright +ARG PLAYWRIGHT_VERSION=1.65.1 +RUN apt-get update \ + && npx --yes "playwright@${PLAYWRIGHT_VERSION}" install-deps chromium \ + && rm -rf /var/lib/apt/lists/* /root/.npm + +# corepack's shims for pnpm and yarn, which fetch the version a repo names on +# first use. All of them: a job's own `corepack enable` rewrites only a link +# that differs, so it then has nothing to write in /usr/local/bin, which the +# runner user may not. +ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 +RUN corepack enable + +# renovate: datasource=github-releases depName=jdx/mise +ARG MISE_VERSION=v2026.11.8 +ARG MISE_SHA256=32b6abe844efa43d37d7ac4ed21d2ec41e9479d66feb19b0db8d2c548cd6e36d +RUN curl -fsSL -o /usr/local/bin/mise "https://github.com/jdx/mise/releases/download/${MISE_VERSION}/mise-${MISE_VERSION}-linux-x64" \ + && echo "${MISE_SHA256} /usr/local/bin/mise" | sha256sum -c - \ + && chmod 0755 /usr/local/bin/mise +COPY mise.toml /etc/mise/config.toml +COPY --chmod=0755 ci-mise-install /usr/local/bin/ci-mise-install +RUN mise install --system && mise reshim --system && rm -rf /root/.cache /root/.local /root/.npm +# The data directory's shims first, then the system's: either dispatches by +# the config of the directory a command runs in. A job's checkout is under +# _work, the one place mise loads a project's config from (above); MISE_YES +# answers mise's other questions, as mise-action has it on the forge. +ENV PATH=/home/runner/.local/share/mise/shims:/usr/local/share/mise/shims:$PATH \ + MISE_TRUSTED_CONFIG_PATHS=/home/runner/_work MISE_YES=1 + USER runner WORKDIR /home/runner +# Not the base's node entrypoint: the runner, one job. +ENTRYPOINT [] +CMD ["./run.sh"] diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install b/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install new file mode 100644 index 00000000..1ab07bbc --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install @@ -0,0 +1,27 @@ +#!/bin/sh +# What jdx/mise-action does for a job on the forge's runners, for a job in the +# environment image (the reusable workflows call it where runner.environment +# is not github-hosted), without what the image already has: no download of +# mise, and no restore of the forge's cache into mise's directories, which a +# runner host shares between its slots. In the directory of the repo's +# config, run as a step: +# +# ci-mise-install [TOOL...] +# +# installs the repo's pins, all of them or the TOOLs named, with +# `mise install`, then hands the later steps the repo's environment the way +# mise-action does: the values mise marks for redaction masked, every +# variable of `mise env` but PATH into GITHUB_ENV, and the PATH entries mise +# manages (the tools' and the config's `_.path`) into GITHUB_PATH, last +# first, since the runner puts each line it reads in front of the rest. +set -eu +: "${GITHUB_ENV:?a step of a GitHub Actions job sets GITHUB_ENV}" "${GITHUB_PATH:?and GITHUB_PATH}" + +mise install "$@" + +mise env --redacted --json | jq -r '.[] | "::add-mask::" + .' +# A delimiter no value holds, as the runner's multiline syntax requires. +delimiter="mise_env_$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')" +mise env --json | jq -r --arg d "$delimiter" \ + 'to_entries[] | select(.key != "PATH") | "\(.key)<<\($d)\n\(.value)\n\($d)"' >>"$GITHUB_ENV" +mise env --paths | tac >>"$GITHUB_PATH" diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind b/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind deleted file mode 100755 index bd88eff8..00000000 --- a/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# The entry of a large slot's container (actions_runners, ci-runner-slot): a -# Docker daemon of the container's own, then the runner as the runner user. -# Started as root in a privileged container; the daemon's data is the volume -# at /var/lib/docker, which goes with the container, so every job meets an -# empty daemon and leaves nothing behind. -set -eu - -# cgroup v2: a cgroup with processes of its own cannot hand controllers to -# children, and the daemon needs them for its containers' limits. Move -# everything here into a child first, then delegate. -if [ -f /sys/fs/cgroup/cgroup.controllers ]; then - mkdir -p /sys/fs/cgroup/init - xargs -rn1 /sys/fs/cgroup/init/cgroup.procs 2>/dev/null || : - sed -e 's/ / +/g' -e 's/^/+/' /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null || : -fi - -dockerd --group docker >/var/log/dockerd.log 2>&1 & -for _ in $(seq 1 60); do - docker info >/dev/null 2>&1 && break - sleep 1 -done -if ! docker info >/dev/null 2>&1; then - echo "ci-runner-dind: the Docker daemon did not come up" >&2 - tail -n 40 /var/log/dockerd.log >&2 || : - exit 1 -fi - -cd /home/runner -export HOME=/home/runner USER=runner LOGNAME=runner -exec setpriv --reuid runner --regid runner --init-groups ./run.sh diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml new file mode 100644 index 00000000..04c0c0ee --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -0,0 +1,28 @@ +# The tools the environment image carries (Dockerfile beside this file), as +# mise's system config, /etc/mise/config.toml: the lowest of mise's configs, so +# that a repo's own pin of any of them wins. Installed at build time into mise's +# system directory, which mise searches after its data directory and never +# writes; a version a repo pins and the image lacks installs into the data +# directory, which a runner host shares between its medium and large slots; in +# a small slot or on an instance it stays in the job's container. +[tools] +# plx-ci at the Plexus version: the pin is written with each version, never by +# the update bot (§ 1 PLX-Updates); allow_low_downloads only waives npm's +# young-package heuristics. It runs on the base image's node. +"npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } +# The vault's CLI, which load-secrets-action uses where it finds one. +"aqua:1password/cli" = "2.42.0" +# What the small jobs installed for themselves: gh for plx-update, crane for +# the forge's registry, exo for the hybrid strategy's instances. +gh = "2.106.0" +crane = "0.22.1" +"github:exoscale/cli" = { version = "1.103.2", bin = "exo" } + +[settings] +# Trust for a project's config is the content's, never automatic, never by CI +# and never by --yes, so only MISE_TRUSTED_CONFIG_PATHS (the job's checkout +# under _work) loads without a `mise trust`, and no trust mise grants on its +# own is written where another job sharing mise's directories would read it. +paranoid = ["config"] +# The image's mise moves with the image, by its pin: no warning about a newer one in every job's log. +disable_update_warning = true diff --git a/ansible/ci/roles/actions_runners/tasks/buildkit.yml b/ansible/ci/roles/actions_runners/tasks/buildkit.yml new file mode 100644 index 00000000..60c7ced3 --- /dev/null +++ b/ansible/ci/roles/actions_runners/tasks/buildkit.yml @@ -0,0 +1,166 @@ +--- +# The BuildKit service (defaults: actions_runners_buildkit_*): buildkitd from +# BuildKit's release, its configuration in BuildKit's default place, and the +# unit ci-buildkit. Started or restarted at the end, without a handler, so +# that the service answers once this file has run, and restarted by what is +# on disk rather than by what this run changed, so that a run that failed +# halfway leaves no daemon behind its files. +- name: Which buildkitd is installed + ansible.builtin.command: + cmd: /usr/local/bin/buildkitd --version + register: actions_runners_buildkit_installed + changed_when: false + failed_when: false + check_mode: false + +# `buildkitd --version` prints `buildkitd github.com/moby/buildkit `. +- name: Install buildkitd from the pinned release + when: actions_runners_buildkit_version not in actions_runners_buildkit_installed.stdout.split() + vars: + tarball: /var/tmp/buildkit-{{ actions_runners_buildkit_version }}.linux-amd64.tar.gz + block: + - name: Download the release + ansible.builtin.get_url: + url: >- + https://github.com/moby/buildkit/releases/download/{{ actions_runners_buildkit_version + }}/buildkit-{{ actions_runners_buildkit_version }}.linux-amd64.tar.gz + dest: "{{ tarball }}" + checksum: sha256:{{ actions_runners_buildkit_sha256 }} + owner: root + group: root + mode: "0600" + + # The daemon, the runc it runs build steps with, the CNI plugins of its + # bridge (found on PATH by their names), and the client; the tarball's + # emulators are left out, since the builds are for the host's platform. + - name: Unpack buildkitd, buildkit-runc, the bridge's plugins and buildctl + ansible.builtin.unarchive: + src: "{{ tarball }}" + dest: /usr/local/bin + remote_src: true + include: + - bin/buildkitd + - bin/buildkit-runc + - bin/buildkit-cni-bridge + - bin/buildkit-cni-firewall + - bin/buildkit-cni-host-local + - bin/buildkit-cni-loopback + - bin/buildctl + extra_opts: [--strip-components=1] + owner: root + group: root + when: not ansible_check_mode # the module needs the tarball, which check mode does not fetch + + - name: Remove the download + ansible.builtin.file: + path: "{{ tarball }}" + state: absent + +- name: Create the configuration directory + ansible.builtin.file: + path: /etc/buildkit + state: directory + owner: root + group: root + mode: "0755" + +# Both workers are named: the containerd worker would otherwise switch itself +# on beside the OCI worker wherever Docker's containerd socket exists. The +# bridge gives each build step a network namespace of its own instead of +# the host's, BuildKit's fallback without a CNI configuration. The build +# steps' cgroups go below the unit's own (Delegate=), so that its MemoryMax +# covers them; BuildKit places each at /buildkit/. +- name: Configure buildkitd + ansible.builtin.copy: + dest: /etc/buildkit/buildkitd.toml + owner: root + group: root + mode: "0644" + content: | + # Managed by Ansible (actions_runners); the role's defaults say why. + [grpc] + address = ["tcp://127.0.0.1:{{ actions_runners_buildkit_port }}"] + + [worker.oci] + enabled = true + networkMode = "bridge" + {% if actions_runners_buildkit_subnet %} + bridgeSubnet = "{{ actions_runners_buildkit_subnet }}" + {% endif %} + gc = true + maxUsedSpace = "{{ actions_runners_buildkit_cache_max }}" + defaultCgroupParent = "system.slice/ci-buildkit.service" + + [worker.containerd] + enabled = false + register: actions_runners_buildkit_config + +# Type=notify: buildkitd reports ready once it listens. The daemon runs in +# the subgroup `daemon` of the unit's cgroup and the build steps beside it, +# since a cgroup that holds a process cannot hand controllers to children. +# The limit holds no swap besides, or a build over it would swap instead of +# failing. +- name: Install the BuildKit unit + ansible.builtin.copy: + dest: /etc/systemd/system/ci-buildkit.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=BuildKit for the publish jobs of the CI runner slots + Documentation=https://github.com/moby/buildkit + + [Service] + Type=notify + ExecStart=/usr/local/bin/buildkitd + Delegate=yes + DelegateSubgroup=daemon + MemoryMax={{ actions_runners_buildkit_memory | default('infinity', true) }} + MemorySwapMax={{ 0 if actions_runners_buildkit_memory else 'infinity' }} + # buildkitd ends with status 1 on SIGTERM and SIGINT, the signals it + # handles; it leaves SIGHUP to Go's default, death by the signal, + # which systemd counts as a clean stop. A restart or a reboot then + # marks it failed for nobody, and a crash with any status still does. + KillSignal=SIGHUP + Restart=always + RestartSec=5s + + [Install] + WantedBy=multi-user.target + register: actions_runners_buildkit_unit + +# The running daemon is what is on disk only if it started after the last of +# its files changed. The change time, not the modification time: tar keeps +# the release's modification times. +- name: Find the files that changed since buildkitd started + ansible.builtin.shell: + executable: /bin/bash + cmd: | + set -euo pipefail + started=$(systemctl show -P ExecMainStartTimestamp --timestamp=us+utc ci-buildkit.service) + [ -n "$started" ] || exit 0 + started=$(date -d "$started" +%s%6N) + for f in /usr/local/bin/buildkitd /usr/local/bin/buildkit-runc \ + /etc/buildkit/buildkitd.toml /etc/systemd/system/ci-buildkit.service; do + changed=$(stat -c %.6Z "$f" 2>/dev/null) || { echo "$f"; continue; } + [ "${changed/./}" -lt "$started" ] || echo "$f" + done + register: actions_runners_buildkit_newer + changed_when: false + check_mode: false + +# A dry run writes nothing, so there what this run would change stands in +# for the files; and it has no unit to look up while the unit is new. +- name: Start the BuildKit service, restarted when it is not what is on disk + when: not (ansible_check_mode and actions_runners_buildkit_unit is changed) + vars: + restart: >- + {{ actions_runners_buildkit_newer.stdout | length > 0 + or (ansible_check_mode and (actions_runners_buildkit_config is changed + or actions_runners_buildkit_unit is changed)) }} + ansible.builtin.systemd_service: + name: ci-buildkit.service + enabled: true + daemon_reload: "{{ restart | bool }}" + state: "{{ 'restarted' if restart | bool else 'started' }}" diff --git a/ansible/ci/roles/actions_runners/tasks/connect.yml b/ansible/ci/roles/actions_runners/tasks/connect.yml index 8ebe4aac..782501cd 100644 --- a/ansible/ci/roles/actions_runners/tasks/connect.yml +++ b/ansible/ci/roles/actions_runners/tasks/connect.yml @@ -61,9 +61,8 @@ # What a slot's container gets, so that the job's secret reads go to the # server: load-secrets-action prefers Connect over the service account token -# the workflow also sets. The large slot has a network of its own and reaches -# the host at Docker's host gateway; the small and medium slots share the -# host's network and use loopback (ci-runner-slot sets the host). +# the workflow also sets. Every slot shares the host's network and uses +# loopback (ci-runner-slot sets the host). - name: Write the slots' Connect token when: actions_runners_connect_token | length > 0 no_log: true diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 7ddf7d66..b2d6f2c4 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -118,7 +118,7 @@ owner: "{{ actions_runners_runner_uid }}" group: "{{ actions_runners_runner_uid }}" mode: "0755" - loop: ["", pnpm-store] + loop: ["", pnpm-store, mise, mise/data, mise/state, mise/cache, corepack, ms-playwright] - name: Pull the runner image when: not actions_runners_image_build @@ -180,8 +180,14 @@ changed_when: actions_runners_connect_removed.stdout | length > 0 failed_when: false -# What a slot's container is made of: the image and the cache for every -# slot, the memory limit per size. ci-runner-slot reads both at the start of +- name: The BuildKit service + ansible.builtin.include_tasks: buildkit.yml + +# What a slot's container is made of: the image for every slot, the +# cache directory a medium or large slot mounts from, and where the host's +# BuildKit service listens, which every slot's jobs are told as BUILDKIT_HOST +# (a publish builds through it), from the one variable the service's +# configuration takes its port from; the memory limit per size. ci-runner-slot reads both at the start of # a container, and the JIT script reads where to register, so a change to any # of them restarts the slots (the handler): a job in flight on this host # fails and is run again by hand, which a configure run on a runner host @@ -196,6 +202,7 @@ content: | IMAGE={{ actions_runners_image }} CACHE_DIR={{ actions_runners_cache_dir }} + BUILDKIT_HOST=tcp://127.0.0.1:{{ actions_runners_buildkit_port }} notify: Restart the slots - name: Write each size's limit diff --git a/hk.pkl b/hk.pkl index df59babb..8f7c3682 100644 --- a/hk.pkl +++ b/hk.pkl @@ -10,16 +10,16 @@ hooks { check = "mise :lint {{ files }}" fix = "mise :lint --write {{ files }}" } - ["ops"] { - glob = List("ansible/**", "tests/**", ".github/workflows/*.yml") - check = "mise :check-ops" + ["check"] { + depends = "lint" + check = "mise :check" } } } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/mise.toml b/mise.toml index 494d239c..9052579a 100644 --- a/mise.toml +++ b/mise.toml @@ -45,23 +45,66 @@ _.path = ["{{config_root}}/node_modules/.bin"] # Contract verbs (§ 3 PLX-Repo) [tasks.dev] -description = "No-op: nothing to start; the roles are applied by tenant playbooks, the workflows run on the forge" +description = "No-op: nothing to start; the roles are applied by tenant playbooks, the workflows run on the forge; a name is accepted and ignored, it applies to the whole repo" +usage = 'arg "[name]" hide=#true' run = 'echo "dev: nothing to start in tooling"' [tasks.build] depends = ["install"] -description = "Build the packages (the collection and the workflows ship as source)" -run = "turbo run build" +description = "Build the packages (the collection and the workflows ship as source), each after the workspace packages it depends on" +usage = 'arg "[name]" help="Package to build, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "build: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "build: no package $usage_name under packages/" >&2; exit 1; } +fi +turbo run build ${dir:+--filter="{./$dir}"} +''' + +[tasks.check] +depends = ["lint", "check-ops", "check-requirements", "check-doctor"] +description = "Run every static check, none of them a test of the code under test (check-ops runs a script against a stub): lint, the packages' types, the workflows, the collection, the citations, the repo contract" +usage = 'arg "[name]" help="Package to check, by its directory name under packages/ (e.g. lib, defaults to all)"' +# The repo-wide checks cannot be scoped; the name scopes the types of the packages. +run = 'mise run check-js ${usage_name:+"$usage_name"}' + +[tasks.test] +depends = ["install"] +description = "Run check, then the unit tests of the packages (the roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" +usage = 'arg "[name]" help="Package to test, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "test: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "test: no package $usage_name under packages/" >&2; exit 1; } +fi +mise run check ${usage_name:+"$usage_name"} +turbo run test ${dir:+--filter="{./$dir}"} +''' -[tasks.verify] -depends = ["lint", "check", "test", "newborn"] -description = "Perform all steps that verify code quality" +[tasks.e2e] +depends = ["build"] +description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verbs run (newborns/); it neither checks nor tests this repo; a name is accepted and ignored, it applies to the whole repo" +usage = 'arg "[name]" hide=#true' +# Never a turbo task, so never cached: what it exercises is the network (the +# tools a newborn installs). The packages of this workspace are packed once and +# served to the newborns by a registry of the run's own, so a newborn runs the +# plx being cut, also where its version is not on npm yet (newborns/helpers.ts). +env = { NEWBORN_TARBALLS = "{{config_root}}/node_modules/.cache/newborn-tarballs" } +run = ["node newborns/pack.ts", "node --test newborns/*.test.ts"] # The upstream's verb (§ 1.5 PLX) [tasks.ship] -depends = ["build", "newborn"] -description = "Cut the version from this checkout's own build, after every template has passed as a newborn: plx-dev ship over the workspace this checkout sits in (plexus-ms/tooling under it)" +depends = ["build", "e2e"] +description = "Cut the version from this checkout's own build, after every template has passed as a newborn (e2e): plx-dev ship over the workspace this checkout sits in (plexus-ms/tooling under it)" # Never a published package: the tool that releases the version is the code at # main, built here, so it cannot lag behind the release it cuts. Flags follow # `--`: `mise ship -- -n` previews, `mise ship -- -y` runs unattended. @@ -85,27 +128,24 @@ arg "" var=#true default="." help="Files or directories to lint (defaults ''' run = "biome check ${usage_write:+--write} --no-errors-on-unmatched $usage_paths" -[tasks.check] -depends = ["check-js", "check-ops", "check-requirements"] -description = "Run static checks on the codebase: the packages, the workflows, the collection, the citations" - -[tasks.newborn] -depends = ["build"] -description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verify run (newborns/)" -hide = true -# Never a turbo task, so never cached: what it exercises is the network (the -# tools a newborn installs). The packages of this workspace are packed once and -# served to the newborns by a registry of the run's own, so a newborn runs the -# plx being cut, also where its version is not on npm yet (newborns/helpers.ts). -env = { NEWBORN_TARBALLS = "{{config_root}}/node_modules/.cache/newborn-tarballs" } -run = ["node newborns/pack.ts", "node --test newborns/*.test.ts"] - [tasks.check-js] -depends = ["install"] +depends = ["build"] description = "Type-check the packages" hide = true -usage = 'arg "[package]" help="Package to check (defaults to all)"' -run = 'turbo run check ${usage_package:+--filter=$usage_package}' +# After the build, not beside it: under TURBO_FORCE two turbo runs would each +# rebuild lib/dist, while the other, or plx itself, reads it. +usage = 'arg "[name]" help="Package to check, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "check: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "check: no package $usage_name under packages/" >&2; exit 1; } +fi +turbo run check ${dir:+--filter="{./$dir}"} +''' [tasks.check-requirements] depends = ["build"] @@ -124,8 +164,14 @@ else fi ''' +[tasks.check-doctor] +depends = ["build"] +description = "plx doctor over this repo, with the workspace's own build: the repo holds itself to the repo contract it ships" +hide = true +run = "pnpm plx doctor" + [tasks.check-ops] -description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role" +description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base; what each size of slot mounts, and that every slot is told where the BuildKit service listens" hide = true run = [ 'actionlint', @@ -134,6 +180,9 @@ run = [ 'ansible-playbook --syntax-check -i tests/inventory.yml tests/all-roles.yml', 'ansible-playbook --syntax-check -i tests/inventory.yml plexus.platform.playbook plexus.infrastructure.playbook plexus.ci.playbook', './tests/all-roles-listed.sh', + './tests/runner-image-base.sh', + './tests/runner-slot-mounts.sh', + './tests/runner-slot-buildkit.sh', ] # ANSIBLE_HOME keeps ansible-lint's cache and every collections path inside the # project, so a plexus.* collection installed user-wide (a tenant's pin) never @@ -141,9 +190,3 @@ run = [ # puts the four plexus.* collections there and installs what their galaxy.yml # files depend on, which no other path would supply. env = { ANSIBLE_HOME = "{{config_root}}/.ansible", ANSIBLE_COLLECTIONS_PATH = "{{config_root}}/.ansible/collections" } - -[tasks.test] -depends = ["install"] -description = "Run tests on the packages (the roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" -usage = 'arg "[package]" help="Package to test (defaults to all)"' -run = 'turbo run test ${usage_package:+--filter=$usage_package}' diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 63f4a5c3..d154f073 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -1,25 +1,47 @@ -// A newborn app of the Next.js template passes its repo's own `verify`: the +// A newborn app of the Next.js template passes its repo's own `test`: the // repo is a newborn of the Turborepo template with updates beside it, an app // of each profile is created inside it by `plx new`, taking the tenant from // the repo's marker. // An app created where no repo's marker gives a tenant is refused. Each app's // compose file refuses an unset loopback port and publishes a set one // (PLX-App/LoopbackPort), which needs docker compose. +// An app's `build`, run by the repo's verb, leaves one directory that serves +// the whole app wherever it lies, started as the standalone server, and is +// what the build task's cache holds. The image built from that directory alone +// holds it and nothing else, and becomes healthy under the app's compose file, +// a stateful app migrated first from what the directory holds; that needs docker. import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, open, plxNew, sh, tryRun, verify } from './helpers.ts'; +import { born, close, freePort, open, pass, plxNew, put, relock, sh, start, tryRun } from './helpers.ts'; let here = ''; let repo = ''; const PROFILES = ['stateless', 'stateful']; +/** A one-pixel PNG, for the app's public/ and its image optimiser. */ +const PIXEL = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); + +/** The directory an app's build leaves. */ +const output = (app: string) => join(repo, 'apps', app, '.next', 'standalone'); + before(async () => { here = await open('app-nextjs'); repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); + // The stateful app has no public/ until its image test, so that a build without one is shown too. + put(join(repo, 'apps', 'stateless'), { 'public/pixel.png': PIXEL }); + await relock(repo); + await sh('mise', ['exec', '--', 'pnpm', 'install'], repo); + // Tracked, as in a checkout: Turbo hashes what git tracks, and an untracked app's build output with it. + await sh('git', ['add', '-A'], repo); }); after(close); @@ -44,8 +66,200 @@ for (const profile of PROFILES) { }); } -test('the repo around the apps passes its own verify', async () => { - // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. - await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); - await verify(repo, 'acme'); +test('an app builds into one directory that serves all of it, its static files and public/ included, wherever it lies', async () => { + await sh('mise', ['run', 'build', 'stateless'], repo); + const moved = join(here, 'moved'); + cpSync(output('stateless'), moved, { recursive: true, verbatimSymlinks: true }); + const port = await freePort(); + const url = (path: string) => `http://127.0.0.1:${port}${path}`; + const server = await start( + process.execPath, + [join(moved, 'apps', 'stateless', 'server.js')], + here, + { PORT: String(port), HOSTNAME: '127.0.0.1' }, + async () => (await fetch(url('/healthz'))).ok, + ); + try { + const page = await fetch(url('/')); + assert.equal(page.status, 200); + const html = await page.text(); + assert.match(html, /

@acme\/stateless<\/h1>/); + const asset = /\/_next\/static\/[^"]+\.js/.exec(html)?.[0]; + assert.ok(asset, html); + assert.equal((await fetch(url(asset))).status, 200, asset); + assert.equal((await fetch(url('/pixel.png'))).status, 200); + const image = await fetch(url('/_next/image?url=%2Fpixel.png&w=64&q=75'), { headers: { accept: 'image/webp' } }); + assert.equal(image.status, 200); + assert.equal(image.headers.get('content-type'), 'image/webp'); + } finally { + await server.stop(); + rmSync(moved, { recursive: true, force: true }); + } +}); + +test('that directory is all the build leaves: a cache hit restores it whole', async () => { + const dotNext = join(repo, 'apps', 'stateless', '.next'); + await sh('mise', ['run', 'build', 'stateless'], repo); + rmSync(dotNext, { recursive: true, force: true }); + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo), /cache hit/); + assert.deepEqual(readdirSync(dotNext), ['standalone']); + const app = join(output('stateless'), 'apps', 'stateless'); + for (const path of ['server.js', 'package.json', '.next/BUILD_ID', '.next/static', 'public/pixel.png']) + assert.ok(existsSync(join(app, path)), path); +}); + +/** Turbo's hash of each task of an app, by task name, from a dry run in mise's environment, with another platform where one is given. */ +async function hashes(app: string, platform?: string): Promise> { + const dry = `mise exec -- env ${platform ? `PLX_PLATFORM=${platform}` : ''} turbo run build check test --filter=@acme/${app} --dry=json`; + const plan = JSON.parse(await sh('sh', ['-c', `${dry} 2>/dev/null`], repo)); + return Object.fromEntries(plan.tasks.map((task: { task: string; hash: string }) => [task.task, task.hash])); +} + +test("the platform is in the hash of an app's build, and not in its check's", async () => { + const linux = await hashes('stateless', 'linux-x64'); + const mac = await hashes('stateless', 'macos-arm64'); + assert.notEqual(linux.build, mac.build); + assert.equal(linux.check, mac.check); +}); + +test("the app's build adds the platform to what the root declares for build, and keeps its env, inputs and dependsOn", async () => { + // Turbo reads the comment lines of the root's turbo.json, JSON does not. + const text = readFileSync(join(repo, 'turbo.json'), 'utf8').replace(/^\s*\/\/.*$/gm, ''); + const declared = JSON.parse(text).tasks.build; + const dry = 'mise exec -- turbo run build --filter=@acme/stateless --dry=json 2>/dev/null'; + const [resolved] = JSON.parse(await sh('sh', ['-c', dry], repo)).tasks; + assert.deepEqual(resolved.resolvedTaskDefinition.dependsOn, declared.dependsOn); + assert.deepEqual(resolved.resolvedTaskDefinition.env.sort(), [...(declared.env ?? []), 'PLX_PLATFORM'].sort()); + const { build } = await hashes('stateless'); + assert.notEqual((await hashes('stateless', 'none-none')).build, build); + // The root's inputs leave test files out of the build; a source file is in. + const app = join(repo, 'apps', 'stateless', 'src'); + try { + put(app, { 'kept.test.ts': 'export {};\n' }); + await sh('git', ['add', '-A'], repo); + assert.equal((await hashes('stateless')).build, build); + put(app, { 'kept.ts': 'export {};\n' }); + await sh('git', ['add', '-A'], repo); + assert.notEqual((await hashes('stateless')).build, build); + } finally { + for (const file of ['kept.test.ts', 'kept.ts']) rmSync(join(app, file), { force: true }); + await sh('git', ['add', '-A'], repo); + } +}); + +test("the build ID is the hash of the app's build, and a build outside Turbo or without the platform fails", async () => { + await sh('mise', ['run', 'build', 'stateless'], repo); + const { build } = await hashes('stateless'); + assert.equal(readFileSync(join(output('stateless'), 'apps', 'stateless', '.next', 'BUILD_ID'), 'utf8'), build); + const outside = await tryRun('mise', ['exec', '--', 'pnpm', '--filter', '@acme/stateless', 'run', 'build'], repo); + assert.equal(outside.ok, false, outside.output); + assert.match(outside.output, /TURBO_HASH= PLX_PLATFORM=\S/); + const bare = ['exec', '--', 'env', '-u', 'PLX_PLATFORM', 'turbo', 'run', 'build', '--filter=@acme/stateless']; + const unplatformed = await tryRun('mise', bare, repo); + assert.equal(unplatformed.ok, false, unplatformed.output); + assert.match(unplatformed.output, /TURBO_HASH=[0-9a-f]{16} PLX_PLATFORM=$/m); +}); + +test('the build does not type-check, so a hit and a miss of one hash agree, and check does', async () => { + const typo = join(repo, 'apps', 'stateless', 'src', 'typo.test.ts'); + put(repo, { 'apps/stateless/src/typo.test.ts': "export const n: number = 'not a number';\n" }); + await sh('git', ['add', '-A'], repo); + try { + // A test file is no input of the build, so the hash is the one built before, and the miss is forced. + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo), /cache hit/); + const miss = ['exec', '--', 'turbo', 'run', 'build', '--filter=@acme/stateless', '--force']; + assert.match(await sh('mise', miss, repo), /cache bypass/); + const check = await tryRun('mise', ['run', 'check', 'stateless'], repo); + assert.equal(check.ok, false, check.output); + assert.match(check.output, /typo\.test\.ts.*TS2322/); + } finally { + rmSync(typo, { force: true }); + await sh('git', ['add', '-A'], repo); + } +}); + +test("an app's tests run by the repo's verb, and pass while it has none", async () => { + for (const profile of PROFILES) + assert.match(await sh('mise', ['run', 'test', profile], repo), new RegExp(`@acme/${profile}:test`)); +}); + +/** Every path below `dir`, sorted, as Node lists it: the same call inside an image and outside. */ +const LIST = "console.log(JSON.stringify(require('fs').readdirSync(process.argv[1], { recursive: true }).sort()))"; + +for (const profile of PROFILES) { + test(`the image of a ${profile} app holds the directory and nothing else, and becomes healthy under its compose file`, async () => { + const app = join(repo, 'apps', profile); + if (profile === 'stateful') { + // What the migrate service runs is put into the directory by the build, here a file Next traces in. + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + manifest.scripts.migrate = 'node migrate.mjs'; + const config = readFileSync(join(app, 'next.config.ts'), 'utf8').replace( + "output: 'standalone',", + "output: 'standalone',\n outputFileTracingIncludes: { '/*': ['./migrate.mjs'] },", + ); + put(app, { + 'package.json': manifest, + 'next.config.ts': config, + 'migrate.mjs': "console.log('migrated in', process.cwd());\n", + 'public/pixel.png': PIXEL, + }); + await sh('git', ['add', '-A'], repo); + } + await sh('mise', ['run', 'build', profile], repo); + const id = randomBytes(4).toString('hex'); + const tag = `plx-newborn-${profile}:${id}`; + // Limits for every container, on a machine others share; the build runs nothing and needs none. + const limits = { cpus: 4, mem_limit: '6g', pids_limit: 1000 }; + // As the Dockerfile's header says: the directory is the context. + const dockerfile = join(app, 'docker', 'Dockerfile'); + await sh('docker', ['build', '--build-arg', `APP=${profile}`, '-f', dockerfile, '-t', tag, output(profile)], repo); + try { + const config = JSON.parse(await sh('docker', ['image', 'inspect', '--format', '{{json .Config}}', tag], here)); + assert.equal(config.User, 'node'); + assert.deepEqual(Object.keys(config.ExposedPorts ?? {}), ['3000/tcp']); + assert.ok(config.Env.includes('NODE_ENV=production'), config.Env.join(' ')); + const run = ['run', '--rm', '--cpus', '4', '--memory', '6g', '--pids-limit', '1000', '--entrypoint', 'node']; + const held = JSON.parse( + (await sh('docker', [...run, tag, '-e', LIST, '/repo'], here)).trim().split('\n').at(-1) ?? '', + ); + const local = JSON.parse((await sh(process.execPath, ['-e', LIST, output(profile)], here)).trim()); + assert.deepEqual(held, local); + assert.deepEqual( + held.filter((path: string) => !path.split('/').includes('node_modules') && /(? { + await pass(repo, 'acme', 'test'); }); diff --git a/newborns/caches.ts b/newborns/caches.ts new file mode 100644 index 00000000..a09a8cfc --- /dev/null +++ b/newborns/caches.ts @@ -0,0 +1,156 @@ +// Turbo's remote caches for the newborn tests, as the step turbo-cache of this +// repo starts them in a job: an S3 stand-in, RustFS in a container published +// on a free loopback port, with the tenant acme's buckets, and the cache +// server the step's action starts, its binary fetched at the commit the step +// pins, each from an empty environment and an empty directory so that no +// TURBO_TOKEN reaches it but the one given. Every server's log is kept: what a +// test reads to count the requests a job made. +import { type ChildProcess, spawn } from 'node:child_process'; +import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { arch, platform } from 'node:os'; +import { join } from 'node:path'; +import { sh, tryRun } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); +const RUSTFS = 'rustfs/rustfs:1.0.5'; +const KEY = 'newborn-access'; +const SECRET = 'newborn-secret-not-a-real-one'; + +/** Waits until `url` answers 200, or throws after a minute. */ +async function answers(url: string): Promise { + const until = Date.now() + 60_000; + for (;;) { + try { + if ((await fetch(url)).ok) return; + } catch {} + if (Date.now() > until) throw new Error(`${url} did not answer`); + await new Promise((resolve) => setTimeout(resolve, 250)); + } +} + +/** The S3 stand-in and the cache servers started against it. */ +export interface Caches { + /** The stand-in's address, `http://127.0.0.1:`. */ + s3: string; + /** One S3 call to the stand-in, signed by curl. */ + call(method: string, path: string): Promise; + /** The keys of a bucket below a team, as the server writes them: `/`. */ + keys(bucket: string, team?: string): Promise; + /** A cache server for `bucket` on `port`, with `token` where given; resolves with its log once it answers. */ + serve(bucket: string, port: number, token?: string): Promise; + /** Kills the servers and removes the stand-in. */ + stop(): Promise; +} + +/** The server's binary for this machine, at the commit of the action the step pins, into `dir`. */ +async function fetchServer(dir: string): Promise { + const step = readFileSync(join(STEP, 'action.yml'), 'utf8'); + const sha = /uses: brunojppb\/turbo-cache-server@([0-9a-f]{40})/.exec(step)?.[1]; + if (!sha) throw new Error('the step pins no brunojppb/turbo-cache-server by commit'); + // The names the action's own action/util.mjs picks. + const name = platform() === 'darwin' ? `decay-darwin-${arch()}` : `decay-${arch()}`; + const answer = await fetch(`https://raw.githubusercontent.com/brunojppb/turbo-cache-server/${sha}/action/${name}`); + if (!answer.ok) throw new Error(`no server binary ${name} at ${sha}: ${answer.status}`); + const path = join(dir, name); + writeFileSync(path, Buffer.from(await answer.arrayBuffer())); + chmodSync(path, 0o755); + return path; +} + +/** RustFS with `buckets`, and the server's binary, in `dir`. */ +export async function startCaches(dir: string, buckets: string[]): Promise { + const servers: ChildProcess[] = []; + // The container's id, the one line of its kind: a first run pulls the image and prints its progress too. + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '-p', + '127.0.0.1::9000', + '-e', + `RUSTFS_ACCESS_KEY=${KEY}`, + '-e', + `RUSTFS_SECRET_KEY=${SECRET}`, + RUSTFS, + ], + dir, + ) + ).match(/^[0-9a-f]{64}$/m); + const container = started?.[0] ?? ''; + const stop = async () => { + for (const child of servers) + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + if (container) await tryRun('docker', ['rm', '-f', container], dir); + }; + try { + if (!container) throw new Error('docker run printed no container id'); + const published = (await sh('docker', ['port', container, '9000/tcp'], dir)).trim().split('\n')[0] ?? ''; + const s3 = `http://${published}`; + const call = (method: string, path: string) => + sh( + 'curl', + ['-fsS', '-X', method, '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`, `${s3}/${path}`], + dir, + ); + const until = Date.now() + 60_000; + const listing = ['-fsS', '-o', '/dev/null', '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`]; + while ((await tryRun('curl', [...listing, `${s3}/`], dir)).ok === false) { + if (Date.now() > until) throw new Error(`the S3 stand-in at ${s3} did not come up`); + await new Promise((resolve) => setTimeout(resolve, 500)); + } + for (const bucket of buckets) await call('PUT', bucket); + const binary = await fetchServer(dir); + return { + s3, + call, + keys: async (bucket, team = 'acme-web') => { + const xml = await call('GET', `${bucket}?list-type=2&prefix=${team}/`); + return [...xml.matchAll(/([^<]*)<\/Key>/g)].map((m) => m[1] ?? ''); + }, + serve: async (bucket, port, token) => { + const cwd = join(dir, `server-${port}`); + mkdirSync(cwd); + const child = spawn(binary, [], { + cwd, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { + PATH: '/usr/bin:/bin', + OTEL_SDK_DISABLED: 'true', + PORT: String(port), + S3_ENDPOINT: s3, + S3_REGION: 'us-east-1', + S3_BUCKET_NAME: bucket, + S3_ACCESS_KEY: KEY, + S3_SECRET_KEY: SECRET, + S3_USE_PATH_STYLE: 'true', + ...(token ? { TURBO_TOKEN: token } : {}), + }, + }); + const log: string[] = []; + child.stdout?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + child.stderr?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + servers.push(child); + await answers(`http://127.0.0.1:${port}/management/health`); + return log; + }, + stop, + }; + } catch (error) { + await stop(); + throw error; + } +} + +/** The artifact requests of a server's log. */ +export const requests = (log: string[]) => log.filter((line) => line.includes('/v8/artifacts')); + +/** The requests of a server's log to an artifact, by method: `HEAD`, `GET`, `PUT`. */ +export const artifactMethods = (log: string[]): string[] => + log.flatMap((line) => /"(GET|HEAD|PUT|POST|DELETE) \/v8\/artifacts\/[0-9a-f]+\?/.exec(line)?.[1] ?? []); diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts new file mode 100644 index 00000000..c8d84748 --- /dev/null +++ b/newborns/e2e-playwright.test.ts @@ -0,0 +1,873 @@ +// E2E suites of the template e2e-playwright, in newborn repos of the +// Turborepo template with updates beside it: one with two stateless apps, +// `stateless` and `less`, each with its suite, and one with the answer +// `postgres`, a stateful app whose `migrate` and `seed` are written as its +// author writes them and an app with a `seed` script only, each with its suite. +// Each repo passes `mise e2e` from a fresh clone, each suite starting a copy of +// its own app's build output and removing it at the end; a database is started +// for an app with a `migrate` or `seed` script and for no other, `migrate` runs +// with NODE_ENV=production, then `seed`. An app that needs a database in a repo +// without the answer `postgres` fails before anything starts, naming the answer. +// The stateless suites keep their `run.ts` as generated, and a suite without it +// runs as one with it. The stateful suite's `run.ts` says what its app needs: a +// setting that names the server's own address, without which the server refuses +// to start, a secret and a directory for files; a setting of the server alone; a +// PostgreSQL setting; and a second process from the build output, a worker that +// writes into the database. Migrate, seed and the worker see the environment it +// gives everything; its specs read the database through DATABASE_URL, see the +// environment, and wait on the worker, which the teardown ends. A further process +// that exits before the specs end fails the run, naming it. A run.ts that never +// returns, returns what setup.ts does not take, or sets a name of the setup's, +// fails the run with a message that names what is wrong. +// Without Chromium in Playwright's shared cache the run fails, naming the +// command that installs it, and that command does. The suite's own `e2e` fails +// without the build output and does not build it. Editing a spec moves the +// hash of the suite's `e2e` and leaves the app's `build`; editing the app, or +// giving it a `migrate` script, moves both. A run killed by SIGINT or SIGKILL +// of `mise`, or by SIGKILL of the Playwright runner that started the app, +// leaves no server, no worker and no PostgreSQL behind. The repo's own `check` +// passes as generated, also where the app is an ES module, and type-checks each +// suite after its app's check, without building the app; `plx doctor` in it +// says nothing of the suites' files. It reads the app's code a spec imports +// through the app's `exports` as the app's own check reads it: the suite's +// `tsconfig.json` extends the app's, so an alias of the app's own and a newer +// target the app's workspace packages need pass with no edit of the suite; a +// suite starts an app whose `exports` leave out `./package.json`. A type error +// in a spec, also one a change of the app causes, or in what `run.ts` returns +// fails it, naming the file; editing the app, its `tsconfig.json` or a spec +// moves the hash of the suite's check, and a spec neither the app's check nor +// its build. Created by +// `plx new`; it needs the network. +// +// Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` +// of this workspace: kept from one run to the next and never the user's. +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { born, close, git, type Launched, launch, open, put, relock, sh, tryRun, until } from './helpers.ts'; + +const SHARED = { PLAYWRIGHT_BROWSERS_PATH: join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright') }; + +let here = ''; +before(async () => { + here = await open('e2e-playwright'); +}); +after(close); + +/** `git` that must succeed. */ +async function gitOk(dir: string, ...args: string[]): Promise { + const ran = await git(dir, ...args); + assert.ok(ran.ok, ran.output); +} + +/** A one-pixel PNG, for an app's public/ and its image optimiser, which writes its cache below the server's directory. */ +const PIXEL = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); + +/** A spec of `lines`, as a file of the suite. */ +const spec = (...lines: string[]) => ["import { expect, test } from '@playwright/test';", '', ...lines, ''].join('\n'); + +/** Adds scripts to an app's package.json. */ +function scripts(app: string, added: Record): void { + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + put(app, { 'package.json': { ...manifest, scripts: { ...manifest.scripts, ...added } } }); +} + +const psql = (sql: string) => `psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "${sql}"`; + +/** What a newborn app gets beside the template's files, given its directory and its suite's. */ +const EXTRAS: Record void> = { + // A request the image optimiser answers, which makes the server write below its own directory. + stateless: (app, suite) => { + put(app, { 'public/pixel.png': PIXEL }); + put(suite, { + 'specs/image.spec.ts': spec( + "test('the image optimiser answers', async ({ request }) => {", + " const image = await request.get('/_next/image?url=%2Fpixel.png&w=64&q=75', { headers: { accept: 'image/webp' } });", + ' expect(image.ok()).toBe(true);', + '});', + ), + }); + }, + // The stateful app's migrate and seed as its author writes them, run with the database in DATABASE_URL, and a page + // that reads what they wrote; migrate says which NODE_ENV it ran with. Its server refuses to start unless ACME_URL + // names its own address; started with ACME_TASK=work it is the worker, which records in the database, a few seconds + // after it started, the ACME_POOL it was given. Its suite's run.ts says all of that, and its specs check it. + stateful: (app, suite) => { + scripts(app, { + migrate: `echo "migrate saw NODE_ENV=$NODE_ENV and ACME_SECRET=$ACME_SECRET" && ${psql('create table greeting (text text not null); create table worked (pool text not null, secret text not null)')}`, + seed: `echo "seed saw ACME_SECRET=$ACME_SECRET" && ${psql("insert into greeting values ('hello from the seed')")}`, + }); + put(app, { + 'src/app/greeting/page.tsx': [ + "import { execFileSync } from 'node:child_process';", + "import { connection } from 'next/server';", + '', + 'export default async function Greeting() {', + ' await connection();', + " const sql = ['-Atc', 'select text from greeting'];", + ' return (', + ' <>', + "

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

", + '

pool {process.env.ACME_POOL}

', + ' ', + ' );', + '}', + '', + ].join('\n'), + 'src/instrumentation.ts': [ + 'export async function register() {', + " if (process.env.NEXT_RUNTIME === 'nodejs') await import('./settings');", + '}', + '', + ].join('\n'), + 'src/settings.ts': [ + "import { execFileSync } from 'node:child_process';", + '', + 'const { ACME_POOL, ACME_SECRET, ACME_TASK, ACME_URL, DATABASE_URL, HOSTNAME, PORT } = process.env;', + "if (ACME_TASK === 'work') {", + " console.log('the worker answers on port', PORT);", + " process.on('SIGTERM', () => console.log('the worker was ended by SIGTERM'));", + ' setTimeout(() => {', + " const values = [ACME_POOL ?? 'none', ACME_SECRET ?? 'none'].map((value) => \"'\" + value + \"'\").join(', ');", + " execFileSync('psql', [DATABASE_URL ?? '', '-c', 'insert into worked values (' + values + ')']);", + ' }, 3_000);', + "} else if (ACME_TASK === 'quit') {", + ' setTimeout(() => process.exit(3), 1_000);', + "} else if (ACME_URL !== ['http://', HOSTNAME, ':', PORT].join('')) {", + " console.error('the server refuses to start: ACME_URL is', ACME_URL ?? 'unset', 'and not its own address');", + ' process.exit(1);', + '}', + '', + ].join('\n'), + }); + put(suite, { + 'run.ts': [ + "import type { Needs, Run } from './setup.ts';", + '', + 'export default async function needs(run: Run): Promise {', + ' return {', + " env: { ACME_URL: run.address, ACME_SECRET: 'a secret of the run', ACME_FILES: await run.directory() },", + " server: { env: { ACME_POOL: '20' } },", + ' postgres: { max_connections: 200 },', + " processes: [{ env: { ACME_TASK: 'work' } }],", + ' };', + '}', + '', + ].join('\n'), + 'specs/greeting.spec.ts': spec( + "test('the page shows what the seed wrote into the migrated database', async ({ page }) => {", + " await page.goto('/greeting');", + " await expect(page.getByText('hello from the seed')).toBeVisible();", + '});', + ), + 'specs/needs.spec.ts': [ + "import { execFileSync } from 'node:child_process';", + "import { existsSync } from 'node:fs';", + "import { expect, test } from '@playwright/test';", + '', + 'const sql = (query: string) =>', + " execFileSync('psql', [process.env.DATABASE_URL ?? '', '-Atc', query], { encoding: 'utf8' }).trim();", + '', + "test('a spec reads the database of the run, which has the settings run.ts gave it', () => {", + " expect(sql('select text from greeting')).toBe('hello from the seed');", + " expect(sql('show max_connections')).toBe('200');", + '});', + '', + "test('a spec sees the environment run.ts gave everything', () => {", + ' expect(process.env.ACME_URL).toBe(process.env.PLX_E2E_BASE_URL);', + " expect(process.env.ACME_SECRET).toBe('a secret of the run');", + " expect(existsSync(process.env.ACME_FILES ?? '')).toBe(true);", + '});', + '', + "test('the server has the environment run.ts gave it alone', async ({ page }) => {", + " await page.goto('/greeting');", + " await expect(page.getByText('pool 20')).toBeVisible();", + '});', + '', + "test('a spec waits on the worker, a second process with the environment of everything and not the server alone', async () => {", + " await expect.poll(() => sql('select pool, secret from worked'), { timeout: 30_000 }).toBe('none|a secret of the run');", + '});', + '', + ].join('\n'), + }); + }, + // An app of the stateless profile with a seed script and no migrate. + seeded: (app) => scripts(app, { seed: `echo "seed saw $DATABASE_URL" && ${psql('select 1')}` }), +}; + +/** + * A newborn repo with an app at apps/ of each profile given, plus what + * EXTRAS gives it, and its suite at e2e/, committed; returns the repo. + * `fresh` clones it. + */ +async function newborn( + name: string, + apps: Record, + answers: Record = {}, +): Promise { + const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + for (const [app, profile] of Object.entries(apps)) { + await born(join(dir, 'apps', app), ['app-nextjs'], { name: `@acme/${app}`, profile }); + await born(join(dir, 'e2e', app), ['e2e-playwright'], { app: `@acme/${app}` }); + EXTRAS[app]?.(join(dir, 'apps', app), join(dir, 'e2e', app)); + } + await relock(dir); + await gitOk(dir, 'add', '-A'); + await gitOk(dir, 'commit', '--no-verify', '-q', '-m', 'born'); + return dir; +} + +/** + * The suite of `app`'s check, as Turbo names the task in what it prints: a line's prefix on a terminal, the heading of + * its group under GitHub Actions. + */ +const checked = (app: string) => new RegExp(`@acme/${app}-e2e:check`); + +/** A new directory for a run's TMPDIR, short, as a database's socket lies in it and a socket's path holds about a hundred bytes. */ +function tmp(name: string): string { + const dir = join(here, name); + mkdirSync(dir, { recursive: true }); + return dir; +} + +/** What a run left in its TMPDIR of the suite's copies and the database's clusters. */ +const leftIn = (dir: string) => readdirSync(dir).filter((entry) => /^(plx-e2e|test-postgres)-/.test(entry)); + +/** A fresh clone of `dir`, its tools installed, as a checkout on another machine. */ +async function fresh(dir: string, name: string): Promise { + const clone = join(here, name); + await gitOk(here, 'clone', '-q', dir, clone); + await sh('sh', ['-c', 'mise trust && mise install'], clone); + return clone; +} + +/** Turbo's hashes of the suite's e2e and what it depends on, by task id, from a dry run. */ +async function hashes(dir: string, suite: string): Promise> { + const ran = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'e2e', `--filter=${suite}`, '--dry=json'], dir); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + return Object.fromEntries(dry.tasks.map((t: { taskId: string; hash: string }) => [t.taskId, t.hash])); +} + +describe('a repo with two stateless apps, one name the end of the other, and their suites', () => { + let repo = ''; + before(async () => { + repo = await newborn('stateless', { stateless: 'stateless', less: 'stateless' }); + }); + + test("the suite's marker lists its template and names the app", () => { + const marker = readFileSync(join(repo, 'e2e', 'stateless', 'PLEXUS.md'), 'utf8'); + assert.match(marker, /^---\ntemplates: \[e2e-playwright\]\napp: "@acme\/stateless"\n---\n/); + }); + + test('without Chromium in the shared cache, mise e2e fails naming the command that installs it, which does', async () => { + const clone = await fresh(repo, 'stateless-browserless'); + const empty = join(here, 'no-browsers'); + mkdirSync(empty, { recursive: true }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { PLAYWRIGHT_BROWSERS_PATH: empty }); + assert.equal(ran.ok, false, ran.output); + const named = /install it with `([^`]+)` in (\S+)/.exec(ran.output); + assert.ok(named, ran.output); + const [, command, where] = named as unknown as [string, string, string]; + assert.equal(where, join(clone, 'e2e', 'stateless')); + await sh('mise', ['exec', '--', 'sh', '-c', command], where, SHARED); + const again = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, SHARED); + assert.ok(again.ok, again.output); + }); + + describe('from a fresh clone', () => { + let clone = ''; + before(async () => { + clone = await fresh(repo, 'stateless-clone'); + }); + + test('passes mise e2e: each suite starts a copy of its own app, no database where the app has neither migrate nor seed, and removes the copy', async () => { + const run = tmp('s0'); + const ran = await tryRun('mise', ['run', 'e2e'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /\s2 passed \(/, 'the two specs of stateless'); + assert.match(ran.output, /\s1 passed \(/, 'the one spec of less'); + assert.doesNotMatch(ran.output, /> @acme\/\w+@[\d.]+ (migrate|seed)/); + assert.deepEqual(leftIn(run), [], 'no copy is left'); + // The optimiser wrote its cache below the server's directory: in the copy, and not in the output. + const served = join(clone, 'apps', 'stateless', '.next', 'standalone', 'apps', 'stateless'); + assert.ok(existsSync(join(served, 'server.js')), served); + assert.equal(existsSync(join(served, '.next', 'cache', 'images')), false, 'the output was served itself'); + }); + + test('a suite without run.ts runs as one with run.ts as generated, and passes its check', async () => { + const run = tmp('s4'); + try { + rmSync(join(clone, 'e2e', 'less', 'run.ts')); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /\s1 passed \(/); + assert.deepEqual(leftIn(run), []); + const checked = await tryRun('mise', ['run', 'check'], clone); + assert.ok(checked.ok, checked.output); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + // Each a run.ts and what the failed run says; each fails before the server starts, and leaves nothing. + const refused: [string, string, RegExp][] = [ + [ + 'returns nothing', + 'export default () => undefined;', + /run\.ts returned undefined, where setup\.ts takes an object/, + ], + ['returns null', 'export default () => null;', /run\.ts returned null, where setup\.ts takes an object/], + [ + 'misspells a field', + 'export default () => ({ evn: {} });', + /run\.ts returned evn, which setup\.ts does not take/, + ], + ['gives processes as no list', 'export default () => ({ processes: {} });', /processes of run\.ts is no list/], + [ + 'gives a value that is no string', + 'export default () => ({ env: { A: 1 } });', + /env\.A of run\.ts is no string/, + ], + [ + 'names DATABASE_URL in env', + "export default () => ({ env: { DATABASE_URL: 'x' } });", + /env\.DATABASE_URL of run\.ts is the setup's to give/, + ], + [ + 'names PORT for the server', + "export default () => ({ server: { env: { PORT: '1' } } });", + /server\.env\.PORT of run\.ts is the setup's to give/, + ], + [ + 'names the base URL for a process', + "export default () => ({ processes: [{ env: { PLX_E2E_BASE_URL: 'x' } }] });", + /processes\[0\]\.env\.PLX_E2E_BASE_URL of run\.ts is the setup's to give/, + ], + [ + 'names NODE_ENV', + "export default () => ({ env: { NODE_ENV: 'test' } });", + /env\.NODE_ENV of run\.ts is the setup's to give/, + ], + ]; + for (const [at, [what, source, message]] of refused.entries()) + test(`a run.ts that ${what} fails the run, saying so`, async () => { + const run = tmp(`r${at}`); + try { + put(clone, { 'e2e/less/run.ts': `${source}\n` }); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, message); + assert.doesNotMatch(ran.output, /TypeError/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('a run.ts that never returns fails the run after a minute, leaving nothing', async () => { + const run = tmp('s5'); + try { + put(clone, { 'e2e/less/run.ts': 'export default () => new Promise(() => {});\n' }); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /run\.ts did not return within a minute/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('passes its own check as generated, which type-checks each suite, and plx doctor in it says nothing of the suites', async () => { + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.doesNotMatch(ran.output, /e2e\/\w+\/\S+:\d+:\d+|Suppression comment/); + for (const suite of ['stateless', 'less']) assert.match(ran.output, checked(suite), suite); + }); + + test('passes its own check as generated where the app is an ES module', async () => { + try { + const manifest = JSON.parse(readFileSync(join(clone, 'apps', 'stateless', 'package.json'), 'utf8')); + put(clone, { 'apps/stateless/package.json': { ...manifest, type: 'module' } }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('a type error in a spec fails mise check, which names the file', async () => { + try { + const file = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { + 'e2e/stateless/specs/home.spec.ts': `${readFileSync(file, 'utf8')}export const n: number = 'one';\n`, + }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /(?:^|: )specs\/home\.spec\.ts\(\d+,\d+\): error TS2322/m); + assert.match(ran.output, /Failed:\s+@acme\/stateless-e2e#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + // What run.ts returns, wrong in a way the run would refuse (as the refused runs above show), is found by check. + const mistyped: [string, string, RegExp][] = [ + ['a misspelt field', 'return { evn: {} };', /(?:^|: )run\.ts\(\d+,\d+\): error TS2353: .*'evn'/m], + ['a value that is no string', 'return { env: { A: 1 } };', /(?:^|: )run\.ts\(\d+,\d+\): error TS2322/m], + ]; + for (const [what, line, message] of mistyped) + test(`run.ts returning ${what} fails mise check, which names run.ts`, async () => { + try { + const file = join(clone, 'e2e', 'less', 'run.ts'); + const generated = readFileSync(file, 'utf8'); + assert.match(generated, /return \{\};/); + put(clone, { 'e2e/less/run.ts': generated.replace('return {};', line) }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, message); + assert.match(ran.output, /Failed:\s+@acme\/less-e2e#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test("the check reads what a spec imports of the app through its exports as the app reads it, an ES module or not, and fails a spec the app's change no longer fits", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + // A module of the app's, which imports another without an extension and a third by the app's alias @/, as the + // app's own code may. + put(app, { + 'src/lib/greet.ts': + "import { tail } from './tail';\n\nexport const greet = (name: string): string => `hello ${name}${tail}`;\n", + 'src/lib/tail.ts': "import { mark } from '@/lib/mark';\n\nexport const tail: string = mark;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", + }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + for (const type of [undefined, 'module']) { + put(app, { 'package.json': { ...manifest, type, exports: { './greet': './src/lib/greet.ts' } } }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, `${type ?? 'commonjs'}:\n${ran.output}`); + } + // A change of the app's that its own check passes and the spec no longer fits; an error in the app's own code + // fails the app's check first, which the suite's follows. + put(app, { + 'src/lib/greet.ts': + "import { tail } from './tail';\n\nexport const greet = (times: number): string => `hello${tail.repeat(times)}`;\n", + }); + const broken = await tryRun('mise', ['run', 'check'], clone); + assert.equal(broken.ok, false, broken.output); + assert.match(broken.output, /(?:^|: )specs\/greet\.spec\.ts\(\d+,\d+\): error TS2345/m); + assert.match(broken.output, /Failed:\s+@acme\/stateless-e2e#check/); + assert.doesNotMatch(broken.output, /Failed:\s+@acme\/stateless#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + + test("an app whose exports leave out ./package.json is started by its suite, whose spec runs the app's code it imports through them", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + const run = tmp('s7'); + try { + put(app, { + 'package.json': { ...manifest, exports: { './greet': './src/lib/greet.ts' } }, + 'src/lib/greet.ts': + "import { mark } from '@/lib/mark';\n\nexport const greet = (name: string): string => `hello ${name}${mark}`;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", + }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /\s3 passed \(/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + + /** Sets compiler options in the app `stateless`'s tsconfig.json, written as the repo's formatter writes it. */ + async function compilerOptions(app: string, options: Record): Promise { + const config = JSON.parse(readFileSync(join(app, 'tsconfig.json'), 'utf8')); + put(app, { 'tsconfig.json': { ...config, compilerOptions: { ...config.compilerOptions, ...options } } }); + await sh('mise', ['exec', '--', 'biome', 'format', '--write', join(app, 'tsconfig.json')], clone); + } + + /** The app `stateless` exporting `./greet`, which imports `lib` beside it, and a spec of its suite that imports it. */ + function greeting(app: string, manifest: Record, lib: Record): void { + put(app, { 'package.json': { ...manifest, exports: { './greet': './src/lib/greet.ts' } }, ...lib }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + } + + test("an app with an alias of its own, not the template's @/*, passes the suite's check with no edit of the suite", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + await compilerOptions(app, { paths: { '~/*': ['./src/*'] } }); + greeting(app, manifest, { + 'src/lib/greet.ts': + "import { mark } from '~/lib/mark';\n\nexport const greet = (name: string): string => `hello ${name}${mark}`;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", + }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + + test("an app with a newer target than the base, whose workspace package needs it, passes the suite's check, which reads the package as the app does", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + // A package of the workspace whose source uses a flag of a regular expression that ES2018 brought. + put(clone, { + 'packages/text/package.json': { name: '@acme/text', private: true, exports: { '.': './src/index.ts' } }, + 'packages/text/src/index.ts': + "export const firstLine = (text: string): string => /^(.*?)$/ms.exec(text)?.[1] ?? '';\n", + }); + await compilerOptions(app, { target: 'ES2022' }); + greeting( + app, + { ...manifest, dependencies: { ...(manifest.dependencies as object), '@acme/text': 'workspace:*' } }, + { + 'src/lib/greet.ts': + "import { firstLine } from '@acme/text';\n\nexport const greet = (name: string): string => firstLine(`hello ${name}!\\nmore`);\n", + }, + ); + await relock(clone); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e', 'packages'); + } + }); + + test("the suite's check needs no build and follows the app's check; editing the app or a spec moves it, a spec neither the app's check nor its build", async () => { + const [suite, app] = ['@acme/stateless-e2e#check', '@acme/stateless#check']; + /** Turbo's hashes of the suite's check and what it depends on, with the app's build, by task id. */ + const checks = async () => { + const ran = await tryRun( + 'mise', + ['exec', '--', 'turbo', 'run', 'check', 'build', '--filter=@acme/stateless-e2e...', '--dry=json'], + clone, + ); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + const tasks: { taskId: string; hash: string; dependencies: string[] }[] = dry.tasks; + return { tasks, hash: Object.fromEntries(tasks.map((t) => [t.taskId, t.hash])) }; + }; + try { + const first = await checks(); + assert.deepEqual(first.tasks.find((t) => t.taskId === suite)?.dependencies, [app]); + assert.deepEqual(first.tasks.find((t) => t.taskId === app)?.dependencies, [], "the app's check builds nothing"); + const specFile = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(specFile, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const specEdited = await checks(); + assert.notEqual(specEdited.hash[suite], first.hash[suite]); + for (const id of [app, '@acme/stateless#build']) assert.equal(specEdited.hash[id], first.hash[id], id); + const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); + put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const appEdited = await checks(); + assert.notEqual(appEdited.hash[suite], specEdited.hash[suite], 'an edit of the app'); + // The app's tsconfig.json, which the suite's extends. + const config = JSON.parse(readFileSync(join(clone, 'apps', 'stateless', 'tsconfig.json'), 'utf8')); + put(clone, { + 'apps/stateless/tsconfig.json': { + ...config, + compilerOptions: { ...config.compilerOptions, target: 'ES2022' }, + }, + }); + await gitOk(clone, 'add', '-A'); + assert.notEqual((await checks()).hash[suite], appEdited.hash[suite], "an edit of the app's tsconfig.json"); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test("the suite's own e2e fails without the build output, and does not build it", async () => { + const dotNext = join(clone, 'apps', 'stateless', '.next'); + rmSync(dotNext, { recursive: true, force: true }); + const ran = await tryRun( + 'mise', + ['exec', '--', 'pnpm', '--filter', '@acme/stateless-e2e', 'run', 'e2e'], + clone, + SHARED, + ); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /@acme\/stateless has no build output at \S+\.next\/standalone/); + assert.equal(existsSync(dotNext), false, 'nothing was built'); + }); + + test("editing a spec moves the suite's e2e and not the app's build; editing the app or giving it a migrate moves both", async () => { + const [e2e, build] = ['@acme/stateless-e2e#e2e', '@acme/stateless#build']; + const app = join(clone, 'apps', 'stateless'); + try { + const first = await hashes(clone, '@acme/stateless-e2e'); + assert.ok(first[e2e] && first[build], JSON.stringify(first)); + const specFile = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(specFile, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const specEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(specEdited[e2e], first[e2e]); + assert.equal(specEdited[build], first[build]); + const page = join(app, 'src', 'app', 'page.tsx'); + put(app, { 'src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const appEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(appEdited[e2e], specEdited[e2e]); + assert.notEqual(appEdited[build], specEdited[build]); + scripts(app, { migrate: 'echo migrated' }); + await gitOk(clone, 'add', '-A'); + assert.notEqual((await hashes(clone, '@acme/stateless-e2e'))[e2e], appEdited[e2e], 'a migrate script'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('an app with a migrate script, in a repo without the answer postgres, fails before anything starts, naming the answer', async () => { + const app = join(clone, 'apps', 'stateless'); + const run = tmp('s1'); + try { + scripts(app, { migrate: 'echo migrated' }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /answer `postgres` in the repo's PLEXUS\.md.*`plx apply`/); + assert.doesNotMatch(ran.output, /migrated/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + }); +}); + +/** The command lines of every process that mentions `text`. */ +async function mentioning(text: string): Promise { + const ps = await sh('ps', ['-axww', '-o', 'args='], here); + return ps.split('\n').filter((line) => line.includes(text)); +} + +describe('a repo with the answer postgres, a stateful app, an app with a seed alone, and their suites', () => { + let clone = ''; + before(async () => { + clone = await fresh( + await newborn('stateful', { stateful: 'stateful', seeded: 'stateless' }, { postgres: '18.6' }), + 'stateful-clone', + ); + }); + + test("passes mise check from a fresh clone, each suite type-checked, the stateful suite's run.ts and specs included", async () => { + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + for (const suite of ['stateful', 'seeded']) assert.match(ran.output, checked(suite), suite); + }); + + test('passes mise e2e from a fresh clone: migrate in production, then seed, against the database the server gets, with what run.ts says', async () => { + const run = tmp('s2'); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /migrate saw NODE_ENV=production and ACME_SECRET=a secret of the run\n/); + assert.match(ran.output, /seed saw ACME_SECRET=a secret of the run\n/); + assert.match(ran.output, /CREATE TABLE[\s\S]*INSERT 0 1/); + assert.match(ran.output, /\s6 passed \(/); + assert.deepEqual(leftIn(run), [], 'no copy and no directory of run.ts is left'); + // The worker was still running when the specs ended, and the teardown ended it. + const worker = /the worker answers on port (\d+)/.exec(ran.output)?.[1]; + assert.ok(worker, ran.output); + assert.match(ran.output, /the worker was ended by SIGTERM/); + const answers = await fetch(`http://127.0.0.1:${worker}/healthz`).then( + () => true, + () => false, + ); + assert.equal(answers, false, 'the worker answers no more'); + }); + + test('a further process that exits before the specs end fails the run, saying which and with what', async () => { + const run = tmp('s6'); + const file = join(clone, 'e2e', 'stateful', 'run.ts'); + try { + put(clone, { + 'e2e/stateful/run.ts': readFileSync(file, 'utf8').replace( + "processes: [{ env: { ACME_TASK: 'work' } }]", + "processes: [{ env: { ACME_TASK: 'work' } }, { env: { ACME_TASK: 'quit', ACME_QUEUES: 'q-value' } }]", + ), + }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /\s6 passed \(/, 'the specs pass, and the run fails all the same'); + assert.match( + ran.output, + /further process 1 of run\.ts, with ACME_TASK and ACME_QUEUES, exited with 3 before the specs ended/, + ); + assert.deepEqual(leftIn(run), []); + assert.deepEqual(await mentioning(run), [], 'no PostgreSQL is left'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('without the setting that names its address the server refuses to start, and the run fails leaving nothing', async () => { + const run = tmp('s3'); + const file = join(clone, 'e2e', 'stateful', 'run.ts'); + try { + put(clone, { 'e2e/stateful/run.ts': readFileSync(file, 'utf8').replace('ACME_URL: run.address, ', '') }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /the server refuses to start: ACME_URL is unset/); + assert.match(ran.output, /the server exited with 1 before/); + assert.doesNotMatch(ran.output, /q-value/, 'the values of its environment are not shown'); + assert.deepEqual(leftIn(run), []); + assert.deepEqual(await mentioning(run), [], 'no PostgreSQL is left'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('an app with a seed script and no migrate gets a database and its seed, and no migrate', async () => { + const ran = await tryRun('mise', ['run', 'e2e', 'seeded'], clone, SHARED); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /> @acme\/seeded@[\d.]+ seed/); + assert.match(ran.output, /seed saw postgres(ql)?:\/\//); + assert.doesNotMatch(ran.output, /> @acme\/seeded@[\d.]+ migrate/); + assert.match(ran.output, /\s1 passed \(/); + }); + + /** The pid of the one process whose parent is `parent` (any, where undefined) and whose command line matches `pattern`. */ + async function pidOf(pattern: RegExp, parent?: number): Promise { + const ps = await sh('ps', ['-axww', '-o', 'pid=,ppid=,args='], here); + const found = ps + .split('\n') + .map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)) + .filter((m) => m && (parent === undefined || Number(m[2]) === parent) && pattern.test(m[3] as string)); + assert.equal(found.length, 1, `${pattern} under ${parent}:\n${ps}`); + return Number(found[0]?.[1]); + } + + // The run is started from a shell, as from a terminal: mise then neither leads its process group nor its session, + // and a SIGINT to the group reaches it as a Ctrl-C does. (A mise that leads its own session hands a SIGINT on to + // no task, and the run goes on to its end.) + const kills: [string, (run: Launched) => Promise][] = [ + ['SIGINT of the run, as a Ctrl-C', async (run) => void process.kill(-(run.pid as number), 'SIGINT')], + [ + 'SIGKILL of mise', + async (run) => process.kill(await pidOf(/^mise run e2e stateful$/, run.pid as number), 'SIGKILL'), + ], + [ + 'SIGKILL of the Playwright runner', + async () => { + const where = join(clone, 'e2e', 'stateful'); + const runner = new RegExp(`${where.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\S*@playwright/test/cli\\.js test$`); + process.kill(await pidOf(runner), 'SIGKILL'); + }, + ], + ]; + for (const [at, [how, kill]] of kills.entries()) + test(`a run killed by ${how} leaves no server, no worker and no PostgreSQL behind`, async () => { + // A spec that outlasts the kill; the run's temporary files, the database's cluster among them, are found by TMPDIR. + const dir = tmp(`t${at}`); + // A spec of its own in each run, so that a run that went on to its end leaves no cache hit for the next. + put(clone, { + 'e2e/stateful/specs/slow.spec.ts': [ + "import { test } from '@playwright/test';", + '', + `test('waits, to be killed by ${how}', async () => {`, + ' await new Promise((resolve) => setTimeout(resolve, 20_000));', + '});', + '', + ].join('\n'), + }); + // Streamed, as on a terminal: under GitHub Actions Turbo holds a task's output back until the task ends. + const env = { ...SHARED, TMPDIR: dir, TURBO_LOG_ORDER: 'stream' }; + const run = launch('sh', ['-c', 'mise run e2e stateful; exit'], clone, env); + try { + let ended = false; + void run.closed.then(() => { + ended = true; + }); + await until( + 'the specs run', + () => { + assert.ok(!ended, `the run ended before its specs ran:\n${run.output()}`); + return /Running \d+ tests/.test(run.output()); + }, + 300_000, + ); + const port = /http:\/\/127\.0\.0\.1:(\d+)/.exec(run.output())?.[1]; + assert.ok(port, run.output()); + const answers = () => + fetch(`http://127.0.0.1:${port}/healthz`).then( + (r) => r.ok, + () => false, + ); + assert.ok(await answers(), 'the server answers before the kill'); + // The worker is started once the server answers, and may say so after the specs began. + await until('the worker answers', () => /the worker answers on port \d+/.test(run.output()), 60_000); + const workerPort = /the worker answers on port (\d+)/.exec(run.output())?.[1]; + const works = () => + fetch(`http://127.0.0.1:${workerPort}/healthz`).then( + (r) => r.ok, + () => false, + ); + assert.ok(await works(), 'the worker answers before the kill'); + assert.ok( + (await mentioning(dir)).some((line) => /postgres/.test(line)), + 'and its database runs', + ); + await kill(run); + await until(`the run ends after ${how}`, () => ended, 120_000); + await until( + `after ${how}, the server, the worker and the database are gone`, + async () => !(await answers()) && !(await works()) && (await mentioning(dir)).length === 0, + 30_000, + ); + } finally { + run.kill(); + rmSync(join(clone, 'e2e', 'stateful', 'specs', 'slow.spec.ts'), { force: true }); + } + }); +}); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index c541c70e..0d0b0fc3 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -1,15 +1,15 @@ // What the newborn tests share. A newborn is a repo or an app that `plx new` // creates from the templates the built `plx` bundles, birth commands included, // so that each test runs what a tenant runs on the first day: the tools are -// installed from the network, and `mise run verify` is the newborn's own. +// installed from the network, and the newborn's own verbs are run. // // What is tested with what. Every `@plexus-ms` package a newborn installs // (the `plx` and `plx-ci` its `mise.toml` pins, and the packages those need) is // this workspace's own build, served by a registry of its own (registry.ts) to // the installers that read the scope's registry setting; the libraries of the // scope that are not built here, and every other package, come from npm. So the -// newborn's `plx doctor`, in its own `verify`, is the plx being cut, and a -// version whose packages are not on npm yet is tested all the same; `verify` +// newborn's `plx doctor`, in its own `check`, is the plx being cut, and a +// version whose packages are not on npm yet is tested all the same; `pass` // below asserts it of every newborn, whatever the machine has installed. `ship` // stamps the manifests of the packages and the pins of the templates with one // version in one commit; `open` fails if they differ. @@ -25,13 +25,18 @@ // install, byte for byte the build (`assertBuilt`). The pnpm cache directory // is scratch for the commands this file starts (`plx new`'s birth commands, a // lock refresh, `mise run`), through the environment. Not scratch: the pnpm -// that turbo starts inside a newborn's `verify`, which turbo's strict +// that turbo starts inside a newborn's verbs, which turbo's strict // environment keeps the variable from, and which writes npm's own metadata of // the newborn's dependencies to the user's pnpm cache; the user's pnpm store, // which is content-addressed, and corepack's cache. None of them receives a // package built here: mise installs those, into scratch. Nothing is written to // the user's `~/.npmrc` or mise configuration. // +// Remote cache. A newborn's verbs reach no Turbo remote cache unless its test +// names the server (PLX_TURBO_SHARED, PLX_TURBO_TRUSTED, read by repo-turbo's +// turbow): never the server the user's machine may run on its fixed port, and +// in CI no build fails for want of a trusted server. +// // Time limit. A command that outlives LIMIT is killed with everything it // started, its whole process group. import { execFileSync, spawn } from 'node:child_process'; @@ -50,6 +55,7 @@ import { symlinkSync, writeFileSync, } from 'node:fs'; +import { createServer } from 'node:net'; import { homedir, tmpdir } from 'node:os'; import { dirname, join, sep } from 'node:path'; import { PUBLISHED, pack } from './pack.ts'; @@ -63,12 +69,14 @@ const PLX = join(WORKSPACE, 'packages', 'cli', 'dist', 'plx.js'); /** * The environment of the tools a test runs: a hook that runs this leaves * GIT_DIR and its siblings set, which would point a newborn's `git init` - * at the pushing repository, so git's own list of them is removed. + * at the pushing repository, so git's own list of them is removed. A forced + * run of this workspace (TURBO_FORCE) is this workspace's: a newborn's cache + * is new anyway, and its tests read its hits and misses, so it is removed too. */ function cleanEnv(extra: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const local = execFileSync('git', ['rev-parse', '--local-env-vars'], { encoding: 'utf8' }).split('\n'); const env = { ...process.env }; - for (const name of local) delete env[name]; + for (const name of [...local, 'TURBO_FORCE']) delete env[name]; return { ...env, ...world?.env, ...extra }; } @@ -86,51 +94,78 @@ export interface Ran { */ export const LIMIT = 10 * 60_000; +/** A command started leading a process group of its own: what it printed so far, the group's kill, and its end. */ +export interface Launched { + /** The command's process id, which leads the group; undefined where it could not start. */ + pid: number | undefined; + output(): string; + kill(): void; + /** Its exit code once its output is closed; null where it was killed or could not start. */ + closed: Promise; +} + +/** + * Starts a command in a process group of its own and collects what it prints; + * the group is killed once the command exits, so that nothing it started + * outlives it. A command that cannot start ends with the error as its output. + */ +export function launch(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Launched { + const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + let output = ''; + const collect = (chunk: Buffer) => { + output += chunk; + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + const kill = () => { + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + }; + child.on('exit', kill); + const closed = new Promise((resolve) => { + child.on('error', (error) => { + output = error.message; + resolve(null); + }); + child.on('close', resolve); + }); + return { pid: child.pid, output: () => output, kill, closed }; +} + /** * Runs a command and returns what it printed; a failure, a command killed at * its limit included, is returned, never thrown. The command leads a process * group of its own, which is killed at the limit and when the command is done, * so that nothing it started outlives it. */ -export function tryRun( +export async function tryRun( command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv = {}, limit = LIMIT, ): Promise { - return new Promise((resolve) => { - const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); - const killGroup = () => { - try { - if (child.pid) process.kill(-child.pid, 'SIGKILL'); - } catch {} - }; - let output = ''; - let timedOut = false; - child.stdout.on('data', (chunk: Buffer) => { - output += chunk; - }); - child.stderr.on('data', (chunk: Buffer) => { - output += chunk; - }); - const timer = setTimeout(() => { - timedOut = true; - killGroup(); - }, limit); - child.on('error', (error) => { - clearTimeout(timer); - resolve({ ok: false, output: error.message }); - }); - child.on('exit', () => killGroup()); - child.on('close', (code) => { - clearTimeout(timer); - if (timedOut) resolve({ ok: false, output: `${command} timed out after ${limit} ms and was killed\n${output}` }); - else resolve({ ok: code === 0, output }); - }); - }); + const run = launch(command, args, cwd, env); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + run.kill(); + }, limit); + const code = await run.closed; + clearTimeout(timer); + if (timedOut) return { ok: false, output: `${command} timed out after ${limit} ms and was killed\n${run.output()}` }; + return { ok: code === 0, output: run.output() }; } +/** git with an identity and no signing, as a newborn has neither; unfailing, as `tryRun` is. */ +export const git = (dir: string, ...args: string[]) => + tryRun( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + /** Runs a command that must succeed; its output goes with the error otherwise. */ export async function sh(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv = {}): Promise { const ran = await tryRun(command, args, cwd, env); @@ -233,6 +268,8 @@ export async function open(name: string, options: { users?: string; registry?: b MISE_STATE_DIR: join(dir, 'mise-state'), MISE_DATA_DIR: join(dir, 'mise-data'), MISE_SYSTEM_DATA_DIR: seeFromUsers(dir, options.users), + PLX_TURBO_SHARED: 'none', + PLX_TURBO_TRUSTED: 'none', }; world = { dir, env }; try { @@ -294,6 +331,9 @@ export async function born( /** The newborn's own `mise run `; extra arguments follow the task. */ export const mise = (dir: string, ...args: string[]) => tryRun('mise', ['run', ...args], dir); +/** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ +export const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); + /** The tools a newborn's `mise.toml` may pin from the packages built here, with the file of the build each one is. */ const BUILT = [ { tool: 'plx', pkg: 'cli', file: 'plx.js' }, @@ -328,17 +368,85 @@ export async function assertBuilt(dir: string): Promise { } } -/** `mise run verify` in the newborn, which must pass. */ -export async function verify(dir: string, name: string, env: NodeJS.ProcessEnv = {}): Promise { +/** `mise run ` in the newborn, which must pass: the built tools, then the task. */ +export async function pass(dir: string, name: string, task: string, env: NodeJS.ProcessEnv = {}): Promise { await assertBuilt(dir); - const ran = await tryRun('mise', ['run', 'verify'], dir, env); - if (!ran.ok) throw new Error(`the newborn ${name} fails its own verify:\n${ran.output}`); + const ran = await tryRun('mise', ['run', task], dir, env); + if (!ran.ok) throw new Error(`the newborn ${name} fails its own ${task}:\n${ran.output}`); } -/** Writes files below `root`, creating directories; a value that is no string is written as formatted JSON. */ +/** Writes files below `root`, creating directories; a value that is neither a string nor bytes is written as formatted JSON. */ export function put(root: string, files: Record): void { for (const [path, content] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); - writeFileSync(join(root, path), typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`); + const raw = typeof content === 'string' || content instanceof Uint8Array; + writeFileSync(join(root, path), raw ? content : `${JSON.stringify(content, null, 2)}\n`); + } +} + +/** A TCP port on loopback that nothing listens on at the time of asking. */ +export function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + server.on('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + server.close(() => + address && typeof address === 'object' ? resolve(address.port) : reject(new Error('no port')), + ); + }); + }); +} + +/** A server a test started, and its stop. */ +export interface Started { + stop(): Promise; +} + +/** + * Starts a long-running command, a server, leading a process group of its + * own, and resolves once `ready` answers true; rejects with what the command + * printed when it exits first or LIMIT passes. `stop` kills the whole group. + */ +export async function start( + command: string, + args: string[], + cwd: string, + env: NodeJS.ProcessEnv, + ready: () => Promise, +): Promise { + const run = launch(command, args, cwd, env); + let gone = false; + void run.closed.then(() => { + gone = true; + }); + const stop = async () => { + run.kill(); + await run.closed; + }; + try { + await until(`${command} ready`, async () => { + if (gone) throw new Error(`${command} exited`); + return ready().catch(() => false); + }); + return { stop }; + } catch { + await stop(); + throw new Error( + `${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${run.output()}`, + ); + } +} + +/** + * Resolves once `check` answers true, asking every 200 ms; rejects, naming + * `what`, once `limit` milliseconds have passed. A check that throws ends the + * wait with its error. + */ +export async function until(what: string, check: () => boolean | Promise, limit = LIMIT): Promise { + for (const end = Date.now() + limit; Date.now() < end; ) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 200)); } + throw new Error(`${what}: not within ${limit} ms`); } diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts new file mode 100644 index 00000000..80797007 --- /dev/null +++ b/newborns/pipeline.test.ts @@ -0,0 +1,457 @@ +// A newborn app repo through its pipeline: the commands the jobs of its +// workflows call (_check.yml, _e2e.yml, _publish-deploy.yml and _deploy.yml), +// in the order the jobs run and each job from a fresh clone of the repo's +// origin, with its tools installed as a job installs them, and each as a job +// of the forge (GITHUB_ACTIONS=true) with the one cache server its job starts. +// The workflows themselves run only on the forge; what of them this file +// stands in for: +// +// test mise run test, with the shared cache +// plan plx-ci plan --deploy, in the repo's mise environment, with crane, +// asking the trusted cache which large jobs have work +// e2e per app the plan gives a large job: mise run build , the +// suite's Chromium, mise run e2e , with the trusted cache +// publish per app: plx-ci publish --context , +// with the trusted cache, without BUILDKIT_HOST, so through this +// machine's Docker, into a registry on loopback +// deploy per deploy: plx deploy, over an ssh that runs each line here with +// bash, into a directory standing in for the host's /opt/stacks, with +// this machine's Docker +// +// The caches are the cache servers the step turbo-cache starts, against an S3 +// stand-in with the two buckets (caches.ts). The repo has two apps from +// app-nextjs: `web`, with two E2E suites, and `site`, without one. The first +// run gives both a large job, publishes each image from a restore of the +// output its large job built, and deploys `web` healthy. A second run on the +// same content gives no app a large job, builds no image, and leaves `web` +// running; the plan's requests to the trusted server are HEAD requests only. +// A change to a spec alone gives exactly `web` a large job, which runs its +// suites and no build, and publish builds no image; so does a change to a spec +// of its second suite alone. A change to `site` alone +// gives exactly `site` a large job, and publish builds its image. Where a suite +// fails, its large job fails and the run publishes nothing; the step that keeps +// the results, which runs on the forge only after the E2E step failed (its +// shape is packages/lib/src/pipeline.test.ts's), finds in that job's checkout, +// at the path it names, the results of the failed suites and no other, under +// the suite's directory name, in one artifact per app: for `web`, whose second +// suite fails, and for `site`, given one suite that fails. Needs Docker and the +// network, as the newborns do. +import assert from 'node:assert/strict'; +import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { artifactMethods, type Caches, startCaches } from './caches.ts'; +import { born, close, freePort, git, open, put, relock, sh, tryRun } from './helpers.ts'; + +/** The step of _e2e.yml's large job that keeps a failed suite's results: its artifact's name and its path, as written. */ +function uploadStep(): { name: string; path: string } { + const workflow = readFileSync(join(import.meta.dirname, '..', '.github', 'workflows', '_e2e.yml'), 'utf8'); + const step = /^ {6}- name: .*\n(?: {8}.*\n)*? {8}uses: actions\/upload-artifact@.*\n((?: {8,}.*\n)*)/m.exec( + workflow, + )?.[1]; + const value = (key: string) => new RegExp(`^ {10}${key}: (.*)$`, 'm').exec(step ?? '')?.[1] ?? ''; + return { name: value('name'), path: value('path') }; +} + +/** + * The files the upload step's path finds in a job's checkout, as the artifact holds them: below the first wildcard, + * hidden files and the files in hidden directories left out, as the action leaves them out by default. + */ +function upload(job: string, path: string): string[] { + assert.match(path, /^[^*]+\/\*\/[^*]+$/, `the upload step's path, ${path}, is no directory per suite`); + const [base = '', below = ''] = path.split('/*/'); + const found: string[] = []; + const walk = (dir: string, at: string) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name.startsWith('.')) continue; + if (entry.isDirectory()) walk(join(dir, entry.name), `${at}${entry.name}/`); + else found.push(`${at}${entry.name}`); + } + }; + for (const suite of readdirSync(join(job, base))) { + const results = join(job, base, suite, below); + if (existsSync(results)) walk(results, `${suite}/${below.replace(/\/?$/, '/')}`); + } + return found.sort(); +} + +const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); +/** The app's server-actions key, as the vault would hand it to a build: made up. */ +const KEY = 'bmV3Ym9ybi1zZXJ2ZXItYWN0aW9ucy1rZXktMzJieXQ='; +const CRANE = 'crane@0.22.1'; + +let here = ''; +let origin = ''; +let registry = ''; +let container = ''; +let port = 0; +let caches: Caches | undefined; +/** Every job's environment beyond the world's: a job of the forge, and where the images go. */ +let env: Record = {}; +/** What the step announces in a job that starts the shared cache, and in one that starts the trusted cache. */ +let shared: Record = {}; +let trusted: Record = {}; +/** The trusted server's log. */ +let trustedLog: string[] = []; +const deployments: string[] = []; + +/** `git` that must succeed. */ +async function gitOk(dir: string, ...args: string[]): Promise { + const ran = await git(dir, ...args); + assert.ok(ran.ok, ran.output); + return ran.output.trim(); +} + +before(async () => { + here = await open('pipeline'); + // The forge's registry: a registry on loopback. + const started = (await sh('docker', ['run', '-d', '--rm', '-p', '127.0.0.1::5000', 'registry:2'], here)).match( + /^[0-9a-f]{64}$/m, + ); + container = started?.[0] ?? ''; + if (!container) throw new Error('docker run printed no container id'); + registry = (await sh('docker', ['port', container, '5000/tcp'], here)).trim().split('\n')[0] ?? ''; + // The two caches, each a server with a token of its own, as the step starts them in a job. + caches = await startCaches(here, ['acme-ci-turbo', 'acme-ci-turbo-trusted']); + const [sharedPort, trustedPort] = [await freePort(), await freePort()]; + await caches.serve('acme-ci-turbo', sharedPort, 'a-shared-token'); + trustedLog = await caches.serve('acme-ci-turbo-trusted', trustedPort, 'a-trusted-token'); + shared = { PLX_TURBO_SHARED: `http://127.0.0.1:${sharedPort}`, PLX_TURBO_SHARED_TOKEN: 'a-shared-token' }; + trusted = { PLX_TURBO_TRUSTED: `http://127.0.0.1:${trustedPort}`, PLX_TURBO_TRUSTED_TOKEN: 'a-trusted-token' }; + // The ssh of a deploy: every line it is given runs here, with bash. + const bin = join(here, 'bin'); + mkdirSync(bin); + writeFileSync( + join(bin, 'ssh'), + '#!/usr/bin/env bash\nfor a in "$@"; do [ "$a" = -O ] && exit 0; done\nwhile [ "$1" != -- ]; do shift; done; shift\nexec bash -c "$1"\n', + ); + chmodSync(join(bin, 'ssh'), 0o755); + env = { + GITHUB_ACTIONS: 'true', + // A job announces only the cache it starts. + PLX_TURBO_SHARED: '', + PLX_TURBO_TRUSTED: '', + PLAYWRIGHT_BROWSERS_PATH: BROWSERS, + IMAGE_PREFIX: `${registry}/acme`, + BUILDKIT_HOST: '', + PATH: `${bin}:${process.env.PATH}`, + }; + port = await freePort(); + + const repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme' }); + await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web', profile: 'stateless' }); + await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); + // A second suite of web: the template names a suite's package after its app, so this one is renamed. + await born(join(repo, 'e2e', 'web2'), ['e2e-playwright'], { app: '@acme/web' }); + const second = join(repo, 'e2e', 'web2', 'package.json'); + writeFileSync(second, readFileSync(second, 'utf8').replace('"@acme/web-e2e"', '"@acme/web-e2e2"')); + await born(join(repo, 'apps', 'site'), ['app-nextjs'], { name: '@acme/site', profile: 'stateless' }); + // Where the app deploys in staging: the operations repo's inventory, as the plan reads it. + put(here, { + 'operations/inventory/host_vars/app-host.yml': + 'plexus_deploy_target: ssh://deploy@app-host\nplexus_apps:\n - name: web\n environment: staging\n', + }); + await relock(repo); + await gitOk(repo, 'add', '-A'); + await gitOk(repo, 'commit', '--no-verify', '-q', '-m', 'born'); + origin = join(here, 'origin.git'); + await gitOk(here, 'clone', '-q', '--bare', repo, origin); +}); + +after(async () => { + for (const dir of deployments) await tryRun('docker', ['compose', 'down', '--volumes'], dir); + if (container) await tryRun('docker', ['rm', '-f', container], here); + for (const tag of ['web', 'site']) + await tryRun('sh', ['-c', `docker image ls -q '${registry}/acme/${tag}' | xargs -r docker image rm -f`], here); + await caches?.stop(); + await close(); +}); + +let jobs = 0; +/** A fresh clone of the origin at `sha`, named as the forge's repo, its tools installed: the checkout of one job. */ +async function checkout(sha: string): Promise { + const dir = join(here, 'jobs', String(jobs++)); + await gitOk(here, 'clone', '-q', origin, dir); + await gitOk(dir, 'checkout', '-q', sha); + // The team of the caches is owner-repo, from origin's URL (turbow). + await gitOk(dir, 'remote', 'set-url', 'origin', 'https://github.com/acme/web.git'); + await sh('sh', ['-c', 'mise trust -q && mise install -q'], dir); + return dir; +} + +/** A command of a job, which must pass; its output. */ +async function step(dir: string, command: string[], extra: Record = {}): Promise { + const [name = '', ...args] = command; + const ran = await tryRun(name, args, dir, { ...env, ...extra }); + assert.ok(ran.ok, `${command.join(' ')} failed in ${dir}:\n${ran.output}`); + return ran.output; +} + +/** Turbo's summary of a run, ` of `, one per turbo run in the output. */ +const summaries = (output: string): [number, number][] => + [...output.matchAll(/Cached:\s+(\d+) cached, (\d+) total/g)].map((m) => [Number(m[1]), Number(m[2])]); + +/** The tasks a Turbo dry run of `task` would run, by id: those whose package has the script. */ +async function planned(dir: string, task: string): Promise { + const out = await step(dir, ['mise', 'exec', '--', 'turbo', 'run', task, '--dry=json'], shared); + const dry = JSON.parse(out.slice(out.indexOf('{'))); + return dry.tasks + .filter((t: { command: string }) => t.command !== '') + .map((t: { taskId: string }) => t.taskId) + .sort(); +} + +interface Leg { + app: string; + hash: string; + suites: string[]; + context: string; + build: boolean; + large: boolean; +} + +interface Run { + test: string; + plan: { legs: Leg[]; deploys: { app: string; host: string; image: string }[]; environment: string }; + /** The methods of the plan's requests to the trusted server's artifacts. */ + asked: string[]; + /** The output of each large job, by app; where its E2E step failed, the artifact its upload step would make. */ + large: Record; + published: Record; + deployed: { healthy: boolean; unchanged?: boolean; live?: string }; +} + +/** + * The pipeline of a push of `sha` to develop: the jobs of on_push, in their order. With `failing`, a large job may + * fail, and the run ends after the large jobs, since publish needs them all; otherwise every job must pass. + */ +async function pipeline(sha: string, failing = false): Promise { + const ci = { GITHUB_SHA: sha, GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }; + const testJob = await checkout(sha); + const test = await step(testJob, ['mise', 'run', 'test'], shared); + // The test job needs no built app (§ 1.5 of the verbs), a suite's app included. + assert.equal(existsSync(join(testJob, 'apps', 'web', '.next', 'standalone')), false, 'the test job built the app'); + + const planned = await checkout(sha); + const inventory = join(here, 'operations', 'inventory'); + const before = trustedLog.length; + const planOut = await step( + planned, + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'plan', '--deploy', '--inventory', inventory], + { ...ci, ...trusted }, + ); + const asked = artifactMethods(trustedLog.slice(before)); + const plan = JSON.parse(planOut.slice(planOut.indexOf('{\n'))); + assert.equal(plan.environment, 'staging'); + + const large: Run['large'] = {}; + for (const leg of (plan.legs as Leg[]).filter((l) => l.large)) { + const job = await checkout(sha); + const build = await step(job, ['mise', 'run', 'build', leg.app], { + ...trusted, + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY, + }); + for (const suite of leg.suites) + await step(join(job, suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); + const ran = await tryRun('mise', ['run', 'e2e', leg.app], job, { ...env, ...trusted }); + assert.ok(ran.ok || failing, `mise run e2e ${leg.app} failed in ${job}:\n${ran.output}`); + // The upload step, which on the forge runs after a failed E2E step alone; matrix.app is the leg's, the attempt the first. + const keep = uploadStep(); + const artifact = ran.ok + ? undefined + : { + name: keep.name.replace('${{ matrix.app }}', leg.app).replace('${{ github.run_attempt }}', '1'), + files: upload(job, keep.path), + }; + large[leg.app] = { build, e2e: ran.output, failed: !ran.ok, artifact }; + } + if (Object.values(large).some((job) => job.failed)) + return { test, plan, asked, large, published: {}, deployed: { healthy: false } }; + + const published: Run['published'] = {}; + for (const leg of plan.legs as Leg[]) { + const job = await checkout(sha); + const out = await step( + job, + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha, '--context', leg.context], + { ...ci, ...(leg.build && leg.context === 'output' ? trusted : {}), NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }, + ); + published[leg.app] = JSON.parse(out.slice(out.indexOf('{\n'))); + } + + const [target] = plan.deploys; + assert.ok(target, planOut); + const deployJob = await checkout(sha); + // Its name is the compose project's, unique to this run. + const appDir = join(here, 'stacks', `${basename(here).toLowerCase()}-web`); + mkdirSync(appDir, { recursive: true }); + if (!deployments.includes(appDir)) deployments.push(appDir); + // What the platform playbook writes beside the compose file. + writeFileSync(join(appDir, '.env'), `PLEXUS_LOOPBACK_PORT=${port}\n`); + const deployOut = await step(deployJob, [ + 'mise', + 'exec', + '--', + 'plx', + '--json', + 'deploy', + target.host, + target.app, + '--environment', + 'staging', + '--image', + target.image, + '--app-dir', + appDir, + ]); + const deployed = JSON.parse(deployOut.slice(deployOut.indexOf('{\n'))); + return { test, plan, asked, large, published, deployed }; +} + +/** The digest the registry holds under `ref`. */ +const digestOf = async (ref: string) => (await sh('mise', ['exec', CRANE, '--', 'crane', 'digest', ref], here)).trim(); + +/** The apps the plan gave a large job. */ +const withJob = (run: Run) => run.plan.legs.filter((l) => l.large).map((l) => l.app); + +/** Commits `edit` to a clone of the origin and pushes it; the new commit. */ +async function push(name: string, edit: (dir: string) => void | Promise): Promise { + const clone = join(here, name); + await gitOk(here, 'clone', '-q', origin, clone); + await edit(clone); + await gitOk(clone, 'add', '-A'); + await gitOk(clone, 'commit', '--no-verify', '--allow-empty', '-q', '-m', name); + await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); + return gitOk(clone, 'rev-parse', 'HEAD'); +} + +test('check and test build no app, a suite’s app included, and e2e builds the app before its suite', async () => { + const dir = await checkout(await gitOk(origin, 'rev-parse', 'HEAD')); + await step(dir, ['mise', 'run', 'install']); + for (const task of ['check', 'test']) assert.ok(!(await planned(dir, task)).includes('@acme/web#build'), task); + assert.deepEqual(await planned(dir, 'e2e'), ['@acme/web#build', '@acme/web-e2e#e2e', '@acme/web-e2e2#e2e']); +}); + +let first: Run; +let firstSha = ''; + +test('the first run gives both apps a large job, publishes each image from the output it built, and deploys web healthy', async () => { + firstSha = await gitOk(origin, 'rev-parse', 'HEAD'); + first = await pipeline(firstSha); + assert.deepEqual(withJob(first), ['site', 'web']); + const web = first.plan.legs.find((l) => l.app === 'web'); + assert.deepEqual(web && { ...web, hash: '' }, { + app: 'web', + hash: '', + runner: 'ubuntu-latest', + suites: ['e2e/web', 'e2e/web2'], + context: 'output', + build: true, + large: true, + }); + assert.match(first.large.web?.e2e ?? '', /\d+ passed \(/, 'the suite ran'); + for (const app of ['web', 'site']) { + assert.equal(first.published[app]?.built, true, app); + const image = `${registry}/acme/${app}`; + const hash = first.plan.legs.find((l) => l.app === app)?.hash; + const digest = await digestOf(`${image}:build-${hash}`); + assert.equal(await digestOf(`${image}:${firstSha}`), digest, `${app}: build- and the commit are one image`); + assert.equal(first.published[app]?.digest, digest); + } + assert.deepEqual(first.plan.deploys, [ + { app: 'web', host: 'ssh://deploy@app-host', image: `${registry}/acme/web:${firstSha}` }, + ]); + assert.equal(first.deployed.healthy, true, JSON.stringify(first.deployed)); + assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200); + // The plan only asks: HEAD requests, no artifact read or written. + assert.ok(first.asked.length > 0, 'the plan asked the trusted server'); + assert.deepEqual([...new Set(first.asked)], ['HEAD']); +}); + +test('a second run on the same content gives no app a large job, runs no task and builds no image, and the deploy leaves web running', async () => { + const sha = await push('push-2', () => {}); + const again = await pipeline(sha); + assert.deepEqual(withJob(again), []); + assert.deepEqual([...new Set(again.asked)], ['HEAD']); + const runs = summaries(again.test); + assert.ok(runs.length > 0, again.test); + for (const [cached, total] of runs) assert.equal(cached, total, `the test job runs a task:\n${again.test}`); + for (const app of ['web', 'site']) assert.equal(again.published[app]?.built, false, app); + assert.equal( + await digestOf(`${registry}/acme/web:${sha}`), + await digestOf(`${registry}/acme/web:${firstSha}`), + 'the new commit tags the image there', + ); + assert.equal(again.deployed.healthy, true); + assert.equal(again.deployed.unchanged, true, JSON.stringify(again.deployed)); +}); + +test('a change to a spec alone gives exactly web a large job, which runs its suite and no build, and builds no image', async () => { + const sha = await push('push-3', (dir) => { + const spec = join(dir, 'e2e', 'web', 'specs', 'home.spec.ts'); + writeFileSync(spec, `${readFileSync(spec, 'utf8')}// a spec edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['web']); + assert.equal(run.plan.legs.find((l) => l.app === 'web')?.hash, first.plan.legs.find((l) => l.app === 'web')?.hash); + for (const [cached, total] of summaries(run.large.web?.build ?? '')) + assert.equal(cached, total, run.large.web?.build); + assert.match(run.large.web?.e2e ?? '', /\d+ passed \(/, 'the suite ran again'); + for (const app of ['web', 'site']) assert.equal(run.published[app]?.built, false, app); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); + +test('a change to site alone gives exactly site a large job, and publish builds its image', async () => { + const sha = await push('push-4', (dir) => { + const page = join(dir, 'apps', 'site', 'src', 'app', 'page.tsx'); + writeFileSync(page, `${readFileSync(page, 'utf8')}// site edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['site']); + assert.equal(run.published.site?.built, true); + assert.equal(run.published.web?.built, false); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); + +test('a change to a spec of web’s second suite alone gives web a large job, which runs both suites', async () => { + const sha = await push('push-5', (dir) => { + const spec = join(dir, 'e2e', 'web2', 'specs', 'home.spec.ts'); + writeFileSync(spec, `${readFileSync(spec, 'utf8')}// the second suite's spec edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['web']); + assert.equal([...(run.large.web?.e2e ?? '').matchAll(/\d+ passed \(/g)].length, 2, 'both suites ran'); + for (const app of ['web', 'site']) assert.equal(run.published[app]?.built, false, app); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); + +test('a failed suite fails its large job, which keeps the failed suites’ results, one artifact per app, and nothing is published', async () => { + /** A spec that fails, as its suite's own. */ + const failing = (what: string) => + `import { expect, test } from '@playwright/test';\n\ntest('${what}', async ({ page }) => {\n await page.goto('/');\n await expect(page.getByRole('heading', { level: 1 })).toHaveText('not the name of the app');\n});\n`; + const sha = await push('push-6', async (dir) => { + put(dir, { 'e2e/web2/specs/fails.spec.ts': failing('the second suite of web fails') }); + // site's first suite, which fails. + await born(join(dir, 'e2e', 'site'), ['e2e-playwright'], { app: '@acme/site' }); + put(dir, { 'e2e/site/specs/fails.spec.ts': failing('the suite of site fails') }); + await relock(dir); + }); + const run = await pipeline(sha, true); + assert.deepEqual(withJob(run), ['site', 'web']); + assert.deepEqual(run.published, {}, 'publish needs every large job'); + const { name, path } = uploadStep(); + assert.equal(path, 'e2e/*/test-results/'); + for (const [app, suite] of [ + ['web', 'web2'], + ['site', 'site'], + ] as const) { + const job = run.large[app]; + assert.equal(job?.failed, true, `${app}: ${job?.e2e}`); + assert.match(job?.e2e ?? '', /\d+ failed/, app); + const artifact = job?.artifact; + assert.equal(artifact?.name, `e2e-${app}-attempt-1`, name); + // Only the failed suite's results, under its directory name; what the passed suite of web left is hidden. + assert.ok((artifact?.files.length ?? 0) > 0, `${app}: nothing to keep`); + for (const file of artifact?.files ?? []) assert.ok(file.startsWith(`${suite}/test-results/`), `${app}: ${file}`); + } +}); diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index a55364ff..36622a06 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -1,11 +1,11 @@ // A newborn operations repo, born as a repo is with updates beside its -// template, passes its own `verify`, lint, `plx doctor` and the playbooks' -// syntax, in each shape that changes what is generated; the collections go +// template, passes its own five verbs, with `plx doctor`, lint and the playbooks' +// syntax in `check`, in each shape that changes what is generated; the collections go // into the scratch directory, not into ~/.ansible. Created by `plx new`; it // needs the network (`mise install`, the collections). import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, open, verify } from './helpers.ts'; +import { born, close, open, pass } from './helpers.ts'; let here = ''; before(async () => { @@ -17,15 +17,14 @@ const SHAPES: [string, Record][] = [ ['github', {}], ['hybrid', { infrastructure: 'true', ci_strategy: 'hybrid', pr_reviewers: 'reviewer-a,reviewer-b' }], ['on-prem', { ci_strategy: 'on-prem', ci_overlay: 'netbird' }], - ['own-registry', { ci_registry: 'own' }], ]; +/** The verbs a repo answers with a verdict, each from the checkout as it is. */ +const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; + for (const [name, answers] of SHAPES) - test(`a newborn operations repo (${name}) passes its own verify`, async () => { + test(`a newborn operations repo (${name}) passes its own five verbs`, async () => { const env = { ANSIBLE_COLLECTIONS_PATH: join(here, 'collections') }; - await verify( - await born(join(here, name), ['repo-operations', 'updates'], { tenant: 'acme', ...answers }, env), - name, - env, - ); + const dir = await born(join(here, name), ['repo-operations', 'updates'], { tenant: 'acme', ...answers }, env); + for (const verb of VERBS) await pass(dir, name, verb, env); }); diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 64e11a9a..62d4cd3b 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -1,20 +1,27 @@ // A newborn repo of the Turborepo template, born as a repo is with updates -// beside its template, passes its own `verify`, in each shape that changes -// what is generated: an app repo, a package repo, each also with the tenant's -// private packages, and an app repo also with display versions. In an app repo a verb scopes to an app or a package by name, with -// what it depends on, and refuses an unknown one. A package repo also has what -// a release needs: a workspace package with a pending changeset passes -// `verify`, scoped to it by name, and `changeset version` takes the changeset -// in, with a changelog that `verify` then accepts. Created by `plx new`; it needs -// the network (`mise install`, `pnpm add`). +// beside its template, passes its own four verdicts (`check`, `test`, `build`, +// `e2e`) in each shape that changes what is generated: an app repo, a package +// repo, each also with the tenant's private packages, an app repo also with +// display versions, and one repo with the answer `postgres`, which installs +// the binary and shows its version. `check`, `build` and `test` scope to an +// app or a package by name with what it depends on, `e2e` with what depends on +// it, and each refuses an unknown name. Editing a test file moves the hash of +// `test` and leaves the hash of `build`; the answer's major moves `test` and +// `e2e` and nothing else. The pre-commit hook fixes a format error and accepts +// the commit, and refuses it without `depends = "lint"`. `mise e2e` works first +// in a fresh clone. A package repo also has what a release needs: a workspace +// package with a pending changeset passes `test`, scoped to it by name, and +// `changeset version` takes the changeset in, with a changelog that `check` +// then accepts. Created by `plx new`; it needs the network (`mise install`, +// `pnpm add`). // // mise run newborn # every template // KEEP=1 mise run newborn # leave the newborns in place and say where import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, mise, open, put, sh, verify } from './helpers.ts'; +import { born, close, git, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -22,13 +29,43 @@ before(async () => { }); after(close); -const newborn = (name: string, answers: Record = {}) => - born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); +/** A newborn, which has no `verify` task. */ +async function newborn(name: string, answers: Record = {}): Promise { + const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + assert.doesNotMatch(read(dir, 'mise.toml'), /^\[tasks\.verify\]/m, 'a repo is born without verify'); + return dir; +} const read = (dir: string, file: string) => readFileSync(join(dir, file), 'utf8'); -/** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ -const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); +/** The verbs a repo answers with a verdict, each from the checkout as it is. */ +const VERDICTS = ['check', 'test', 'build', 'e2e']; + +async function passesItsVerbs(dir: string, name: string): Promise { + for (const verb of VERDICTS) await pass(dir, name, verb); +} + +/** The hashes of the tasks `turbo run ` would run for one package and what it needs, by task id, from a dry run. */ +async function hashes(dir: string, pkg: string, tasks: string[]): Promise> { + const ran = await tryRun('mise', ['exec', '--', 'turbo', 'run', ...tasks, `--filter=${pkg}`, '--dry=json'], dir); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + return Object.fromEntries(dry.tasks.map((t: { taskId: string; hash: string }) => [t.taskId, t.hash])); +} + +/** Projects of a newborn: each prints what it did, so that a run shows which ones it ran. `needs` are workspace dependencies. */ +function projects(dir: string, specs: Record): void { + for (const [name, { verbs, needs = [] }] of Object.entries(specs)) + put(dir, { + [`packages/${name}/package.json`]: { + name, + version: '0.0.0', + private: true, + scripts: Object.fromEntries(verbs.map((verb) => [verb, `echo ${verb}-ran packages/${name}`])), + dependencies: Object.fromEntries(needs.map((need) => [need, 'workspace:*'])), + }, + }); +} describe('an app repo', () => { let dir = ''; @@ -36,43 +73,179 @@ describe('an app repo', () => { dir = await newborn('app'); }); - test('passes its own verify, and has no display versions unasked', async () => { - await verify(dir, 'app'); + test('passes its own verbs, and has no display versions unasked', async () => { + await passesItsVerbs(dir, 'app'); assert.doesNotMatch(read(dir, '.github/workflows/on_push.yml'), /display-versions|contents: write/); assert.doesNotMatch(read(dir, 'PLEXUS.md'), /^major:/m); }); - test('scopes a verb to an app or a package by name, with what it depends on', async () => { + test('scopes a verb to a project by name: with what it depends on, e2e with what depends on it, and refuses an unknown name', async () => { + // Under packages/, where plx doctor asks nothing of a project, so that a refusal can only be the name's. + projects(dir, { + 'demo-lib': { verbs: ['build', 'check', 'test'] }, + 'demo-app': { verbs: ['build', 'check', 'test', 'e2e'], needs: ['demo-lib'] }, + 'demo-other': { verbs: ['build', 'check', 'test', 'e2e'] }, + }); + await relock(dir); + for (const verb of ['build', 'check', 'test']) { + const app = await mise(dir, verb, 'demo-app'); + assert.ok(app.ok, app.output); + assert.match(app.output, new RegExp(`${verb}-ran packages/demo-app`), `${verb} of the app`); + assert.match(app.output, new RegExp(`${verb}-ran packages/demo-lib`), `${verb} of what the app depends on`); + assert.doesNotMatch(app.output, new RegExp(`${verb}-ran packages/demo-other`), `${verb} of no other project`); + const lib = await mise(dir, verb, 'demo-lib'); + assert.ok(lib.ok, lib.output); + assert.match(lib.output, new RegExp(`${verb}-ran packages/demo-lib`)); + assert.doesNotMatch(lib.output, new RegExp(`${verb}-ran packages/demo-(app|other)`), `${verb} of no dependent`); + } + // test runs check first, with the same name. + const tested = await mise(dir, 'test', 'demo-lib'); + assert.match(tested.output, /check-ran packages\/demo-lib/); + assert.doesNotMatch(tested.output, /check-ran packages\/demo-(app|other)/, 'the name goes on to check'); + const suite = await mise(dir, 'e2e', 'demo-lib'); + assert.ok(suite.ok, suite.output); + assert.match(suite.output, /e2e-ran packages\/demo-app/, 'the suite of a dependent runs'); + assert.doesNotMatch(suite.output, /e2e-ran packages\/demo-other/, 'and of no unrelated project'); + for (const verb of VERDICTS) { + const unknown = await mise(dir, verb, 'demo-none'); + assert.equal(unknown.ok, false, `${verb} refuses an unknown name`); + assert.match(unknown.output, /no app or package demo-none/, `${verb} says why`); + } + }); +}); + +test('in a repo with one app, editing a test file moves the hash of test and leaves the hash of build', async () => { + // A repo of its own: the app has no marker or compose file, which only a run of plx doctor would ask for. + const dir = await newborn('one-app'); + put(dir, { + 'apps/hashed/package.json': { + name: 'hashed', + version: '0.0.0', + private: true, + scripts: { build: 'echo built', check: 'echo checked', test: 'echo tested' }, + }, + 'apps/hashed/src/index.ts': 'export const answer = 42;\n', + 'apps/hashed/src/index.test.ts': 'export const first = 1;\n', + }); + await relock(dir); + const before = await hashes(dir, 'hashed', ['build', 'test']); + put(dir, { 'apps/hashed/src/index.test.ts': 'export const first = 2;\n' }); + const after = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(after['hashed#test'], before['hashed#test'], 'the test file is an input of test'); + assert.equal(after['hashed#build'], before['hashed#build'], 'and of no build'); + put(dir, { 'apps/hashed/src/index.ts': 'export const answer = 43;\n' }); + const edited = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(edited['hashed#build'], after['hashed#build'], 'a source file still moves the build'); +}); + +test('mise e2e works first in a fresh clone: it installs what it needs', async () => { + const dir = await newborn('fresh'); + projects(dir, { suite: { verbs: ['e2e'] } }); + await relock(dir); + await git(dir, 'add', '-A'); + const committed = await git(dir, 'commit', '--no-verify', '-q', '-m', 'born'); + assert.ok(committed.ok, committed.output); + const clone = join(here, 'fresh-clone'); + const cloned = await git(here, 'clone', '-q', dir, clone); + assert.ok(cloned.ok, cloned.output); + const installed = await tryRun('sh', ['-c', 'mise trust && mise install'], clone); + assert.ok(installed.ok, installed.output); + const ran = await mise(clone, 'e2e'); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /e2e-ran packages\/suite/); +}); + +describe('the hooks', () => { + const UNFORMATTED = 'export const a = {b: 1};\n'; + let dir = ''; + before(async () => { + dir = await newborn('hooks'); + projects(dir, { fmt: { verbs: ['check', 'test'] } }); + await relock(dir); + await git(dir, 'add', '-A'); + const first = await git(dir, 'commit', '-q', '-m', 'born'); + assert.ok(first.ok, first.output); + }); + + test('a commit with a fixable format error is fixed and accepted; without depends = lint it is refused', async () => { + put(dir, { 'packages/fmt/src/one.ts': UNFORMATTED }); + await git(dir, 'add', '-A'); + const fixed = await git(dir, 'commit', '-m', 'one'); + assert.ok(fixed.ok, fixed.output); + assert.notEqual(read(dir, 'packages/fmt/src/one.ts'), UNFORMATTED, 'the lint fixed the file'); + assert.equal((await git(dir, 'status', '--porcelain')).output.trim(), '', 'and the fix is in the commit'); + + const hook = read(dir, 'hk.pkl'); + assert.match(hook, /^ *depends = "lint"\n/m); + writeFileSync(join(dir, 'hk.pkl'), hook.replace(/^ *depends = "lint"\n/m, '')); + await git(dir, 'add', '-A'); + const unhooked = await git(dir, 'commit', '--no-verify', '-q', '-m', 'without depends'); + assert.ok(unhooked.ok, unhooked.output); + put(dir, { 'packages/fmt/src/two.ts': UNFORMATTED }); + await git(dir, 'add', '-A'); + const refused = await git(dir, 'commit', '-m', 'two'); + assert.equal(refused.ok, false, 'check runs beside the fix and sees the unformatted file'); + }); +}); + +describe('a repo that answers postgres', () => { + let dir = ''; + before(async () => { + dir = await newborn('postgres', { postgres: '18.6' }); + projects(dir, { 'pg-lib': { verbs: ['build'] } }); + // What a test of the app sees of the database: the major, which only a variable declared in env reaches. put(dir, { - 'apps/demo-app/package.json': { - name: 'demo-app', + 'packages/pg-app/package.json': { + name: 'pg-app', version: '0.0.0', private: true, - scripts: { test: 'echo tested apps/demo-app' }, - dependencies: { 'demo-lib': 'workspace:*' }, - }, - 'packages/demo-lib/package.json': { - name: 'demo-lib', - version: '0.0.0', - private: true, - scripts: { test: 'echo tested packages/demo-lib' }, + scripts: { + build: 'echo built', + check: 'echo checked', + test: 'echo major=$PLX_POSTGRES_MAJOR', + e2e: 'echo e2e', + }, + dependencies: { 'pg-lib': 'workspace:*' }, }, }); await relock(dir); - const app = await mise(dir, 'test', 'demo-app'); - assert.ok(app.ok, app.output); - assert.match(app.output, /tested apps\/demo-app/); - assert.match(app.output, /tested packages\/demo-lib/, 'the dependency is tested with the app'); - const lib = await mise(dir, 'test', 'demo-lib'); - assert.ok(lib.ok, lib.output); - assert.match(lib.output, /tested packages\/demo-lib/); - assert.doesNotMatch(lib.output, /tested apps\/demo-app/, 'never a dependent'); - assert.equal((await mise(dir, 'test', 'demo-none')).ok, false, 'an unknown name is refused'); + }); + + test('installs the binary at that version, and the test of an app sees the major', async () => { + appendTask(dir); + const version = await mise(dir, 'postgres-version'); + assert.ok(version.ok, version.output); + assert.match(version.output, /postgres \(PostgreSQL\) 18\.6\b/); + const tested = await mise(dir, 'test'); + assert.ok(tested.ok, tested.output); + assert.match(tested.output, /major=18/); + await passesItsVerbs(dir, 'postgres'); + }); + + test('changing the major moves the hashes of test and e2e and of nothing else', async () => { + const tasks = ['build', 'check', 'test', 'e2e']; + const before = await hashes(dir, 'pg-app', tasks); + // What plx apply writes to mise.toml for the answer 17.12; the binary is not installed for a hash. + writeFileSync( + join(dir, 'mise.toml'), + read(dir, 'mise.toml').replace('PLX_POSTGRES_MAJOR = "18"', 'PLX_POSTGRES_MAJOR = "17"'), + ); + const after = await hashes(dir, 'pg-app', tasks); + const moved = Object.keys(after).filter((id) => after[id] !== before[id]); + assert.deepEqual(moved.sort(), ['pg-app#e2e', 'pg-app#test']); }); }); -test('a private app repo with reviewers passes its own verify', async () => { - await verify( +/** A root task that runs the database server's binary, as a test of an app would. */ +function appendTask(dir: string): void { + writeFileSync( + join(dir, 'mise.toml'), + `${read(dir, 'mise.toml')}\n[tasks.postgres-version]\ndescription = "The version of the pinned binary"\nrun = "postgres --version"\n`, + ); +} + +test('a private app repo with reviewers passes its own verbs', async () => { + await passesItsVerbs( await newborn('private-app', { private_packages_scope: '@acme', pr_reviewers: 'reviewer-a,reviewer-b' }), 'private-app', ); @@ -80,7 +253,7 @@ test('a private app repo with reviewers passes its own verify', async () => { test('an app repo with display versions asks for them and states its major', async () => { const dir = await newborn('versioned-app', { display_versions: 'true' }); - await verify(dir, 'versioned-app'); + await passesItsVerbs(dir, 'versioned-app'); assert.match(read(dir, '.github/workflows/on_push.yml'), /display-versions: true/); assert.match(read(dir, 'PLEXUS.md'), /^major: 1$/m); }); @@ -89,9 +262,9 @@ for (const [name, answers] of [ ['packages', { publishes_packages: 'true' }], ['private-packages', { publishes_packages: 'true', package_registry: 'github', private_packages_scope: '@acme' }], ] as const) { - test(`a package repo (${name}) passes its own verify and takes a changeset in`, async () => { + test(`a package repo (${name}) passes its own verbs and takes a changeset in`, async () => { const dir = await newborn(name, answers); - await verify(dir, name); + await passesItsVerbs(dir, name); put(dir, { 'packages/demo/package.json': { name: '@acme/demo', @@ -101,11 +274,11 @@ for (const [name, answers] of [ '.changeset/first-change.md': '---\n"@acme/demo": minor\n---\n\nA first change.\n', }); await relock(dir); - const scoped = await mise(dir, 'verify', 'demo'); + const scoped = await mise(dir, 'test', 'demo'); assert.ok(scoped.ok, scoped.output); await sh('mise', ['exec', '--', 'pnpm', 'exec', 'changeset', 'version'], dir); assert.match(read(dir, 'packages/demo/package.json'), /"version": "0\.2\.0"/); assert.match(read(dir, 'packages/demo/CHANGELOG.md'), /^## 0\.2\.0\n\n### Minor Changes\n\n- A first change\.$/m); - await verify(dir, name); + await pass(dir, name, 'check'); }); } diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts new file mode 100644 index 00000000..9c7f8d51 --- /dev/null +++ b/newborns/turbo-cache.test.ts @@ -0,0 +1,262 @@ +// A newborn app repo with Turbo's two remote caches (repo-turbo's turbow, and +// the step .github/actions/turbo-cache of this repo), against a real cache +// server and an S3 stand-in. The stand-in is RustFS in a container, published +// on a free loopback port, with the tenant acme's two buckets; the server is +// the binary the step's action starts, fetched at the commit the step pins. +// +// On a developer's machine (outside a job of the forge, whatever CI says), with +// the shared server running without a token as a developer runs it: `mise +// test` writes the shared bucket under the team acme-web, and a second clone, +// by another remote form of the same repo, hits every task; `mise build` and +// `mise e2e` use the shared server too. With a Turbo login and a linked repo +// but no server, no verb sends a request anywhere. +// In a job of the forge (GITHUB_ACTIONS=true), run as a job runs the step: its +// scripts plan and announce around the server, which is started with the +// environment the step gives the action, and the vault's read stood in for by +// the stand-in's keys. With the trusted server, `build` and `e2e` write the +// trusted bucket and the shared server sees no request; `check` and `test` find +// no shared server in that job and run without one. With both servers in one +// checkout, a build after a test reads nothing of the local cache the test +// filled. Where the tenant has no bucket the verbs run without a remote cache; +// without the step `build` fails. Every case sets or unsets GITHUB_ACTIONS +// itself. Needs Docker and the network, as the newborns do. +import assert from 'node:assert/strict'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { type Caches, requests, startCaches } from './caches.ts'; +import { born, close, freePort, open, put, relock, sh, tryRun } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); +const SHARED_BUCKET = 'acme-ci-turbo'; +const TRUSTED_BUCKET = 'acme-ci-turbo-trusted'; + +let here = ''; +let caches: Caches | undefined; + +/** The keys of a bucket below a team, as the server writes them: `/`. */ +const keys = (bucket: string, team = 'acme-web') => (caches as Caches).keys(bucket, team); + +/** A cache server for `bucket` on `port`, with `token` where given; its log. */ +const serve = (bucket: string, port: number, token?: string) => (caches as Caches).serve(bucket, port, token); + +before(async () => { + here = await open('turbo-cache'); + caches = await startCaches(here, [SHARED_BUCKET, TRUSTED_BUCKET]); +}); + +after(async () => { + await caches?.stop(); + await close(); +}); + +/** git with an identity and no signing, as a newborn has neither. */ +const git = (dir: string, ...args: string[]) => + sh( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + +/** A fresh clone of `from`, its origin at `remote`, with its tools installed: what a checkout on another machine is. */ +async function clone(from: string, name: string, remote: string): Promise { + const dir = join(here, name); + await git(here, 'clone', '-q', from, dir); + await git(dir, 'remote', 'set-url', 'origin', remote); + await sh('sh', ['-c', 'mise trust && mise install'], dir); + return dir; +} + +/** `mise run ` in `dir` with `env`, which must pass; its output. */ +async function verb(dir: string, task: string, env: Record): Promise { + const ran = await tryRun('mise', ['run', task], dir, env); + if (!ran.ok) throw new Error(`mise run ${task} failed in ${dir}:\n${ran.output}`); + return ran.output; +} + +/** The lines `KEY=value` a step wrote to a file of the runner's, GITHUB_OUTPUT or GITHUB_ENV. */ +const pairs = (file: string): Record => + Object.fromEntries( + readFileSync(file, 'utf8') + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), + ); + +let runs = 0; +/** One phase of the step's script, as its action runs it: `env` and the runner's files; what it wrote to each. */ +async function step(phase: string, env: Record) { + const n = runs++; + const output = join(here, `github-output-${n}`); + const githubEnv = join(here, `github-env-${n}`); + writeFileSync(output, ''); + writeFileSync(githubEnv, ''); + const ran = await tryRun('bash', [join(STEP, 'turbo-cache.sh'), phase], here, { + GITHUB_OUTPUT: output, + GITHUB_ENV: githubEnv, + OP_CONNECT_HOST: '', + OP_CONNECT_TOKEN: '', + ...env, + }); + assert.ok(ran.ok, ran.output); + return { said: ran.output, outputs: pairs(output), env: pairs(githubEnv) }; +} + +describe('a newborn app repo with the two remote caches', () => { + let origin = ''; + let sharedUrl = ''; + let sharedLog: string[] = []; + before(async () => { + origin = await born(join(here, 'web'), ['repo-turbo', 'updates'], { tenant: 'acme' }); + // A package and an app built from it, each writing its build output and printing what it ran. + const scripts = (name: string) => ({ + build: `mkdir -p dist && echo ${name} > dist/out.txt && echo build-ran ${name}`, + check: `echo check-ran ${name}`, + test: `echo test-ran ${name}`, + e2e: `echo e2e-ran ${name}`, + }); + put(origin, { + 'packages/lib/package.json': { name: 'lib', version: '0.0.0', private: true, scripts: scripts('lib') }, + 'packages/site/package.json': { + name: 'site', + version: '0.0.0', + private: true, + scripts: scripts('site'), + dependencies: { lib: 'workspace:*' }, + }, + }); + await relock(origin); + await git(origin, 'add', '-A'); + await git(origin, 'commit', '--no-verify', '-q', '-m', 'born'); + const port = await freePort(); + sharedUrl = `http://127.0.0.1:${port}`; + sharedLog = await serve(SHARED_BUCKET, port); + }); + + /** A server the step plans, starts and announces in a job, for `cache`: what the job's later steps get. */ + async function jobServer(cache: 'shared' | 'trusted'): Promise> { + const plan = await step('plan', { CACHE: cache, OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); + const port = Number(plan.outputs.port); + const token = plan.outputs.token ?? ''; + // What the action is given by the step: the planned port and token, the bucket, and the keys the vault holds. + await serve(plan.outputs.bucket ?? '', port, token); + const told = await step('announce', { + CACHE: cache, + KEYS: 'success', + SERVER: 'success', + PORT: String(port), + TOKEN: token, + }); + return told.env; + } + + /** A task's miss as Turbo prints it, in a job of the forge as a group of the log. */ + const missed = (task: string) => new RegExp(`(?:${task}: |::group::${task}\\n)cache miss, executing`); + + /** A developer's machine: no job of the forge, though CI may be set there too. */ + const machine = () => ({ GITHUB_ACTIONS: '', CI: 'true', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '' }); + + test('on a developer’s machine, mise test writes the shared bucket, and a second clone hits it', async () => { + const first = await clone(origin, 'first', 'https://github.com/acme/web.git'); + const tested = await verb(first, 'test', machine()); + assert.match(tested, /turbow: the shared remote cache at http:\/\/127\.0\.0\.1:\d+, team acme-web/); + assert.match(tested, /test-ran site/); + const written = await keys(SHARED_BUCKET); + assert.ok(written.length >= 4, `the shared bucket holds the run's tasks under acme-web: ${written}`); + + const second = await clone(origin, 'second', 'git@github.com:acme/web.git'); + const again = await verb(second, 'test', machine()); + assert.match(again, /cache hit, replaying logs/); + assert.doesNotMatch(again, /cache miss/, 'every task of the second clone is a hit'); + + // Outside a job there is no trusted server: build and e2e use the shared one, CI set or not. + for (const task of ['build', 'e2e']) + assert.match(await verb(second, task, machine()), /turbow: the shared remote cache at /, task); + }); + + test('on a developer’s machine with a Turbo login and a linked repo, a verb without a server sends nothing anywhere', async () => { + let hits = 0; + const listener = createServer((req, res) => { + hits++; + req.resume(); + res.statusCode = 404; + res.end(); + }); + const port = await freePort(); + await new Promise((resolve) => listener.listen(port, '127.0.0.1', resolve)); + try { + const linked = await clone(origin, 'linked', 'https://github.com/acme/web'); + // What `turbo link` leaves in the checkout, and `turbo login` in Turbo's configuration directory, which + // TURBO_CONFIG_DIR_PATH names (read by Turbo 2.11.13 as run, not documented). + put(linked, { '.turbo/config.json': { apiUrl: `http://127.0.0.1:${port}`, teamSlug: 'linked' } }); + put(here, { 'turbo-login/turborepo/config.json': { token: 'a-login-token' } }); + const env = { ...machine(), PLX_TURBO_SHARED: 'none', TURBO_CONFIG_DIR_PATH: join(here, 'turbo-login') }; + for (const task of ['check', 'test', 'build', 'e2e']) { + const ran = await verb(linked, task, env); + assert.match(ran, /turbow: without a remote cache/, task); + assert.match(ran, /Remote caching disabled/, task); + } + assert.equal(hits, 0, 'no request reached the linked server'); + // The control: Turbo alone sends the linked team's artifacts with the login token. + const alone = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'check', '--force'], linked, env); + assert.ok(alone.ok, alone.output); + assert.ok(hits > 0, 'Turbo alone reaches the linked server'); + } finally { + await new Promise((resolve) => listener.close(() => resolve())); + } + }); + + test('in a job with the step’s trusted server, build and e2e write the trusted bucket, and the shared server sees nothing', async () => { + const job = await clone(origin, 'trusted-job', 'https://github.com/acme/web'); + const told = await jobServer('trusted'); + assert.deepEqual(Object.keys(told).sort(), ['PLX_TURBO_TRUSTED', 'PLX_TURBO_TRUSTED_TOKEN']); + const before = requests(sharedLog).length; + const env = { GITHUB_ACTIONS: 'true', CI: 'true', PLX_TURBO_SHARED: '', ...told }; + for (const task of ['build', 'e2e']) + assert.match(await verb(job, task, env), /turbow: the trusted remote cache at /, task); + assert.ok((await keys(TRUSTED_BUCKET)).length >= 3, 'the trusted bucket holds the builds and the e2e runs'); + const tested = await verb(job, 'test', env); + assert.match(tested, /turbow: without a remote cache: this job started no shared cache server/); + assert.equal(requests(sharedLog).length, before, 'the shared server saw no request from the job'); + }); + + test('in a job with both servers, a build after a test in one checkout reads nothing the test left in the local cache', async () => { + // A repo of its own name, so that neither bucket holds its tasks yet. + const job = await clone(origin, 'one-checkout', 'https://github.com/acme/one-checkout'); + const env = { GITHUB_ACTIONS: 'true', CI: 'true', ...(await jobServer('shared')), ...(await jobServer('trusted')) }; + const tested = await verb(job, 'test', env); + assert.match(tested, missed('lib:build'), 'the test built lib, into the local cache'); + const built = await verb(job, 'build', env); + assert.doesNotMatch(built, /cache hit/, 'nothing replayed'); + assert.match(built, missed('lib:build')); + assert.match(built, missed('site:build')); + assert.equal((await keys(TRUSTED_BUCKET, 'acme-one-checkout')).length, 2, 'both builds reached the trusted bucket'); + }); + + test('in a job where the tenant has no bucket, the step says so and every verb runs without a remote cache', async () => { + const job = await clone(origin, 'bucketless-job', 'https://github.com/acme/web'); + const plan = await step('plan', { CACHE: 'trusted', OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'false' }); + assert.equal(plan.outputs.read, 'false'); + const told = await step('announce', { CACHE: 'trusted', KEYS: 'skipped', SERVER: 'skipped' }); + assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: 'none' }); + assert.match(told.said, /without the trusted remote cache/); + const built = await verb(job, 'build', { GITHUB_ACTIONS: 'true', CI: 'true', PLX_TURBO_SHARED: '', ...told.env }); + assert.match(built, /turbow: without a remote cache: the tenant has no trusted bucket/); + assert.match(built, /build-ran site/); + }); + + test('in a job without the step, build fails and says why', async () => { + const job = await clone(origin, 'stepless-job', 'https://github.com/acme/web'); + const ran = await tryRun('mise', ['run', 'build'], job, { + GITHUB_ACTIONS: 'true', + CI: 'true', + PLX_TURBO_SHARED: sharedUrl, + PLX_TURBO_TRUSTED: '', + }); + assert.equal(ran.ok, false); + assert.match(ran.output, /in a job of the forge, build and e2e need the trusted cache server/); + assert.doesNotMatch(ran.output, /build-ran/); + }); +}); diff --git a/packages/cli-ci/package.json b/packages/cli-ci/package.json index a0cd5717..1bcf858f 100644 --- a/packages/cli-ci/package.json +++ b/packages/cli-ci/package.json @@ -1,7 +1,7 @@ { "name": "@plexus-ms/cli-ci", "version": "0.133.0", - "description": "plx-ci, the CI verbs of Plexus: throwaway runners on a cloud, a registry on object storage, reproducible image builds, and their teardown", + "description": "plx-ci, the CI verbs of Plexus: the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown", "license": "GPL-3.0-or-later", "type": "module", "bin": { diff --git a/packages/cli-ci/src/commands/build.ts b/packages/cli-ci/src/commands/build.ts deleted file mode 100644 index 970c35c5..00000000 --- a/packages/cli-ci/src/commands/build.ts +++ /dev/null @@ -1,55 +0,0 @@ -// plx-ci build [tag...]: one app's image from its pruned -// context, with the registry as cache, pushed as build- and the extra -// tags, and as too where the candidates have a registry of their own -// (§§ 4 and 8 PLX-Delivery). From the environment: CI_STRATEGY, CI_REGISTRY; -// NEXT_SERVER_ACTIONS_ENCRYPTION_KEY (the app's fixed key), NO_CACHE=1 for a -// build from scratch, BUILDX_BUILDER (default ci), NPM_CONFIG_USERCONFIG (a -// user-level npmrc with the token of the tenant's private package registry, -// handed to the image's installs as a secret). Prints the digest, and writes -// it to GITHUB_OUTPUT when that is set. -// -// plx-ci build website 0f2a3f35123dfd73 "$GITHUB_SHA" -// NO_CACHE=1 plx-ci build website 0f2a3f35123dfd73 "$GITHUB_SHA" repro--1 -import { appendFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { build } from '../core/build.ts'; -import { contextOf } from '../program.ts'; -import { registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('build')) - .description('build one app’s image from its pruned context against the registry and push it') - .argument('', 'the app, apps/ in the checkout') - .argument('', 'Turbo’s hash of the app’s build task') - .argument('', 'the commit, a second tag') - .argument('[tags...]', 'further tags on the same image') - .option('-C, --dir ', 'the checkout to read', '.') - .action( - async ( - app: string, - hash: string, - sha: string, - tags: string[], - opts: { strategy?: string; dir: string }, - command: Command, - ) => { - const ctx = contextOf(command); - const result = await build(ctx, { - app, - hash, - sha, - tags, - encryptionKey: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', - npmrc: process.env.NPM_CONFIG_USERCONFIG || undefined, - noCache: process.env.NO_CACHE === '1', - dir: resolve(opts.dir), - registry: registryFor(settings(opts)), - builder: process.env.BUILDX_BUILDER, - }); - ctx.result(result, (r) => r.digest ?? ''); - if (process.env.GITHUB_OUTPUT && result.digest) - appendFileSync(process.env.GITHUB_OUTPUT, `digest=${result.digest}\n`); - }, - ); -} diff --git a/packages/cli-ci/src/commands/displayVersions.ts b/packages/cli-ci/src/commands/displayVersions.ts index 622e8fed..fcb23677 100644 --- a/packages/cli-ci/src/commands/displayVersions.ts +++ b/packages/cli-ci/src/commands/displayVersions.ts @@ -26,7 +26,7 @@ import { displayVersions, tagDisplayVersion } from '../core/displayVersions.ts'; import { contextOf } from '../program.ts'; import { imagePrefix, need } from './shared.ts'; -/** The app names of _verify.yml's output `deploys`. */ +/** The app names of _e2e.yml's output `deploys`. */ export function appsOfDeploys(json: string): string[] { let data: unknown; try { @@ -48,7 +48,7 @@ export function register(program: Command): void { .description('the string each deployed app shows as its version, and the version a production release cuts') .argument('', 'the environment released into') .argument('', 'the commit released') - .requiredOption('--deploys ', 'the deploys, _verify.yml’s output `deploys`') + .requiredOption('--deploys ', 'the deploys, _e2e.yml’s output `deploys`') .option('-C, --dir ', 'the checkout to read, with its tags', '.') .action(async (environment: string, sha: string, opts: { deploys: string; dir: string }, command: Command) => { const ctx = contextOf(command); diff --git a/packages/cli-ci/src/commands/hybrid.test.ts b/packages/cli-ci/src/commands/hybrid.test.ts new file mode 100644 index 00000000..9f072a74 --- /dev/null +++ b/packages/cli-ci/src/commands/hybrid.test.ts @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { version } from '../program.ts'; +import { launchOptionsFromEnv } from './hybrid.ts'; + +const env = { + GITHUB_REPOSITORY: 'acme/web', + GITHUB_RUN_ID: '41', + GITHUB_RUN_ATTEMPT: '1', + RUNNER_TOKEN: 'ghs_x', + SELF_DELETE_KEY: 'EXOsd', + SELF_DELETE_SECRET: 'sd', + NO_JOB_MINUTES: '10', + DEATH_MINUTES: '45', + POWEROFF_MINUTES: '50', +}; + +test('an instance runs its job in the environment image of this plx-ci’s version', () => { + assert.equal(launchOptionsFromEnv(env).image, `ghcr.io/plexus-ms/ci-runner:${version}`); +}); + +test('RUNNER_IMAGE names another, an unreleased build of it for a trial', () => { + const image = 'ghcr.io/plexus-ms/ci-runner:sha-abc'; + assert.equal(launchOptionsFromEnv({ ...env, RUNNER_IMAGE: image }).image, image); +}); diff --git a/packages/cli-ci/src/commands/hybrid.ts b/packages/cli-ci/src/commands/hybrid.ts index ecb6a717..917e4206 100644 --- a/packages/cli-ci/src/commands/hybrid.ts +++ b/packages/cli-ci/src/commands/hybrid.ts @@ -2,13 +2,15 @@ // throwaway instances its large jobs run on. // // create-instances : one instance per leg of the plan, for the -// app's build, its test or both, at once, each waited for until its runner is online; +// app's e2e job, at once, each waited for until its runner is online; // one that misses is kept, stopped and mailed about, and replaced once. From // the environment: GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT; // RUNNER_TOKEN (Administration: write on the repo); EXOSCALE_API_KEY/_SECRET -// (ci-launch); SELF_DELETE_KEY/_SECRET; SELF_LAYERS; SMTP_* and MAIL_*, -// REGISTRY_* (optional); NO_JOB_MINUTES, DEATH_MINUTES, POWEROFF_MINUTES; -// INSTANCE_TYPE, ZONE, ONLINE_SECONDS. +// (ci-launch); SELF_DELETE_KEY/_SECRET; SELF_LAYERS; SMTP_* and MAIL_* +// (optional); NO_JOB_MINUTES, DEATH_MINUTES, POWEROFF_MINUTES; INSTANCE_TYPE, +// ZONE, ONLINE_SECONDS; RUNNER_IMAGE, the environment image the runner runs in, +// by default the one of this plx-ci's version (a trial names an unreleased +// `…:sha-` from runner-image.yml). // // destroy-instances: the run's cleanup, delete what this run and attempt // created and the registrations nothing used; kept instances are left alone. @@ -28,9 +30,8 @@ import { createInstances, DEFAULTS, type InstanceLeg, type LaunchOptions } from import { destroyInstances } from '../core/destroyInstances.ts'; import { smtpFromEnv } from '../core/mail.ts'; import type { Leg } from '../core/plan.ts'; -import { storageFromEnv } from '../core/registry.ts'; import { sweepInstances } from '../core/sweepInstances.ts'; -import { contextOf } from '../program.ts'; +import { contextOf, version } from '../program.ts'; import { exoOf, githubOf, need, runIdentity, zoneOf } from './shared.ts'; /** The launch options the environment carries; label and app come from the plan's legs. */ @@ -47,7 +48,6 @@ export function launchOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): Omit poweroffMinutes: minutes('POWEROFF_MINUTES'), }, smtp: smtpFromEnv(env), - registry: storageFromEnv(env), zone: zoneOf(env), instanceType: env.INSTANCE_TYPE || DEFAULTS.instanceType, template: env.TEMPLATE || DEFAULTS.template, @@ -56,6 +56,7 @@ export function launchOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): Omit sshKey: DEFAULTS.sshKey, onlineSeconds: Number(env.ONLINE_SECONDS || DEFAULTS.onlineSeconds), tries: DEFAULTS.tries, + image: env.RUNNER_IMAGE || `${DEFAULTS.imageRepository}:${version}`, }; } diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index a1b01188..b79524b9 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -5,22 +5,9 @@ // holds what only that strategy needs. The display versions, opt-in per // repo, read no strategy and sit where a release uses them, after publish. import type { Command } from 'commander'; -import { register as build } from './build.ts'; import { register as displayVersions } from './displayVersions.ts'; import { register as hybrid } from './hybrid.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; -import { register as registry } from './registry.ts'; -import { register as report } from './report.ts'; -import { register as test } from './test.ts'; -export const commands: ((program: Command) => void)[] = [ - registry, - plan, - build, - test, - publish, - displayVersions, - report, - hybrid, -]; +export const commands: ((program: Command) => void)[] = [plan, publish, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index 9de15309..86f7384e 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -1,30 +1,35 @@ -// plx-ci plan [--test] [--deploy] [apps...]: the hashes and the look-ups -// (§ 8 PLX-Delivery), printed as the matrix the large jobs fan out over, each -// leg naming its runner from the strategy and what it owes there, the build, -// the test or both, and the apps with their hashes for the publish. With --deploy, the environment the run -// releases into and each app's target there, from a checkout of the platform -// repo's inventory. Launches nothing: under hybrid, `plx-ci hybrid -// create-instances` reads the matrix next. Writes matrix=, apps=, deploys= -// and environment= to GITHUB_OUTPUT when that is set. -// From the environment: CI_STRATEGY, CI_REGISTRY, CI_OVERLAY; GITHUB_RUN_ID -// and GITHUB_RUN_ATTEMPT (they name the instances under hybrid); for -// --deploy GITHUB_EVENT_NAME, GITHUB_REF_NAME, GITHUB_SHA and IMAGE_PREFIX. +// plx-ci plan [--deploy] [apps...]: the build hashes, the look-ups in the +// forge's registry and what the trusted cache holds (§ 8 PLX-Delivery), +// printed as one leg per app: whether it gets a large job, its e2e job, and +// the runner of that job from the strategy, its suite, and whether publish +// builds its image or tags the one there, and from what. The cache is asked +// through the repo's turbow, so in a job of the forge the plan's job starts +// the trusted cache first (core/plan.ts says how, and what it does when it +// cannot ask, in one line). With --deploy, the environment the run deploys +// into and each app's target there, from a checkout of the operations repo's +// inventory. Launches nothing: under hybrid, `plx-ci hybrid create-instances` +// reads the matrix next. Writes to GITHUB_OUTPUT, when that is set, matrix=, +// the legs with a large job, apps=, every leg, which publish fans out over, +// deploys= and environment=. Runs in the repo's mise environment, which gives +// it PLX_PLATFORM as it gives it to the build. From the environment: +// CI_STRATEGY; PLX_PLATFORM; PLX_TURBO_TRUSTED and its token, as turbow reads +// them; IMAGE_PREFIX or GITHUB_REPOSITORY, where the images live; +// GITHUB_RUN_ID and GITHUB_RUN_ATTEMPT (they name the instances under +// hybrid); for --deploy GITHUB_EVENT_NAME, GITHUB_REF_NAME and GITHUB_SHA. +// crane on the PATH, logged in to the forge's registry. // -// plx-ci --json plan --test -// plx-ci plan --test --deploy --inventory platform/inventory -// plx-ci plan --mode repro website +// plx-ci --json plan +// plx-ci plan --deploy --inventory operations/inventory import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; -import { environmentOf, type Mode, plan, readHashes, verbsOf } from '../core/plan.ts'; +import { appsOf, environmentOf, outputsOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, need, registryFor, settings, withStrategy } from './shared.ts'; +import { imagePrefix, need, settings, withStrategy } from './shared.ts'; interface Opts { strategy?: string; - mode: Mode; - test?: boolean; deploy?: boolean; environment?: string; inventory: string; @@ -34,41 +39,30 @@ interface Opts { export function register(program: Command): void { withStrategy(program.command('plan')) .description( - 'compute the build and test hashes, look them up in the registry, and print the builds, tests and deploys the run needs', + 'compute the build hashes, look the images up in the forge’s registry, and print the e2e jobs, publishes and deploys the run needs', ) .argument('[apps...]', 'the apps (default: every directory under apps/)') - .option( - '--mode ', - 'build (skip what the registry holds), force (build all), repro (two no-cache builds per app)', - 'build', - ) - .option('--test', 'plan the tests too, for the apps with a test task') .option('--deploy', 'plan the deploys too: the environment and each app’s target in it') - .option('--environment ', 'the environment to release into (default: from the branch, main or develop)') - .option('--inventory ', 'the platform repo’s inventory, for --deploy', 'platform/inventory') + .option('--environment ', 'the environment to deploy into (default: from the branch, main or develop)') + .option('--inventory ', 'the operations repo’s inventory, for --deploy', 'platform/inventory') .option('-C, --dir ', 'the checkout to read', '.') .action(async (apps: string[], opts: Opts, command: Command) => { const ctx = contextOf(command); const s = settings(opts); const dir = resolve(opts.dir); const env = process.env; - const all = - apps.length > 0 - ? apps - : (await ctx.readDir(`${dir}/apps`)) - .filter((e) => e.directory) - .map((e) => e.name) - .sort(); + const all = apps.length > 0 ? apps : await appsOf(ctx, dir); const environment = opts.deploy ? environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment) : ''; - const result = await plan(ctx, { + const { hashes, why } = await readHashes(ctx, dir, all); + if (why) + ctx.say(`the plan could not ask the trusted cache, so every task it would ask about counts as work: ${why}`); + const result = await plan(ctx, dir, { apps: all, - mode: opts.mode, - tests: opts.test ?? false, - hashes: await readHashes(ctx, dir, all), + hashes, strategy: s.strategy, - registry: registryFor(s), + prefix: imagePrefix(), // Only hybrid names anything after the run: its instances. run: s.strategy === 'hybrid' @@ -78,27 +72,25 @@ export function register(program: Command): void { ? { environment, targets: targetsIn(await readDeployTargets(ctx, resolve(opts.inventory)), environment), - prefix: imagePrefix(), sha: need('GITHUB_SHA'), } : undefined, }); ctx.result(result, (r) => [ - ...r.legs.map((l) => `${verbsOf(l)} ${l.app} ${l.hash}${l.test ? ` ${l.test}` : ''} ${l.runner}`), + ...r.legs.map( + (l) => + `${l.large ? `e2e ${l.runner}` : 'no e2e'} ${l.app} ${l.hash} ${l.suites.join(' ') || '(no suite)'}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, + ), ...r.deploys.map((l) => `deploy ${l.app} ${l.host} ${l.image}`), ].join('\n'), ); if (env.GITHUB_OUTPUT) appendFileSync( env.GITHUB_OUTPUT, - [ - `matrix=${JSON.stringify(result.legs)}`, - `apps=${JSON.stringify(result.apps)}`, - `deploys=${JSON.stringify(result.deploys)}`, - `environment=${result.environment}`, - '', - ].join('\n'), + `${Object.entries(outputsOf(result)) + .map(([name, value]) => `${name}=${value}`) + .join('\n')}\n`, ); }); } diff --git a/packages/cli-ci/src/commands/publish.ts b/packages/cli-ci/src/commands/publish.ts index b49571f2..2fa0c397 100644 --- a/packages/cli-ci/src/commands/publish.ts +++ b/packages/cli-ci/src/commands/publish.ts @@ -1,40 +1,68 @@ -// plx-ci publish [--test ]: put the tested -// image under its commit in the registry production pulls from: copied from -// the sidecar, or tagged where it is there already (§ 8 PLX-Delivery). Needs -// the registry reachable here (`plx-ci registry`) and crane on the PATH, -// logged in to the forge's registry. From the environment: CI_STRATEGY, -// CI_REGISTRY; IMAGE_PREFIX, where the images live (default ghcr.io/). Prints the image, and writes image= to +// plx-ci publish --context : put the app's +// image under its commit in the forge's registry, the one production pulls +// from (§ 4 PLX-Delivery): tagged where build- is there already, else +// built and pushed under both, from the build output restored by the repo's +// `mise run build ` (`output`) or, for a Dockerfile of the app's own, +// from a pruned context (`pruned`), as the plan's leg says. Runs in a +// checkout, in the repo's mise environment, with crane on the PATH and +// logged in to the forge's registry, and docker's client with buildx. From +// the environment: BUILDKIT_HOST, the BuildKit service to build through, +// which a slot of a runner host is handed, else the runner's Docker builds; +// IMAGE_PREFIX, where the images live (default ghcr.io/); NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, the app's key, +// needed where it builds; NPM_CONFIG_USERCONFIG, a user-level npmrc with the +// token of the tenant's private package registry, handed to a Dockerfile of +// the app's own as a secret. Prints the image, and writes image= to // GITHUB_OUTPUT when that is set. // -// plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" -// plx-ci publish my-app d135e9416e1cf4e8 "$GITHUB_SHA" --test 5b052598a4d84145 +// plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" --context output import { appendFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import type { Command } from 'commander'; +import { Option } from 'commander'; +import type { ImageContext } from '../core/plan.ts'; import { publish } from '../core/publish.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, registryFor, settings, withStrategy } from './shared.ts'; +import { imagePrefix } from './shared.ts'; export function register(program: Command): void { - withStrategy(program.command('publish')) - .description('publish one app’s tested image as in the forge’s registry, beside build- and test-') - .argument('', 'the app') - .argument('', 'Turbo’s hash of the app’s build task') + program + .command('publish') + .description( + 'publish one app’s image as in the forge’s registry: tag build- where it is there, else build it and push it', + ) + .argument('', 'the app, apps/ in the checkout') + .argument('', 'Turbo’s hash of the app’s build task') .argument('', 'the commit, the tag a deploy takes') - .option('--test ', 'Turbo’s hash of the app’s test task; the image is read from test-') + .addOption( + new Option('--context ', 'what the image is made from, as the plan’s leg says') + .choices(['output', 'pruned']) + .makeOptionMandatory(), + ) + .option('-C, --dir ', 'the checkout to read', '.') .action( - async (app: string, build: string, sha: string, opts: { strategy?: string; test?: string }, command: Command) => { + async ( + app: string, + hash: string, + sha: string, + opts: { context: ImageContext; dir: string }, + command: Command, + ) => { const ctx = contextOf(command); + const env = process.env; const result = await publish(ctx, { app, - build, - test: opts.test || undefined, + hash, sha, prefix: imagePrefix(), - registry: registryFor(settings(opts)), + dir: resolve(opts.dir), + context: opts.context, + encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', + npmrc: env.NPM_CONFIG_USERCONFIG || undefined, + buildkit: env.BUILDKIT_HOST || undefined, }); - ctx.result(result, (r) => `${r.image}:${sha}${r.copied ? '' : ' (was there)'}`); - if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `image=${result.image}:${sha}\n`); + ctx.result(result, (r) => `${r.image}:${sha}${r.built ? ` (built, ${r.digest ?? 'no digest'})` : ' (tagged)'}`); + if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, `image=${result.image}:${sha}\n`); }, ); } diff --git a/packages/cli-ci/src/commands/registry.ts b/packages/cli-ci/src/commands/registry.ts deleted file mode 100644 index 73746661..00000000 --- a/packages/cli-ci/src/commands/registry.ts +++ /dev/null @@ -1,91 +0,0 @@ -// plx-ci registry: make sure this machine reaches the registry the run's -// candidates live in (§ 8 PLX-Delivery). With a registry of the tenant's own -// (CI_REGISTRY=own), that is the pair on localhost: nothing where :5000 -// answers already (a slot of a runner host), else the two sidecars are -// started, creating this week's bucket when it is missing. With the forge's -// registry (CI_REGISTRY=ghcr) it is a check that the job has logged in. -// `exists` asks whether a tag is there; `rotate` is the retention, run daily. -// From the environment: CI_STRATEGY, CI_REGISTRY; for the pair -// REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY, REGISTRY_SECRET_KEY -// (the vault item bucket-registry: any S3-compatible store), GITHUB_REPOSITORY -// (the owner names the buckets); for `rotate` under ghcr, GITHUB_TOKEN (the workflow's own, -// with packages: write), which deletes versions of the packages its repo -// published: the repo's apps, or the ones named. -// -// plx-ci registry -// plx-ci registry exists website build-0f2a3f35123dfd73 # exit 0 when it is, 1 otherwise -// plx-ci registry rotate # the buckets, or the repo's apps in ghcr -// plx-ci -n registry rotate # what would go - -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { Packages, packageOf, prune } from '../core/ghcr.ts'; -import { findTag, loggedIn, rotateBuckets, startSidecars, storageFromEnv } from '../core/registry.ts'; -import { contextOf } from '../program.ts'; -import { imagePrefix, need, ownerOf, registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - const registry = withStrategy(program.command('registry')) - .description( - 'make the candidates’ registry reachable here: the pair on localhost (started unless :5000 answers), or a login check for the forge’s', - ) - .action(async (opts: { strategy?: string }, command: Command) => { - const ctx = contextOf(command); - const s = settings(opts); - if (s.registry === 'ghcr') { - const host = imagePrefix().split('/')[0] ?? 'ghcr.io'; - if (!(await loggedIn(ctx, host)) && !ctx.dryRun) - throw new Error(`no login for ${host} here; the job logs in before it asks for the registry`); - ctx.result(`registry: ${imagePrefix()}, logged in`); - return; - } - const result = await startSidecars(ctx, storageFromEnv(), ownerOf(need('GITHUB_REPOSITORY'))); - ctx.result( - result, - (r) => `:5000 ${r.current}\n:5001 ${r.previous}${r.previousAnswers ? '' : ' (not answering)'}`, - ); - }); - withStrategy(registry.command('exists')) - .description('exit 0 when the registry holds the tag') - .argument('') - .argument('') - .action(async (app: string, tag: string, opts: { strategy?: string }, command: Command) => { - const ctx = contextOf(command); - const ref = await findTag(ctx, registryFor(settings(opts)), app, tag); - if (ref === undefined) { - ctx.say(`${app}:${tag} is in no registry here`); - process.exitCode = 1; - } else ctx.result(ref); - }); - withStrategy(registry.command('rotate')) - .description( - 'the retention: this week’s bucket exists and the one from two weeks ago goes; in the forge’s registry, candidates older than thirty days go', - ) - .argument('[apps...]', 'under ghcr: the apps whose packages are pruned (default: every directory under apps/)') - .option('-C, --dir ', 'the checkout to read', '.') - .action(async (apps: string[], opts: { strategy?: string; dir: string }, command: Command) => { - const ctx = contextOf(command); - const s = settings(opts); - const owner = ownerOf(need('GITHUB_REPOSITORY')); - if (s.registry === 'ghcr') { - const all = - apps.length > 0 - ? apps - : (await ctx.readDir(`${resolve(opts.dir)}/apps`)) - .filter((e) => e.directory) - .map((e) => e.name) - .sort(); - const names = all.map((app) => packageOf(imagePrefix(), app)); - const result = await prune(ctx, new Packages(ctx, owner, need('GITHUB_TOKEN')), names); - ctx.result(result, (r) => r.map((v) => `${v.package} ${v.tags.join(' ')}`).join('\n')); - return; - } - const storage = storageFromEnv(); - if (!storage) - throw new Error('REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed'); - const result = await rotateBuckets(ctx, storage, owner); - ctx.result(result, (r) => - [...(r.created ? [`created ${r.created}`] : []), ...(r.removed ? [`removed ${r.removed}`] : [])].join('\n'), - ); - }); -} diff --git a/packages/cli-ci/src/commands/report.ts b/packages/cli-ci/src/commands/report.ts deleted file mode 100644 index 0104c33c..00000000 --- a/packages/cli-ci/src/commands/report.ts +++ /dev/null @@ -1,26 +0,0 @@ -// plx-ci report --mode : what the registry holds after a -// build run, every app's digest and, in repro mode, the two builds of each -// app compared layer by layer (§ 4 PLX-Delivery). Needs the registry -// reachable here (`plx-ci registry`). From the environment: CI_STRATEGY, -// CI_REGISTRY, GITHUB_RUN_ID. -// -// plx-ci report --mode repro "$MATRIX" -import type { Command } from 'commander'; -import { type Leg, type Mode, report } from '../core/plan.ts'; -import { contextOf } from '../program.ts'; -import { need, registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('report')) - .description('the digests the registry holds for a run’s matrix, and in repro mode the layer-by-layer comparison') - .argument('', 'the plan’s matrix, JSON') - .requiredOption('--mode ', 'build, force or repro') - .action(async (matrix: string, opts: { strategy?: string; mode: Mode }, command: Command) => { - const ctx = contextOf(command); - const legs = JSON.parse(matrix) as Leg[]; - const result = await report(ctx, registryFor(settings(opts)), legs, opts.mode, need('GITHUB_RUN_ID')); - // The report narrates every digest and difference as it reads them; the - // result repeats nothing unless asked for as JSON. - ctx.result(result, () => ''); - }); -} diff --git a/packages/cli-ci/src/commands/shared.ts b/packages/cli-ci/src/commands/shared.ts index 8f0dbf1d..e753fba6 100644 --- a/packages/cli-ci/src/commands/shared.ts +++ b/packages/cli-ci/src/commands/shared.ts @@ -8,7 +8,6 @@ import type { Command } from 'commander'; import type { RunIdentity } from '../core/destroyInstances.ts'; import { Exo } from '../core/exoscale.ts'; import { GitHubRunners } from '../core/github.ts'; -import { type Registry, registryOf } from '../core/registry.ts'; import { type Settings, settingsOf } from '../core/strategy.ts'; export function need(name: string, env: NodeJS.ProcessEnv = process.env): string { @@ -34,7 +33,7 @@ export function githubOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Gi return env.RUNNER_TOKEN ? new GitHubRunners(ctx, need('GITHUB_REPOSITORY', env), env.RUNNER_TOKEN) : undefined; } -/** The owner of the repo, the prefix of the bucket names. */ +/** The owner of the repo, the default prefix of the image names. */ export const ownerOf = (repo: string): string => repo.split('/')[0] ?? repo; /** The option every universal command takes; the environment answers without it. */ @@ -42,7 +41,7 @@ export function withStrategy(command: Command): Command { return command.option('--strategy ', 'github, on-prem or hybrid (default: CI_STRATEGY, else github)'); } -/** The repo's three answers: --strategy before CI_STRATEGY, then CI_REGISTRY and CI_OVERLAY. */ +/** The repo's two answers: --strategy before CI_STRATEGY, then CI_OVERLAY. */ export function settings(opts: { strategy?: string }, env: NodeJS.ProcessEnv = process.env): Settings { return settingsOf(env, opts.strategy); } @@ -51,8 +50,3 @@ export function settings(opts: { strategy?: string }, env: NodeJS.ProcessEnv = p export function imagePrefix(env: NodeJS.ProcessEnv = process.env): string { return env.IMAGE_PREFIX || `ghcr.io/${ownerOf(need('GITHUB_REPOSITORY', env))}`; } - -/** Where the candidates live, from the settings. */ -export function registryFor(s: Settings, env: NodeJS.ProcessEnv = process.env): Registry { - return registryOf(s.registry, s.registry === 'ghcr' ? imagePrefix(env) : ''); -} diff --git a/packages/cli-ci/src/commands/test.ts b/packages/cli-ci/src/commands/test.ts deleted file mode 100644 index 227ba5d7..00000000 --- a/packages/cli-ci/src/commands/test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// plx-ci test : the app's compose stack with the -// candidate image from the registry, migrate, up, the app's test script against -// it, and on success the tag test- (§ 8 PLX-Delivery). Runs on a large -// runner in a checkout with the app's dependencies installed. From the -// environment: CI_STRATEGY, CI_REGISTRY; PLEXUS_LOOPBACK_PORT (default 3000), the port the stack -// publishes the app on. Prints the tested digest, and writes it to -// GITHUB_OUTPUT when that is set. -// -// plx-ci test my-app d135e9416e1cf4e8 5b052598a4d84145 -import { appendFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { test } from '../core/test.ts'; -import { contextOf } from '../program.ts'; -import { registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('test')) - .description('run one app’s tests against its compose stack on the candidate image, and tag the image tested') - .argument('', 'the app, apps/ in the checkout') - .argument('', 'Turbo’s hash of the app’s build task, the candidate’s tag') - .argument('', 'Turbo’s hash of the app’s test task, the tag on success') - .option('-C, --dir ', 'the checkout to read', '.') - .action( - async (app: string, build: string, hash: string, opts: { strategy?: string; dir: string }, command: Command) => { - const ctx = contextOf(command); - const result = await test(ctx, { - app, - build, - hash, - dir: resolve(opts.dir), - registry: registryFor(settings(opts)), - port: process.env.PLEXUS_LOOPBACK_PORT ? Number(process.env.PLEXUS_LOOPBACK_PORT) : undefined, - }); - ctx.result(result, (r) => r.digest ?? ''); - if (process.env.GITHUB_OUTPUT && result.digest) - appendFileSync(process.env.GITHUB_OUTPUT, `digest=${result.digest}\n`); - }, - ); -} diff --git a/packages/cli-ci/src/core/build.test.ts b/packages/cli-ci/src/core/build.test.ts deleted file mode 100644 index 1ab10679..00000000 --- a/packages/cli-ci/src/core/build.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { buildArgs, buildStep, tagsOf } from './build.ts'; - -const options = { app: 'website', hash: '0f2a', sha: 'abc', encryptionKey: 'k', registry: { kind: 'own' } as const }; - -test('the build names both sidecars as cache sources when the previous one answers, and only the current one otherwise', () => { - const both = buildArgs(options, '/ctx/full', '/ctx/meta.json', true).join(' '); - assert.match(both, /--cache-from type=registry,ref=localhost:5000\/website:cache/); - assert.match(both, /--cache-from type=registry,ref=localhost:5001\/website:cache/); - assert.match(both, /--cache-to type=registry,ref=localhost:5000\/website:cache,mode=max/); - assert.match(both, /--tag localhost:5000\/website:build-0f2a --tag localhost:5000\/website:abc/); - assert.match(both, /--file \/ctx\/full\/apps\/website\/docker\/Dockerfile/); - assert.match(both, /--provenance=false --sbom=false/); - const one = buildArgs(options, '/ctx/full', '/ctx/meta.json', false).join(' '); - assert.doesNotMatch(one, /5001/); -}); - -test('a no-cache build has no cache arguments and carries the extra tags', () => { - const args = buildArgs({ ...options, noCache: true, tags: ['repro-41-1'] }, '/c', '/m', true).join(' '); - assert.match(args, /--no-cache/); - assert.doesNotMatch(args, /cache-from|cache-to/); - assert.match(args, /--tag localhost:5000\/website:repro-41-1/); -}); - -test('in the forge’s registry a build pushes no commit tag and names no previous week', () => { - const ghcr = { ...options, registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' } as const }; - assert.deepEqual(tagsOf(ghcr), ['build-0f2a']); - assert.deepEqual(tagsOf(options), ['build-0f2a', 'abc']); - const args = buildArgs(ghcr, '/c', '/m', false).join(' '); - assert.match(args, /--tag ghcr.io\/plexus-ms-tenant\/website:build-0f2a/); - assert.doesNotMatch(args, /website:abc/); - assert.match(args, /--cache-to type=registry,ref=ghcr.io\/plexus-ms-tenant\/website:cache,mode=max/); - assert.doesNotMatch(args, /localhost/); -}); - -test('the private registry’s npmrc is a secret of the build only where the job has one', () => { - assert.doesNotMatch(buildArgs(options, '/c', '/m', false).join(' '), /id=npmrc/); - const args = buildArgs({ ...options, npmrc: '/tmp/npmrc' }, '/c', '/m', false).join(' '); - assert.match(args, /--secret id=npmrc,src=\/tmp\/npmrc/); -}); - -test('the build passes the output of BuildKit through to the log at every verbosity', () => { - const step = buildStep(buildArgs(options, '/c', '/m', false), { BUILDX_BUILDER: 'ci' }); - assert.equal(step.kind, 'run'); - assert.equal(step.kind === 'run' && step.interactive, true); - assert.match(buildArgs(options, '/c', '/m', false).join(' '), /--progress plain/); -}); diff --git a/packages/cli-ci/src/core/build.ts b/packages/cli-ci/src/core/build.ts index 5182d2d5..85f993f3 100644 --- a/packages/cli-ci/src/core/build.ts +++ b/packages/cli-ci/src/core/build.ts @@ -1,110 +1,122 @@ -// Build one app's image from its pruned context, with the registry as -// BuildKit cache and candidate store (§§ 4 and 8 PLX-Delivery). Runs on a -// large runner, whichever the strategy gives it, in a checkout of the repo -// with node and docker on the PATH, and by hand the same way. BuildKit runs -// as a docker-container builder on the machine's network (the docker driver -// cannot export a registry cache, and localhost:5000 is the sidecar there); a -// launched instance has bootstrapped it by the time the job starts, anywhere -// else the build creates it. +// Build one app's image and push it (§ 4 PLX-Delivery), for publish, which +// builds only an image the forge's registry lacks. An app's image is made in +// one of two ways, by what its Dockerfile is, the context the plan gives it +// (plan.ts's imageContextOf): // -// The pruned context is `turbo prune --docker` into a -// temporary directory: `json/` with the package manifests alone, `full/` with -// the app and the workspace packages it uses, whole, and the lockfile reduced -// to them beside the two. The build context is `full/`, with the lockfile and -// the repo's root .dockerignore copied in and an empty packages/ made where -// the app uses none; the Dockerfile is apps//docker/Dockerfile in it. -// `json/` goes unused. The directory is removed after the build. +// output an app from app-nextjs: its Dockerfile only copies the one +// directory its build leaves (apps//.next/standalone), and +// that directory is the build context. It is restored by the +// repo's own verb, `mise run build `, which a job runs +// against the trusted cache, where the app's e2e job left it; the +// directory is removed first, so that the image holds the restore +// and nothing a server or an earlier build wrote there. A miss +// builds the app, with the app's key, as the e2e job did. The +// output must hold apps//.next/BUILD_ID, the build's hash +// (generateBuildId in the template's next.config.ts), equal to +// the hash the image is tagged with: an output of another hash, or +// none where the Dockerfile's WORKDIR looks, is refused. +// pruned an app with a Dockerfile of its own builds itself in it, from +// `turbo prune --docker` (the Turbo the lockfile +// has) into a temporary directory: `json/` with the package +// manifests alone, `full/` with the app and the workspace packages +// it uses, whole, and the lockfile reduced to them beside the two. +// The build context is `full/`, with the lockfile and the repo's +// root .dockerignore copied in and an empty packages/ made where +// the app uses none; the Dockerfile is apps//docker/Dockerfile +// in it, given BUILD_HASH, the app's key as a BuildKit secret and, +// where the job has one, the npmrc of the tenant's private +// packages. `json/` goes unused. The directory is removed after. +// +// Either way the image is built for linux/amd64 and pushed under build- +// and the commit, with no layer cache, SOURCE_DATE_EPOCH fixing the times +// BuildKit sets, and no provenance or SBOM, so that the manifest is the image +// and nothing else. No rewrite-timestamp: the runner's Docker of the forge +// refuses it beside the unpack of its image store, and an image is built once +// per hash, so no two builds of it are compared. BuildKit's log is the +// job's, at every verbosity. Where the build runs is told apart at this step +// by BUILDKIT_HOST alone, which knows no strategy: a slot of a runner host, +// under on-prem and hybrid, is handed the address of the host's BuildKit +// service there (actions_runners, from the port the service listens on), and +// the build goes through a buildx builder of the remote driver to it, +// plexus-buildkit, made where the machine has none of the name yet; without +// it, as on the forge's runners under github, the runner's own Docker builds +// (the default builder). The push uses the login of the job's +// ~/.docker/config.json, which BuildKit is handed through the build's session. import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { Context, Step } from '@plexus-ms/lib'; import { run, UsageError } from '@plexus-ms/lib'; -import { packageName, turboOf } from './plan.ts'; -import { answers, candidateRef, PREVIOUS_PORT, type Registry } from './registry.ts'; +import { type ImageContext, packageName, turboOf } from './plan.ts'; + +/** The buildx builder of the remote driver that reaches it. */ +export const BUILDER = 'plexus-buildkit'; export interface BuildOptions { app: string; - /** Turbo's hash of the app's build task; the image's primary tag and Next's build ID. */ + /** Turbo's hash of the app's build task; the image's tag build- and its build ID. */ hash: string; + /** The commit, the image's second tag. */ sha: string; - /** Further tags on the same image. */ - tags?: string[]; - /** The app's fixed key, a BuildKit secret; the Dockerfile reads it as next-server-actions-encryption-key. */ + /** The image, `/`, without a tag. */ + image: string; + /** What the image is made from. */ + context: ImageContext; + /** The checkout. */ + dir: string; + /** The app's server-actions key: for a build of the output that misses the cache, or a secret of a Dockerfile of its own. */ encryptionKey: string; - /** - * A user-level npmrc holding the token of the tenant's private package registry, a BuildKit - * secret; the Dockerfile mounts it as npmrc for its installs. Absent where the repo installs none. - */ + /** A user-level npmrc with the token of the tenant's private package registry, a secret of a Dockerfile of its own. */ npmrc?: string; - /** Build from scratch, the reproducibility measurement. */ - noCache?: boolean; - /** The checkout; default the cwd. */ - dir?: string; - /** Where the candidates live. */ - registry: Registry; - builder?: string; + /** The BuildKit service to build through, `tcp://
:` (BUILDKIT_HOST); without it the runner's Docker. */ + buildkit?: string; } -export interface Build { - app: string; +export interface Built { tags: string[]; digest?: string; - /** Seconds the prune and the build took. */ - pruneSeconds: number; - buildSeconds: number; } -export const PREVIOUS_REGISTRY = `localhost:${PREVIOUS_PORT}`; - -/** - * The tags a build pushes: build- and the extra ones, and the commit - * where the candidates have a registry of their own. In the forge's registry - * the commit's tag marks a published image, which only `publish` may set. - */ -export function tagsOf(options: BuildOptions): string[] { - return [`build-${options.hash}`, ...(options.registry.kind === 'own' ? [options.sha] : []), ...(options.tags ?? [])]; -} +/** The output directory of an app from app-nextjs: the build context of its image. */ +export const outputOf = (dir: string, app: string): string => join(dir, 'apps', app, '.next', 'standalone'); -/** The `docker buildx build` arguments, so that the tests pin them. */ +/** The `docker buildx build` arguments for a context and a Dockerfile, so that the tests pin them. */ export function buildArgs( options: BuildOptions, context: string, + dockerfile: string, metadataFile: string, - previousAnswers: boolean, + builder?: string, ): string[] { - const { app } = options; - const ref = (tag: string) => candidateRef(options.registry, app, tag); - const tags = tagsOf(options).flatMap((t) => ['--tag', ref(t)]); - const cache = options.noCache - ? ['--no-cache'] - : [ - '--cache-from', - `type=registry,ref=${ref('cache')}`, - ...(previousAnswers ? ['--cache-from', `type=registry,ref=${PREVIOUS_REGISTRY}/${app}:cache`] : []), - '--cache-to', - `type=registry,ref=${ref('cache')},mode=max`, - ]; + const { app, image } = options; + const own = + options.context === 'pruned' + ? [ + '--build-arg', + `BUILD_HASH=${options.hash}`, + '--secret', + 'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY', + ...(options.npmrc ? ['--secret', `id=npmrc,src=${options.npmrc}`] : []), + ] + : []; return [ 'buildx', 'build', context, '--file', - `${context}/apps/${app}/docker/Dockerfile`, + dockerfile, '--platform', 'linux/amd64', + ...(builder ? ['--builder', builder] : []), '--build-arg', `APP=${app}`, - '--build-arg', - `BUILD_HASH=${options.hash}`, - '--secret', - 'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY', - ...(options.npmrc ? ['--secret', `id=npmrc,src=${options.npmrc}`] : []), - ...cache, - ...tags, - // SOURCE_DATE_EPOCH and rewrite-timestamp flatten every timestamp the image - // carries; provenance and SBOM off, so the manifest is the image and nothing else. + ...own, + '--tag', + `${image}:build-${options.hash}`, + '--tag', + `${image}:${options.sha}`, '--output', - 'type=image,push=true,rewrite-timestamp=true,oci-mediatypes=true', + 'type=image,push=true,oci-mediatypes=true', '--provenance=false', '--sbom=false', '--metadata-file', @@ -114,85 +126,105 @@ export function buildArgs( ]; } -/** - * The build as a step. BuildKit's output is the job's log, inherited and not - * captured: which layers came from the cache and what each step cost is read - * there, at every verbosity. - */ +/** The build as a step: BuildKit's output is the job's log, inherited and not captured. */ export function buildStep(args: string[], env: NodeJS.ProcessEnv): Step { return run('docker', args, { env, interactive: true }); } -/** The builder, created where the machine has none of the name yet. */ -async function ensureBuilder(ctx: Context, name: string): Promise { +/** The builder: the remote one of the BuildKit service where one is given, made where missing; none, the runner's Docker, otherwise. */ +async function builderFor(ctx: Context, options: BuildOptions): Promise { + if (!options.buildkit) return undefined; if (!ctx.dryRun) { try { - await ctx.read('docker', ['buildx', 'inspect', name]); - return; + await ctx.read('docker', ['buildx', 'inspect', BUILDER]); + return BUILDER; } catch {} } + await ctx.apply([run('docker', ['buildx', 'create', '--name', BUILDER, '--driver', 'remote', options.buildkit])]); + return BUILDER; +} + +/** The output restored by the repo's verb into a clean directory, refused unless it is the build of `hash`. */ +async function restoreOutput(ctx: Context, options: BuildOptions): Promise { + const { app, dir, hash } = options; + const output = outputOf(dir, app); await ctx.apply([ - run('docker', [ - 'buildx', - 'create', - '--name', - name, - '--driver', - 'docker-container', - '--driver-opt', - 'network=host', - '--bootstrap', - ]), + run('rm', ['-rf', output]), + run('mise', ['run', 'build', app], { + cwd: dir, + env: { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey }, + }), ]); + if (!ctx.dryRun) { + const where = `apps/${app}/.next/standalone`; + let id: string; + try { + id = (await ctx.readFile(join(output, 'apps', app, '.next', 'BUILD_ID'))).trim(); + } catch { + throw new Error( + `${where} holds no apps/${app}/.next/BUILD_ID: the build left no app at the place the Dockerfile starts it`, + ); + } + if (id !== hash) + throw new Error( + `${where} holds the build ${id}, not ${hash}: the plan and the build saw different inputs (another Turbo, or another PLX_PLATFORM)`, + ); + } + return output; } -export async function build(ctx: Context, options: BuildOptions): Promise { - if (!options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); - const dir = options.dir ?? '.'; - const out = join(tmpdir(), `plx-ci-build-${randomBytes(4).toString('hex')}`); +/** A pruned context of the app, in a new temporary directory; its build context is `/full`. */ +async function prunedContext(ctx: Context, options: BuildOptions, out: string): Promise { + const { dir } = options; const context = join(out, 'full'); - const builder = options.builder ?? 'ci'; - const env = { - NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey, - BUILDX_BUILDER: builder, - SOURCE_DATE_EPOCH: '0', - }; - const name = await packageName(ctx, dir, options.app); - await ensureBuilder(ctx, builder); - - // The pruned context: the app, the workspace packages it uses, a lockfile - // reduced to them. turbo writes the lockfile beside `full`, and leaves out - // the root .dockerignore and an empty packages/ when the app uses none; the + // turbo writes the lockfile beside `full`, and leaves out the root + // .dockerignore and an empty packages/ when the app uses none; the // Dockerfile wants all three. - let t = Date.now(); await ctx.apply([ - run('npx', ['--yes', await turboOf(ctx, dir), 'prune', name, '--docker', '--out-dir', out], { - cwd: dir, - }), + run( + 'npx', + [ + '--yes', + await turboOf(ctx, dir), + 'prune', + await packageName(ctx, dir, options.app), + '--docker', + '--out-dir', + out, + ], + { cwd: dir }, + ), run('cp', [join(out, 'pnpm-lock.yaml'), join(context, 'pnpm-lock.yaml')]), run('cp', [join(dir, '.dockerignore'), join(context, '.dockerignore')]), run('mkdir', ['-p', join(context, 'packages')]), ]); - const pruneSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`build: prune ${pruneSeconds}s`); + return context; +} - // The previous week's sidecar exists only when its bucket does, and only - // with a registry of the tenant's own. - const previousAnswers = options.registry.kind === 'own' && (ctx.dryRun ? true : await answers(ctx, PREVIOUS_PORT)); - if (options.registry.kind === 'own' && !previousAnswers) - ctx.say(`build: no previous-week registry on ${PREVIOUS_REGISTRY}`); +/** Build the app's image from its context and push it under build- and the commit. */ +export async function build(ctx: Context, options: BuildOptions): Promise { + if (!options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); + const { app } = options; + const builder = await builderFor(ctx, options); + const out = join(tmpdir(), `plx-ci-build-${randomBytes(4).toString('hex')}`); + const pruned = options.context === 'pruned'; + const context = pruned ? await prunedContext(ctx, options, out) : await restoreOutput(ctx, options); + if (!pruned) await ctx.apply([run('mkdir', ['-p', out])]); + const dockerfile = join(pruned ? context : options.dir, 'apps', app, 'docker', 'Dockerfile'); const metadataFile = join(out, 'metadata.json'); - t = Date.now(); - await ctx.apply([buildStep(buildArgs(options, context, metadataFile, previousAnswers), env)]); - const buildSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`build: build${options.noCache ? ' no-cache' : ''} ${buildSeconds}s`); - - const tags = tagsOf(options); - const result: Build = { app: options.app, tags, pruneSeconds, buildSeconds }; + const env = { + SOURCE_DATE_EPOCH: '0', + ...(pruned ? { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey } : {}), + }; + const t = Date.now(); + await ctx.apply([buildStep(buildArgs(options, context, dockerfile, metadataFile, builder), env)]); + ctx.say(`build: ${app} ${Math.round((Date.now() - t) / 1000)}s`); + const tags = [`build-${options.hash}`, options.sha]; + const result: Built = { tags }; if (!ctx.dryRun) { const meta = JSON.parse(await ctx.readFile(metadataFile)) as { 'containerimage.digest'?: string }; result.digest = meta['containerimage.digest']; - ctx.say(`build: ${options.app} ${tags.join(' ')} -> ${result.digest ?? ''}`); + ctx.say(`build: ${options.image} ${tags.join(' ')} -> ${result.digest ?? ''}`); } await ctx.apply([run('rm', ['-rf', out])]); return result; diff --git a/packages/cli-ci/src/core/createInstances.test.ts b/packages/cli-ci/src/core/createInstances.test.ts index 309e9de4..b58ea40c 100644 --- a/packages/cli-ci/src/core/createInstances.test.ts +++ b/packages/cli-ci/src/core/createInstances.test.ts @@ -33,17 +33,18 @@ const options: LaunchOptions = { sshKey: 'runners', onlineSeconds: 5, tries: 2, + image: 'ghcr.io/plexus-ms/ci-runner:sha-abc', now: () => now, sleep: async () => {}, }; -test('the user-data is rendered with the run’s facts and the week’s buckets, and fits the API', () => { - const text = renderUserData(options, 'JIT', now); +test('the user-data is rendered with the run’s facts, and fits the API', () => { + const text = renderUserData(options, 'JIT'); assert.match(text, /^hostname: exo-large-41-website-1$/m); - assert.match(text, /REGISTRY_BUCKET=acme-ci-registry-2026-w45/); - assert.match(text, /REGISTRY_PREVIOUS_BUCKET=acme-ci-registry-2026-w44/); + assert.doesNotMatch(text, /REGISTRY/); assert.match(text, /SELF_LAYERS=off/); - assert.match(text, /content: "JIT"/); + assert.match(text, /ACTIONS_RUNNER_INPUT_JITCONFIG=JIT$/m); + assert.match(text, /docker pull -q ghcr\.io\/plexus-ms\/ci-runner:sha-abc$/m); assert.ok(encodeUserData(text).length < DEFAULTS.userDataLimit); }); diff --git a/packages/cli-ci/src/core/createInstances.ts b/packages/cli-ci/src/core/createInstances.ts index dee20bb4..49e5ecfe 100644 --- a/packages/cli-ci/src/core/createInstances.ts +++ b/packages/cli-ci/src/core/createInstances.ts @@ -1,6 +1,6 @@ // Create the throwaway instances a run's large jobs need (§ 8 PLX-Delivery, // the hybrid strategy), one per leg of the plan, at once: the one machine an -// app's build, its test or both run on. +// app's e2e job, its build and its suites, runs on. // For each: a JIT config from GitHub, the raw create-instance call with the // labels the cleanup and the sweep read, user-data that arms the teardown // layers first, then a wait for the runner to show online, since a boot that @@ -10,7 +10,7 @@ // three minutes (waitOperation, exoscale.ts). A create still pending then // fails its launch, which removes its runner registration; once every launch // has settled the command fails, and with it the plan job, after which the -// workflow's `cleanup` job (_verify.yml) deletes what the run launched, found +// workflow's `cleanup` job (_e2e.yml) deletes what the run launched, found // by its labels. A created instance's runner then has `onlineSeconds` to // show online, 120 by default or ONLINE_SECONDS, looked at every five seconds. // @@ -40,8 +40,7 @@ import { KEPT_LABEL, type RunIdentity, repoLabel } from './destroyInstances.ts'; import { type CreateInstance, type Exo, sleep } from './exoscale.ts'; import type { GitHubRunners } from './github.ts'; import { type Smtp, sendMail } from './mail.ts'; -import type { ObjectStorage } from './registry.ts'; -import { deadline, iso, registryBuckets } from './time.ts'; +import { deadline, iso } from './time.ts'; import { RUNNER_USER_DATA, render } from './userData.ts'; /** What a runner's user-data is told. */ @@ -61,7 +60,6 @@ export interface LaunchOptions { selfLayers: 'on' | 'off'; deadlines: Deadlines; smtp?: Smtp; - registry?: ObjectStorage; zone: string; instanceType: string; template: string; @@ -72,6 +70,8 @@ export interface LaunchOptions { onlineSeconds: number; /** Instances tried before the launch gives up: the first and one replacement. */ tries: number; + /** The environment image the runner runs in, as a slot's does: `:`. */ + image: string; /** The wait between two looks at the runner; the tests pass none. */ sleep?: (ms: number) => Promise; now?: () => Date; @@ -86,8 +86,8 @@ export const DEFAULTS = { sshKey: 'runners', onlineSeconds: 120, tries: 2, - runnerVersion: '2.338.2', - runnerSha256: 'baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40', + /** The environment image, built by runner-image.yml and tagged with the Plexus version. */ + imageRepository: 'ghcr.io/plexus-ms/ci-runner', /** What the API accepts, base64 characters. */ userDataLimit: 32768, } as const; @@ -105,9 +105,7 @@ export interface Launch { } /** The runner's user-data for one launch, rendered: the values written as they are. */ -export function renderUserData(options: LaunchOptions, jitconfig: string, now: Date): string { - const owner = options.run.repo.split('/')[0] ?? options.run.repo; - const buckets = registryBuckets(owner, now); +export function renderUserData(options: LaunchOptions, jitconfig: string): string { return render(RUNNER_USER_DATA, { POWEROFF_MINUTES: String(options.deadlines.poweroffMinutes), NO_JOB_MINUTES: String(options.deadlines.noJobMinutes), @@ -117,8 +115,7 @@ export function renderUserData(options: LaunchOptions, jitconfig: string, now: D APP: options.app ?? '', REPO: options.run.repo, RUN: options.run.runId, - RUNNER_VERSION: DEFAULTS.runnerVersion, - RUNNER_SHA256: DEFAULTS.runnerSha256, + IMAGE: options.image, JITCONFIG: jitconfig, SELF_DELETE_KEY: options.selfDelete.key, SELF_DELETE_SECRET: options.selfDelete.secret, @@ -129,12 +126,6 @@ export function renderUserData(options: LaunchOptions, jitconfig: string, now: D SMTP_PASSWORD: options.smtp?.password ?? '', MAIL_FROM: options.smtp?.from ?? '', MAIL_TO: options.smtp?.to ?? '', - REGISTRY_ENDPOINT: options.registry?.endpoint ?? '', - REGISTRY_REGION: options.registry?.region ?? '', - REGISTRY_BUCKET: buckets.current, - REGISTRY_PREVIOUS_BUCKET: buckets.previous, - REGISTRY_ACCESS_KEY: options.registry?.accessKey ?? '', - REGISTRY_SECRET_KEY: options.registry?.secretKey ?? '', }); } @@ -215,7 +206,7 @@ export async function launch(ctx: Context, exo: Exo, github: GitHubRunners, opti securityGroupId, sshKey: options.sshKey, diskSize: options.diskSize, - userDataBase64: encodeUserData(renderUserData(options, registration?.encodedJitConfig ?? '', t0)), + userDataBase64: encodeUserData(renderUserData(options, registration?.encodedJitConfig ?? '')), labels, }; const operation = await exo.createInstance(request); diff --git a/packages/cli-ci/src/core/displayVersions.test.ts b/packages/cli-ci/src/core/displayVersions.test.ts index 7e7fc2c5..5af66365 100644 --- a/packages/cli-ci/src/core/displayVersions.test.ts +++ b/packages/cli-ci/src/core/displayVersions.test.ts @@ -58,7 +58,7 @@ function repo(options: { const ref = args[1] ?? ''; crane.push(ref); const key = ref.replace('ghcr.io/acme/', ''); - return options.digests[key] ?? notThere('crane'); + return options.digests[key] ?? notThere(); }, curl: (_cwd, _args, input) => { options.curl?.push([input ?? '']); @@ -250,7 +250,7 @@ test('tagging posts a release at the commit, and a re-run finds its tag; a tag e await assert.rejects(tagDisplayVersion(new Context({}, dry.io), { ...opts, version: 'v1.3' }), UsageError); }); -test('the apps are read from the deploys the verify planned', () => { +test('the apps are read from the deploys the plan made', () => { assert.deepEqual(appsOfDeploys('[{"app":"web","host":"h","image":"i"},{"app":"api","host":"h","image":"i"}]'), [ 'web', 'api', diff --git a/packages/cli-ci/src/core/ghcr.test.ts b/packages/cli-ci/src/core/ghcr.test.ts deleted file mode 100644 index f3273f43..00000000 --- a/packages/cli-ci/src/core/ghcr.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { Context, ExecError } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { Packages, packageOf, prunable, prune, type Version } from './ghcr.ts'; - -const now = new Date('2026-11-06T12:00:00Z'); -const old = '2026-09-30T12:00:00Z'; -const recent = '2026-10-20T12:00:00Z'; -const v = (id: number, createdAt: string, tags: string[]): Version => ({ id, createdAt, tags }); - -test('only a version older than thirty days whose every tag is a candidate’s goes', () => { - const versions = [ - v(1, old, ['build-0f2a']), - v(2, old, ['build-0f2a', 'test-5b05']), - v(3, old, ['build-0f2a', 'test-5b05', '8e51d0821a4c0d1f6b0a9d6e2f0c7d3b5a1e4f90']), - v(4, recent, ['build-c51b']), - v(5, old, []), - v(6, old, ['cache']), - v(7, old, ['build-0f2a', 'latest']), - v(8, old, ['build-notahash']), - ]; - assert.deepEqual( - prunable(versions, now).map((x) => x.id), - [1, 2], - ); -}); - -test('an app’s package is named by what follows the owner in the prefix, and the app', () => { - assert.equal(packageOf('ghcr.io/Acme', 'website'), 'website'); - assert.equal(packageOf('ghcr.io/acme/web/', 'app'), 'web/app'); -}); - -test('prune takes the named packages only, skips one that does not exist, and deletes by the rule; a dry run deletes nothing', async () => { - const calls: string[] = []; - const io = fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const method = input.match(/request = "(\w+)"/)?.[1]; - const url = input.match(/url = "([^"]+)"/)?.[1] ?? ''; - calls.push(`${method} ${url.replace('https://api.github.com/orgs/acme/packages', '')}`); - assert.match(input, /Authorization: Bearer ghp_x/); - if (method === 'DELETE') return ''; - if (url.includes('/container/website/')) - return JSON.stringify([ - { id: 1, created_at: old, metadata: { container: { tags: ['build-0f2a'] } } }, - { id: 2, created_at: old, metadata: { container: { tags: ['build-aaaa', 'abc123'] } } }, - ]); - if (url.includes('/container/web%2Fapp/')) - return JSON.stringify([{ id: 3, created_at: recent, metadata: { container: { tags: ['test-5b05'] } } }]); - return notThere('curl'); - }, - }); - const ctx = new Context({}, io); - const names = ['website', 'never-built', 'web/app']; - const pruned = await prune(ctx, new Packages(ctx, 'acme', 'ghp_x'), names, now); - assert.deepEqual(pruned, [{ package: 'website', id: 1, tags: ['build-0f2a'] }]); - assert.deepEqual(calls, [ - 'GET /container/website/versions?per_page=100&page=1', - 'DELETE /container/website/versions/1', - 'GET /container/never-built/versions?per_page=100&page=1', - 'GET /container/web%2Fapp/versions?per_page=100&page=1', - ]); - - calls.length = 0; - const dry = new Context({ dryRun: true }, io); - assert.equal((await prune(dry, new Packages(dry, 'acme', 'ghp_x'), names, now)).length, 1); - assert.ok(!calls.some((c) => c.startsWith('DELETE'))); -}); - -test('a package API that refuses the token is an error, not a package that does not exist', async () => { - const io = fakeIo({}, undefined, { - curl: () => { - throw new ExecError('curl', 22, 'curl: (22) The requested URL returned error: 401\n'); - }, - }); - const ctx = new Context({}, io); - await assert.rejects(prune(ctx, new Packages(ctx, 'acme', 'ghp_x'), ['website'], now), /401/); -}); diff --git a/packages/cli-ci/src/core/ghcr.ts b/packages/cli-ci/src/core/ghcr.ts deleted file mode 100644 index 44d0feab..00000000 --- a/packages/cli-ci/src/core/ghcr.ts +++ /dev/null @@ -1,122 +0,0 @@ -// The candidates a repo's runs leave in the forge's registry (`ci_registry: -// ghcr`), pruned (§ 8 PLX-Delivery), for the packages of the repo's own apps -// and no other: a version of a container package whose every tag -// is `build-` or `test-` and that is older than thirty days goes. -// A version that carries any other tag stays, whatever its age: a commit's -// SHA marks a published image, which a rollback may ask for years later, and -// `cache` is the one moving tag BuildKit rewrites. An untagged version stays -// as well, since it may be part of an image this rule knows nothing about. -// Through GitHub's packages API with curl; the token goes to curl as a config -// on stdin, never on argv. That API takes no App token: the workflow's own -// token deletes versions of the packages its repo published, which is why -// the pruning is mounted in the app repo. -import type { Context } from '@plexus-ms/lib'; -import { orAbsent, run } from '@plexus-ms/lib'; -import { curlNotFound } from './registry.ts'; - -export interface Version { - id: number; - /** `2026-11-04T10:40:27Z`. */ - createdAt: string; - tags: string[]; -} - -export const PRUNE_AFTER_DAYS = 30; -const CANDIDATE_TAG = /^(build|test)-[0-9a-f]+$/; - -/** The versions that go: tagged, with candidate tags only, created more than `days` ago. */ -export function prunable(versions: Version[], now: Date, days = PRUNE_AFTER_DAYS): Version[] { - const before = now.getTime() - days * 86_400_000; - return versions.filter( - (v) => v.tags.length > 0 && v.tags.every((t) => CANDIDATE_TAG.test(t)) && Date.parse(v.createdAt) < before, - ); -} - -export class Packages { - readonly ctx: Context; - readonly org: string; - private readonly token: string; - - constructor(ctx: Context, org: string, token: string) { - this.ctx = ctx; - this.org = org; - this.token = token; - } - - private config(method: string, path: string): string { - return `${[ - `url = "https://api.github.com/orgs/${this.org}/packages${path}"`, - `request = "${method}"`, - 'fail-with-body', - 'silent', - 'show-error', - `header = "Authorization: Bearer ${this.token}"`, - 'header = "Accept: application/vnd.github+json"', - 'header = "X-GitHub-Api-Version: 2022-11-28"', - ].join('\n')}\n`; - } - - /** Every page of a list, a hundred entries each. */ - private async pages(path: string): Promise { - const all: T[] = []; - for (let page = 1; ; page++) { - const sep = path.includes('?') ? '&' : '?'; - const out = await this.ctx.read('curl', ['-K', '-'], { - input: this.config('GET', `${path}${sep}per_page=100&page=${page}`), - }); - const items = JSON.parse(out) as T[]; - all.push(...items); - if (items.length < 100) return all; - } - } - - async versions(name: string): Promise { - const raw = await this.pages<{ - id: number; - created_at: string; - metadata?: { container?: { tags?: string[] } }; - }>(`/container/${encodeURIComponent(name)}/versions`); - return raw.map((v) => ({ id: v.id, createdAt: v.created_at, tags: v.metadata?.container?.tags ?? [] })); - } - - async deleteVersion(name: string, id: number): Promise { - await this.ctx.effect( - run('curl', ['-K', '-'], { - input: this.config('DELETE', `/container/${encodeURIComponent(name)}/versions/${id}`), - }), - ); - } -} - -export interface Pruned { - package: string; - id: number; - tags: string[]; -} - -/** The package an app's image is, under `ghcr.io/[/]`: the path and the app. */ -export function packageOf(prefix: string, app: string): string { - const path = prefix.toLowerCase().replace(/\/$/, '').split('/').slice(2); - return [...path, app].join('/'); -} - -/** Prune the named packages by the rule above; a package that does not exist yet has nothing to prune. */ -export async function prune(ctx: Context, packages: Packages, names: string[], now = new Date()): Promise { - const pruned: Pruned[] = []; - for (const name of names) { - const versions = await orAbsent(packages.versions(name), curlNotFound); - if (versions === undefined) { - ctx.say(`rotate: no package ${name} in ghcr.io/${packages.org}`); - continue; - } - for (const v of prunable(versions, now)) { - ctx.say(`rotate: ${name} ${v.tags.join(' ')} (${v.createdAt}) is older than ${PRUNE_AFTER_DAYS} days`); - await packages.deleteVersion(name, v.id); - pruned.push({ package: name, id: v.id, tags: v.tags }); - } - } - ctx.say( - `rotate: ${pruned.length} candidate version(s) pruned from ${names.length} package(s) of ghcr.io/${packages.org}`, - ); - return pruned; -} diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index b13ddcca..b3a64a3c 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -1,67 +1,107 @@ import assert from 'node:assert/strict'; +import type { PassThrough } from 'node:stream'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { deployLegsOf, environmentOf, hashesOf, legsOf, plan, readHashes, verbsOf } from './plan.ts'; +import { REPO } from '../testing/checkout.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; +import { appsOf, deployLegsOf, environmentOf, hashesOf, imageContextOf, legsOf, plan, readHashes } from './plan.ts'; const dryRun = JSON.stringify({ tasks: [ { taskId: '@acme/website#build', package: '@acme/website', hash: '0f2a', command: 'next build' }, - { taskId: '@acme/website#test', package: '@acme/website', hash: 'dc97', command: '' }, { taskId: '@acme/my-lib#build', package: '@acme/my-lib', hash: '4b6a' }, { taskId: '@acme/my-app#build', package: '@acme/my-app', hash: 'c51b', command: 'next build' }, - { taskId: '@acme/my-app#test', package: '@acme/my-app', hash: '5b05', command: 'pnpm test' }, + { taskId: '@acme/solver#build', package: '@acme/solver', hash: '9e1d', command: 'make' }, + { taskId: '@acme/stub#build', package: '@acme/stub', hash: 'aaaa', command: '' }, { taskId: '@other/x#build', package: '@other/x', hash: 'ffff', command: 'x' }, + // The e2e tasks of the same dry run: a suite is a package whose e2e task waits for the app's build. + { + taskId: '@acme/website-e2e#e2e', + package: '@acme/website-e2e', + hash: 'e2e1', + command: 'playwright test', + directory: 'e2e/website', + dependencies: ['@acme/website#build'], + }, + { + taskId: '@acme/website#e2e', + package: '@acme/website', + hash: 'e2e2', + command: '', + directory: 'apps/website', + dependencies: ['@acme/my-lib#build'], + }, + { + taskId: '@acme/tools#e2e', + package: '@acme/tools', + hash: 'e2e3', + command: '', + directory: 'e2e/tools', + dependencies: ['@acme/my-app#build'], + }, ], }); -const packages = { website: '@acme/website', 'my-app': '@acme/my-app' }; +const packages = { website: '@acme/website', 'my-app': '@acme/my-app', solver: '@acme/solver' }; const hashes = hashesOf(dryRun, packages); const run = { runId: '41', attempt: '1' }; -test('hashesOf keeps the build hash of each app’s package, and the test hash where the script exists', () => { +/** What a context narrated so far. */ +function narrated(ctx: Context): string { + const chunks: string[] = []; + for (let chunk = (ctx.io.stderr as PassThrough).read(); chunk !== null; chunk = (ctx.io.stderr as PassThrough).read()) + chunks.push(String(chunk)); + return chunks.join(''); +} + +test('hashesOf keeps the build hash of each app’s package, and the directory of the suite whose e2e waits for that build', () => { + // The rule `mise run e2e ` follows too: Turbo's graph, never a directory's name. assert.deepEqual(hashes, [ - { app: 'website', hash: '0f2a' }, - { app: 'my-app', hash: 'c51b', test: '5b05' }, + { app: 'website', hash: '0f2a', suites: ['e2e/website'] }, + { app: 'my-app', hash: 'c51b', suites: [] }, + { app: 'solver', hash: '9e1d', suites: [] }, ]); - assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope' }), []); + assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope', stub: '@acme/stub' }), []); }); -test('readHashes asks each app’s package.json for the name Turbo knows it by', async () => { - const io = fakeIo( - { - repo: { - 'package.json': JSON.stringify({ devDependencies: { turbo: '2.9.0' } }), - apps: { site: { 'package.json': JSON.stringify({ name: '@acme/website' }) } }, - }, +test('without a turbow, readHashes runs a plain dry run of build and e2e with the Turbo the lockfile has, in the environment it is given', async () => { + const seen: { args: string[]; cwd: string }[] = []; + const io = fakeIo(REPO, undefined, { + npx: (cwd, args) => { + seen.push({ cwd, args }); + return dryRun; }, - undefined, - { - npx: (_cwd, args) => { - assert.deepEqual(args, ['--yes', 'turbo@2.9.0', 'run', 'build', 'test', '--dry-run=json']); - return dryRun; - }, - }, - ); - assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['site']), [{ app: 'site', hash: '0f2a' }]); + }); + const env = { PLX_PLATFORM: 'linux-x64' }; + assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), { + hashes: [{ app: 'website', hash: '0f2a', suites: ['e2e/website'] }], + why: 'the checkout has no turbow to name the trusted cache with', + }); + assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', 'e2e', '--dry-run=json'] }]); }); -test('a leg names its runner from the strategy: the forge’s, a large slot, or an instance of its own', () => { - assert.deepEqual(legsOf(['website'], hashes, 'build', 'hybrid', run), [ - { app: 'website', hash: '0f2a', runner: 'exo-large-41-website-1', n: 1, build: true, test: '' }, - ]); - assert.equal(legsOf(['website'], hashes, 'build', 'github', run)[0]?.runner, 'ubuntu-latest'); - assert.equal(legsOf(['website'], hashes, 'build', 'on-prem', run)[0]?.runner, 'ci-large'); - assert.deepEqual( - legsOf(['my-app'], hashes, 'repro', 'hybrid', { runId: '41', attempt: '2' }).map((l) => l.runner), - ['exo-large-41-my-app-2-1', 'exo-large-41-my-app-2-2'], +test('readHashes refuses to run without PLX_PLATFORM, which no build lacks, and runs nothing', async () => { + const io = fakeIo(REPO, undefined, { npx: () => assert.fail('no dry run without the platform') }); + await assert.rejects(readHashes(new Context({}, io), '/repo', ['website'], {}), /PLX_PLATFORM is empty.*mise/s); +}); + +test('readHashes refuses a lockfile without Turbo for the workspace root', async () => { + const io = fakeIo( + { repo: { ...(REPO.repo as Tree), 'pnpm-lock.yaml': "lockfileVersion: '9.0'\nimporters:\n .: {}\n" } }, + undefined, + { npx: () => assert.fail('no dry run without a locked Turbo') }, + ); + await assert.rejects( + readHashes(new Context({}, io), '/repo', ['website'], { PLX_PLATFORM: 'linux-x64' }), + /pnpm-lock\.yaml locks no turbo/, ); - assert.throws(() => legsOf(['nope'], hashes, 'build', 'hybrid', run), /no build hash for nope/); }); -test('a leg is named after the verbs it mounts', () => { - assert.equal(verbsOf({ build: true, test: '5b05' }), 'build, test'); - assert.equal(verbsOf({ build: true, test: '' }), 'build'); - assert.equal(verbsOf({ build: false, test: '5b05' }), 'test'); +test('a leg names the runner of its e2e job from the strategy: the forge’s, a large slot, or an instance of its own', () => { + assert.equal(legsOf(['website'], hashes, 'hybrid', run)[0]?.runner, 'exo-large-41-website-1'); + assert.equal(legsOf(['website'], hashes, 'github', run)[0]?.runner, 'ubuntu-latest'); + assert.equal(legsOf(['website'], hashes, 'on-prem', run)[0]?.runner, 'ci-large'); + assert.equal(legsOf(['my-app'], hashes, 'hybrid', { runId: '41', attempt: '2' })[0]?.runner, 'exo-large-41-my-app-2'); + assert.throws(() => legsOf(['nope'], hashes, 'hybrid', run), /no build hash for nope/); }); test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { @@ -79,91 +119,127 @@ test('deployLegsOf: an app with a target deploys the commit’s image there, one }); }); -test('the plan skips what the registry holds, per build and per test, and plans the deploys of an environment', async () => { - // The pair holds website's build and nothing of my-app. - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.endsWith(':5000/v2/website/manifests/build-0f2a') ? '' : notThere('curl')), +/** A forge registry, as crane sees it, holding the refs given; every look-up is recorded. */ +function forge(holds: string[]) { + const asked: string[] = []; + const io = fakeIo(REPO, undefined, { + crane: (_cwd, args) => { + asked.push(args.join(' ')); + return args[0] === 'digest' && holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere(); + }, }); - const result = await plan(new Context({}, io), { - apps: ['website', 'my-app'], - mode: 'build', - tests: true, + return { io, asked }; +} + +test('every app gets a publish leg, and a large job where the plan could not ask the cache and its job’s tasks are needed', async () => { + const { io, asked } = forge(['ghcr.io/acme/website:build-0f2a']); + const result = await plan(new Context({}, io), '/repo', { + apps: ['website', 'my-app', 'solver'], hashes, strategy: 'hybrid', - registry: { kind: 'own' }, + prefix: 'ghcr.io/Acme', run, - deploy: { - environment: 'staging', - targets: { 'my-app': 'ssh://plexus@host-a' }, - prefix: 'ghcr.io/acme', - sha: 'abc', - }, }); - // One leg, one instance: my-app's build and its test after it. + assert.deepEqual(asked, [ + 'digest ghcr.io/acme/website:build-0f2a', + 'digest ghcr.io/acme/my-app:build-c51b', + 'digest ghcr.io/acme/solver:build-9e1d', + ]); assert.deepEqual(result.legs, [ - { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', n: 1, build: true, test: '5b05' }, + // The image is there: publish adds the commit’s tag; its suite still runs, the cache unasked. + { + app: 'website', + hash: '0f2a', + runner: 'exo-large-41-website-1', + suites: ['e2e/website'], + context: 'output', + build: false, + // Nothing asked of the trusted cache: its tasks count as work. + large: true, + }, + // No suite: its e2e job builds the app into the trusted cache and runs no suite; the image is missing. + { + app: 'my-app', + hash: 'c51b', + runner: 'exo-large-41-my-app-1', + suites: [], + context: 'output', + build: true, + large: true, + }, + // A Dockerfile of its own and no suite: built from a pruned context, and no large job. + { + app: 'solver', + hash: '9e1d', + runner: 'exo-large-41-solver-1', + suites: [], + context: 'pruned', + build: true, + large: false, + }, ]); - assert.deepEqual(result.skipped, [{ app: 'website', hash: '0f2a', ref: 'localhost:5000/website:build-0f2a' }]); - assert.deepEqual(result.apps, hashes); - assert.equal(result.environment, 'staging'); - assert.deepEqual(result.deploys, [{ app: 'my-app', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/my-app:abc' }]); + assert.equal(result.environment, ''); + assert.deepEqual(result.deploys, []); }); -test('an app whose build the registry holds and whose test it does not gets a leg that only tests', async () => { - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.includes('/manifests/build-') ? '' : notThere('curl')), - }); - const result = await plan(new Context({}, io), { +test('the plan says which images exist and which publish will build', async () => { + const { io } = forge(['ghcr.io/acme/website:build-0f2a']); + const ctx = new Context({}, io); + await plan(ctx, '/repo', { apps: ['website', 'my-app'], hashes, strategy: 'github', prefix: 'ghcr.io/acme', run }); + assert.equal( + narrated(ctx), + [ + 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', + 'website: the trusted cache was not asked; a large job', + 'my-app: ghcr.io/acme/my-app:build-c51b is missing; publish builds it', + 'my-app: the trusted cache was not asked; a large job', + '', + ].join('\n'), + ); +}); + +test('a look-up that cannot run is the job’s fault, never a missing image', async () => { + const io = fakeIo(REPO, undefined, { crane: () => undefined }); + await assert.rejects( + plan(new Context({}, io), '/repo', { apps: ['website'], hashes, strategy: 'github', prefix: 'ghcr.io/acme', run }), + /could not look up ghcr.io\/acme\/website:build-0f2a/, + ); +}); + +test('with an environment the plan adds the deploys of the apps with a target there', async () => { + const { io } = forge([]); + const result = await plan(new Context({}, io), '/repo', { apps: ['website', 'my-app'], - mode: 'build', - tests: true, - hashes, - strategy: 'hybrid', - registry: { kind: 'own' }, - run, - }); - assert.deepEqual(result.legs, [ - { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', n: 1, build: false, test: '5b05' }, - ]); - assert.equal(result.skipped.length, 2); - // Without --test and in repro mode no leg tests. - const builds = await plan(new Context({}, io), { - apps: ['my-app'], - mode: 'repro', - tests: true, hashes, - strategy: 'hybrid', - registry: { kind: 'own' }, + strategy: 'on-prem', + prefix: 'ghcr.io/acme', run, + deploy: { environment: 'staging', targets: { 'my-app': 'ssh://plexus@host-a' }, sha: 'abc' }, }); assert.deepEqual( - builds.legs.map((l) => [l.n, l.build, l.test]), + result.legs.map((l) => [l.app, l.runner, l.build]), [ - [1, true, ''], - [2, true, ''], + ['website', 'ci-large', true], + ['my-app', 'ci-large', true], ], ); + assert.equal(result.environment, 'staging'); + assert.deepEqual(result.deploys, [{ app: 'my-app', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/my-app:abc' }]); }); -test('with the forge’s registry the look-up is crane’s, and without an environment nothing deploys', async () => { - const asked: string[] = []; - const io = fakeIo({}, undefined, { - crane: (_cwd, args) => { - asked.push(args.join(' ')); - return args[1]?.endsWith(':build-0f2a') ? 'sha256:abc' : notThere('crane'); - }, - }); - const result = await plan(new Context({}, io), { - apps: ['website'], - mode: 'build', - tests: true, - hashes, - strategy: 'github', - registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' }, - run, +test('the apps are the directories under apps/, and a checkout without apps/ says so in one line', async () => { + assert.deepEqual(await appsOf(new Context({}, fakeIo(REPO)), '/repo'), ['my-app', 'solver', 'website']); + await assert.rejects(appsOf(new Context({}, fakeIo({ repo: {} })), '/repo'), (error: Error) => { + assert.equal(error.message, '/repo has no apps/: the plan reads the apps of an app repo there'); + return true; }); - assert.deepEqual(asked, ['digest ghcr.io/plexus-ms-tenant/website:build-0f2a']); - assert.deepEqual(result.legs, []); - assert.deepEqual(result.deploys, []); - assert.equal(result.environment, ''); +}); + +test('an app without a marker builds from a pruned context; a marker that does not parse is an error that names it', async () => { + const tree = structuredClone(REPO); + const apps = (tree.repo as Tree).apps as Tree; + delete (apps.website as Tree)['PLEXUS.md']; + assert.equal(await imageContextOf(new Context({}, fakeIo(tree)), '/repo', 'website'), 'pruned'); + (apps.website as Tree)['PLEXUS.md'] = '---\ntemplates: [app-nextjs\n - nope\n---\n'; + await assert.rejects(imageContextOf(new Context({}, fakeIo(tree)), '/repo', 'website'), /apps\/website\/PLEXUS\.md/); }); diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 8fd89671..815e3309 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -1,45 +1,147 @@ -// The plan of a run (§ 8 PLX-Delivery): for every app, the build and the test -// hash from one Turbo dry run and a look-up in the registry, which leaves one -// leg per app that owes something: the build where its image is missing, the -// test where its test tag is, both on one machine, the test after the build -// (two build legs without cache in repro mode, which plans no test). Each leg -// names the runner its job asks for, from the strategy: the forge's, a large -// slot, or, under hybrid, the one label of an instance `hybrid -// create-instances` then creates for it. With a deploy asked for, the plan also says which -// environment the run releases into and where each app deploys there, from -// the platform repo's inventory. The plan decides and launches nothing: its -// result is the matrices the jobs fan out over. +// The plan of a run (§ 8 PLX-Delivery): every app's build hash from one Turbo +// dry run, a look-up of `build-` in the forge's registry, and, from the +// same dry run with the trusted cache named, whether the cache holds the +// tasks an app's large job would run. That leaves one leg per app, which +// publish fans out over: `build`, the image is missing and publish makes it, +// or the image is there and publish adds the commit's tag; what publish makes +// it from, `output`, the directory the app's build leaves (an app from +// app-nextjs, by its marker), or `pruned`, a pruned context its Dockerfile +// builds itself from (§ 4 PLX-Delivery); the directories of the app's E2E +// suites, none or several, for the large job's browsers; and `large`, whether +// the app gets a large job, its e2e job. The suites are what `mise run e2e +// ` runs: the packages whose e2e task Turbo has wait for the app's build. +// +// An app's large job has work when a task it would run is a MISS in the +// trusted cache and its result is needed. The e2e of each of the app's suites +// is always needed; the app's build output is needed when the app has one or +// more suites, which start it, and when the image is missing and is built from +// the output, which publish restores. So an app with suites gets a large job +// when its build or the e2e of any of its suites is a MISS; one without a +// suite, built from the output, when its image is missing and its build is a +// MISS; one with a Dockerfile of its own and no suite never, since its publish +// builds itself. A MISS is Turbo's word: an entry not found, or a cache that +// did not answer for it, and the plan's line for the app says no more. +// A task the package does not define (``) is no MISS that asks +// for a job. What the plan cannot find out counts as work: without a turbow +// to name the cache, with the cache `none` or no cache step, with a dry run +// that gives no cache status, every status is unknown and counts as a MISS, +// and the plan says why in one line. A server that does not answer gives a +// MISS for every task in Turbo's dry run, which is work all the same; the +// plan reads Turbo's warning for its line. +// +// The plan asks the cache the way the repo's verbs reach it: through the +// repo's own `./turbow trusted`, which names the server its job announced +// (PLX_TURBO_TRUSTED and its token, the team from origin) in a job of the +// forge, and the shared server elsewhere, as a build there would; with the +// Turbo the lockfile has first on its PATH, run by npx without an install. A +// dry run only asks: it sends a HEAD request per task, beside a status +// request and an empty listing, and restores and writes nothing (seen against +// the cache server the step starts, brunojppb/turbo-cache-server 5.0.4). +// That Turbo's dry run gives each task `cache: { status: 'HIT' | 'MISS' }` +// when a remote cache is named is not in its documentation of `--dry`; it is +// what Turbo 2.11.13 does, and planCache.test.ts holds the shape, so that a +// Turbo that changes it gives every app its job rather than none. +// +// Each leg names the runner of its large job, from the strategy: the forge's, +// a large slot, or, under hybrid, the one label of an instance `hybrid +// create-instances` then creates for it. With a deploy asked for, the plan +// also says which environment the run deploys into and where each app deploys +// there, from the operations repo's inventory. The plan decides and launches +// nothing: its result is the matrices the jobs fan out over. No test hash is +// computed and nothing records that an image was tested: that publish follows +// the e2e jobs is the order of the jobs. +// +// The hash is the build's own only when the dry run sees what the build sees: +// the Turbo the lockfile has, run with no node_modules, and the environment +// of the repo's mise, which gives PLX_PLATFORM to every task (§ 1.10 of the +// app's build hash). Without PLX_PLATFORM the plan refuses: its hash would be +// one no build ever has. import type { Context, EnvironmentTargets } from '@plexus-ms/lib'; -import { UsageError } from '@plexus-ms/lib'; -import { digestOf, findTag, imageName, layersOf, type Registry } from './registry.ts'; +import { ExecError, MARKER_FILE, parseMarkerConfig, run as step, UsageError, write } from '@plexus-ms/lib'; +import { parseAllDocuments } from 'yaml'; +import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; -export type Mode = 'build' | 'force' | 'repro'; +/** Whether the trusted cache holds an app's build, and the e2e of every one of its suites (true where it has none). */ +export interface Cached { + build: boolean; + e2e: boolean; +} -/** One app's hashes: of its build task, and of its test task when it has one. */ +/** One app's build hash, Turbo's hash of its package's build task, the directories of its E2E suites, and what the cache holds. */ export interface Hash { app: string; hash: string; - test?: string; + suites: string[]; + /** Absent where the dry run said nothing of the cache for one of these tasks: every one of them unknown. */ + cached?: Cached; + /** With `cached`: whether the cache holds each task, `build` and each suite's directory, in that order. */ + hits?: Record; } /** Turbo's marker for a task whose script the package does not define. */ const NONEXISTENT = ''; -/** The build and test hashes from Turbo's dry run (`turbo run build test --dry-run=json`), per app, by its package's name. */ +interface DryTask { + taskId: string; + package: string; + hash: string; + command?: string; + directory?: string; + dependencies?: string[]; + cache?: { status?: string }; +} + +/** Whether the dry run says if the cache holds the task. */ +const told = (t: DryTask): boolean => t.cache?.status === 'HIT' || t.cache?.status === 'MISS'; + +/** The tasks of a dry run that exist, and the first of them that has no cache status, if any. */ +function tasksOf(dryRun: string): { tasks: DryTask[]; unknown?: string } { + const tasks = ((JSON.parse(dryRun) as { tasks?: DryTask[] }).tasks ?? []).filter((t) => t.command !== NONEXISTENT); + return { tasks, unknown: tasks.find((t) => !told(t))?.taskId }; +} + +/** + * The build hashes from Turbo's dry run (`turbo run build e2e --dry-run=json`), + * per app, by its package's name; the directories of the packages whose e2e + * task waits for that build, its suites, sorted; and whether the cache holds + * the build and each suite's e2e, where the dry run gives every one of them a + * cache status. + */ export function hashesOf(dryRun: string, packages: Record): Hash[] { - const data = JSON.parse(dryRun) as { - tasks?: { taskId: string; package: string; hash: string; command?: string }[]; - }; - const tasks = (data.tasks ?? []).filter((t) => t.command !== NONEXISTENT); + const { tasks } = tasksOf(dryRun); return Object.entries(packages).flatMap(([app, name]) => { const build = tasks.find((t) => t.package === name && t.taskId.endsWith('#build')); if (!build) return []; - const test = tasks.find((t) => t.package === name && t.taskId.endsWith('#test')); - return [{ app, hash: build.hash, ...(test ? { test: test.hash } : {}) }]; + const suites = tasks + .filter((t) => t.taskId.endsWith('#e2e') && t.dependencies?.includes(build.taskId)) + .sort((x, y) => (x.directory ?? '').localeCompare(y.directory ?? '')); + const hit = (t: DryTask) => t.cache?.status === 'HIT'; + const known = told(build) && suites.every(told); + const cached = known + ? { + cached: { build: hit(build), e2e: suites.every(hit) }, + hits: Object.fromEntries([['build', hit(build)], ...suites.map((t) => [t.directory ?? t.taskId, hit(t)])]), + } + : {}; + return [{ app, hash: build.hash, suites: suites.map((t) => t.directory ?? ''), ...cached }]; }); } +/** The apps of a checkout: the directories under apps/, sorted. */ +export async function appsOf(ctx: Context, dir: string): Promise { + let entries: { name: string; directory: boolean }[]; + try { + entries = await ctx.readDir(`${dir}/apps`); + } catch { + throw new UsageError(`${dir} has no apps/: the plan reads the apps of an app repo there`); + } + return entries + .filter((e) => e.directory) + .map((e) => e.name) + .sort(); +} + /** The name of an app's package, `apps//package.json`: what Turbo calls it. */ export async function packageName(ctx: Context, dir: string, app: string): Promise { const pkg = JSON.parse(await ctx.readFile(`${dir}/apps/${app}/package.json`)) as { name?: string }; @@ -47,19 +149,118 @@ export async function packageName(ctx: Context, dir: string, app: string): Promi return pkg.name; } -/** Turbo at the version the repo's root pins. */ +/** + * Turbo at the version the repo's lockfile has for its root, `turbo@`, + * which npx runs without an install. pnpm 11 and later write the package + * manager's own document before the workspace's; the workspace's is the one + * whose root lists turbo. + */ export async function turboOf(ctx: Context, dir: string): Promise { - const pkg = JSON.parse(await ctx.readFile(`${dir}/package.json`)) as { devDependencies?: Record }; - return `turbo@${pkg.devDependencies?.turbo ?? 'latest'}`; + const text = await ctx.readFile(`${dir}/pnpm-lock.yaml`); + for (const doc of parseAllDocuments(text)) { + const lock = (Array.isArray(doc) ? undefined : doc.toJS()) as { + importers?: Record }>; + } | null; + const version = lock?.importers?.['.']?.devDependencies?.turbo?.version; + if (version) return `turbo@${version}`; + } + throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); } -export async function readHashes(ctx: Context, dir: string, apps: string[]): Promise { +/** A hash with nothing known of the cache. */ +const forgotten = ({ cached: _, hits: __, ...hash }: Hash): Hash => hash; + +/** The hashes, and why the plan could not ask the trusted cache, empty where it could. */ +export interface Hashes { + hashes: Hash[]; + why: string; +} + +/** + * The build hashes, suites and cache statuses of `apps`, from one dry run of + * the Turbo the lockfile has, in `env`, the repo's mise environment: through + * the repo's turbow, which names the trusted cache, where the checkout has + * one; else, or where turbow cannot name it, a dry run that asks no cache. + */ +export async function readHashes( + ctx: Context, + dir: string, + apps: string[], + env: NodeJS.ProcessEnv = process.env, +): Promise { + if (!env.PLX_PLATFORM) + throw new UsageError( + 'PLX_PLATFORM is empty: the plan runs in the repo’s mise environment, as its build does (after `mise install`, or under `mise exec`), or its hashes are ones no build has', + ); const packages: Record = {}; for (const app of apps) packages[app] = await packageName(ctx, dir, app); - const out = await ctx.read('npx', ['--yes', await turboOf(ctx, dir), 'run', 'build', 'test', '--dry-run=json'], { - cwd: dir, - }); - return hashesOf(out, packages); + const turbo = await turboOf(ctx, dir); + const dry = ['run', 'build', 'e2e', '--dry-run=json']; + const unasked = async (why: string): Promise => { + const out = await ctx.read('npx', ['--yes', turbo, ...dry], { cwd: dir, env }); + return { hashes: hashesOf(out, packages).map(forgotten), why }; + }; + try { + await ctx.readFile(`${dir}/turbow`); + } catch { + return unasked('the checkout has no turbow to name the trusted cache with'); + } + // turbow runs `turbo` from the PATH: the lockfile's, through npx, in a directory of its own first. + const shim = ((await ctx.stage(step('mktemp', ['-d', '-t', 'plx-ci-turbo-XXXXXX']))) ?? '').trim(); + const errors = `${shim}/turbow.err`; + await ctx.stage(write(`${shim}/turbo`, `#!/bin/sh\nexec npx --yes ${turbo} "$@"\n`)); + await ctx.stage(step('chmod', ['755', `${shim}/turbo`])); + const lines = async () => (await ctx.readFile(errors).catch(() => '')).split('\n'); + const said = async () => (await lines()).find((l) => l.startsWith('turbow:'))?.replace(/^turbow:\s*/, '') ?? ''; + // Turbo's own warning where the server it was named does not answer (2.11.13); its statuses are then all MISS. + const unavailable = async () => + (await lines()).find((l) => /Remote caching unavailable/.test(l))?.replace(/^\s*WARNING\s*•?\s*/, ''); + try { + const out = await ctx.read('sh', ['-c', 'exec ./turbow "$@" 2>"$0"', errors, 'trusted', ...dry], { + cwd: dir, + env: { ...env, PATH: `${shim}:${env.PATH ?? ''}` }, + }); + const line = await said(); + const without = /^without a remote cache: (.*)$/.exec(line)?.[1]; + const why = without ?? (await unavailable()); + if (why !== undefined) return { hashes: hashesOf(out, packages).map(forgotten), why }; + const { unknown } = tasksOf(out); + if (unknown !== undefined) + return { + hashes: hashesOf(out, packages), + why: `Turbo’s dry run (${turbo}) gave no cache status for ${unknown}`, + }; + return { hashes: hashesOf(out, packages), why: '' }; + } catch (error) { + if (!(error instanceof ExecError)) throw error; + // turbow's own words, its last line: the reason it gives, or what failed under it. + const last = (await lines()) + .filter((l) => l.trim() !== '') + .at(-1) + ?.replace(/^turbow:\s*/, ''); + return unasked(`turbow failed: ${last ?? error.message.split('\n')[0]}`); + } finally { + await ctx.stage(step('rm', ['-rf', shim])); + } +} + +/** What publish makes an app's image from: the directory its build leaves, or a pruned context its own Dockerfile builds in. */ +export type ImageContext = 'output' | 'pruned'; + +/** An app's image context: `output` where its marker lists the template app-nextjs, whose Dockerfile only copies the build output; `pruned` otherwise. */ +export async function imageContextOf(ctx: Context, dir: string, app: string): Promise { + const path = `apps/${app}/${MARKER_FILE}`; + let marker: string; + try { + marker = await ctx.readFile(`${dir}/${path}`); + } catch { + return 'pruned'; + } + try { + return (parseMarkerConfig(marker).templates ?? []).includes('app-nextjs') ? 'output' : 'pruned'; + } catch (error) { + throw new UsageError(`${path}: ${error instanceof Error ? error.message : String(error)}`); + } } /** The run a plan is for; names the instances under hybrid. */ @@ -68,52 +269,50 @@ export interface Run { attempt: string; } -/** - * A large job: one app, the runner it asks for, and what it owes there. `hash` - * is the build hash, the candidate's tag, whether or not the leg builds it. - */ +/** One app of the run: the runner of its e2e job, and what its publish does. */ export interface Leg { app: string; + /** The build hash: the image's tag `build-`. */ hash: string; + /** The runner the app's e2e job asks for. */ runner: string; - n: number; - /** The image is to be built. */ + /** The directories of the app's E2E suites, none for none. */ + suites: string[]; + /** What publish makes the image from. */ + context: ImageContext; + /** The forge's registry lacks `build-`: publish builds the image; else it tags the one there. */ build: boolean; - /** The test hash where the candidate is to be tested, else empty. */ - test: string; + /** The app gets a large job: a task of it is a MISS in the trusted cache, or unknown, and its result is needed. */ + large: boolean; } -/** A deploy job: one app, where it deploys in the run's environment, and the image the release publishes. */ +/** A deploy job: one app, where it deploys in the run's environment, and the image the run publishes. */ export interface DeployLeg { app: string; host: string; image: string; } -/** The verbs a leg owes, as the plan prints them: `build`, `test`, or `build, test`. */ -export const verbsOf = (leg: Pick): string => - [leg.build ? 'build' : '', leg.test ? 'test' : ''].filter((v) => v !== '').join(', '); - -/** The legs a mode asks for, one per app (two in repro mode), before the registry is consulted and the tests are added. */ -export function legsOf(apps: string[], hashes: Hash[], mode: Mode, strategy: Strategy, run: Run): Leg[] { - return apps.flatMap((app) => { - const hash = hashes.find((h) => h.app === app)?.hash; - if (!hash) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); - const copies = mode === 'repro' ? 2 : 1; - return Array.from({ length: copies }, (_, i) => { - const n = i + 1; - const base = `exo-large-${run.runId}-${app}-${run.attempt}`; - const runner = runnerOf(strategy, 'large', mode === 'repro' ? `${base}-${n}` : base); - return { app, hash, runner, n, build: true, test: '' }; - }); +/** The runner of each app's e2e job, before the checkout and the registry are read. */ +export function legsOf( + apps: string[], + hashes: Hash[], + strategy: Strategy, + run: Run, +): Omit[] { + return apps.map((app) => { + const found = hashes.find((h) => h.app === app); + if (!found) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); + const runner = runnerOf(strategy, 'large', `exo-large-${run.runId}-${app}-${run.attempt}`); + return { app, hash: found.hash, runner, suites: found.suites }; }); } /** - * The environment a run releases into (§ 3 PLX-Delivery): `given` when the + * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the * caller stands in for an environment branch, else main is production and * develop is staging, on a push or a run by hand; anything else, a pull - * request among it, releases nowhere. + * request among it, deploys nowhere. */ export function environmentOf(event: string, ref: string, given = ''): string { if (given) return given; @@ -139,70 +338,41 @@ export function deployLegsOf( } export interface Plan { - /** The large jobs to run: per app, the build, the test, or both. */ + /** One per app: what publish fans out over, and, those with `large`, the large jobs. */ legs: Leg[]; - /** Every app planned, with its hashes: what the publish fans out over. */ - apps: Hash[]; - /** The environment the run releases into, empty for none. */ + /** The environment the run deploys into, empty for none. */ environment: string; - /** The deploys of the release, empty without an environment. */ + /** The deploys of the run, empty without an environment. */ deploys: DeployLeg[]; - skipped: { app: string; hash: string; ref: string }[]; - skippedTests: { app: string; hash: string; ref: string }[]; } export interface PlanOptions { apps: string[]; - mode: Mode; - /** Plan tests too; off for the build measurements. */ - tests?: boolean; hashes: Hash[]; strategy: Strategy; - registry: Registry; + /** Where the published images live, `ghcr.io/`. */ + prefix: string; run: Run; - /** With a deploy asked for: the environment, its targets, and what names the published image. */ - deploy?: { environment: string; targets: EnvironmentTargets; prefix: string; sha: string }; + /** With a deploy asked for: the environment, its targets, and the commit the deploys take. */ + deploy?: { environment: string; targets: EnvironmentTargets; sha: string }; } -export async function plan(ctx: Context, options: PlanOptions): Promise { - const { apps, hashes, mode, strategy, registry, run } = options; - const result: Plan = { - legs: [], - apps: apps.map((app) => { - const h = hashes.find((x) => x.app === app); - if (!h) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); - return h; - }), - environment: options.deploy?.environment ?? '', - deploys: [], - skipped: [], - skippedTests: [], - }; - for (const leg of legsOf(apps, hashes, mode, strategy, run)) { - let build = true; - if (mode === 'build') { - const ref = await findTag(ctx, registry, leg.app, `build-${leg.hash}`); - if (ref !== undefined) { - ctx.say(`${leg.app}: ${ref} exists, nothing to build`); - result.skipped.push({ app: leg.app, hash: leg.hash, ref }); - build = false; - } - } - // The test of an app with a test task, on the machine that builds it or, - // the build being there already, on one that only tests. - let test = (options.tests && mode !== 'repro' && hashes.find((h) => h.app === leg.app)?.test) || ''; - if (test && mode === 'build') { - const ref = await findTag(ctx, registry, leg.app, `test-${test}`); - if (ref !== undefined) { - ctx.say(`${leg.app}: ${ref} exists, nothing to test`); - result.skippedTests.push({ app: leg.app, hash: test, ref }); - test = ''; - } - } - if (build || test) result.legs.push({ ...leg, build, test }); +/** The plan of `dir`, a checkout: a leg per app, its image looked up in the forge's registry, and the deploys. */ +export async function plan(ctx: Context, dir: string, options: PlanOptions): Promise { + const { apps, hashes, strategy, prefix, run } = options; + const result: Plan = { legs: [], environment: options.deploy?.environment ?? '', deploys: [] }; + for (const leg of legsOf(apps, hashes, strategy, run)) { + const ref = `${imageName(prefix, leg.app)}:build-${leg.hash}`; + const build = (await craneDigest(ctx, ref)) === undefined; + ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); + const context = await imageContextOf(ctx, dir, leg.app); + const found = hashes.find((h) => h.app === leg.app); + const large = hasWork({ suites: leg.suites, context, build }, found?.cached); + ctx.say(`${leg.app}: ${holds(found?.hits)}; ${large ? 'a large job' : 'no large job'}`); + result.legs.push({ ...leg, context, build, large }); } if (options.deploy?.environment) { - const { environment, targets, prefix, sha } = options.deploy; + const { environment, targets, sha } = options.deploy; const { legs, without } = deployLegsOf(apps, targets, prefix, sha); result.deploys = legs; for (const app of without) ctx.say(`${app} has no deployment in ${environment}; nothing to deploy`); @@ -210,59 +380,31 @@ export async function plan(ctx: Context, options: PlanOptions): Promise { return result; } -export interface Comparison { - app: string; - hash: string; - digest?: string; - /** In repro mode: the two builds' digests and the layers that differ. */ - repro?: { one?: string; two?: string; identical: boolean; layers: number; same: number; differing: string[] }; +/** Whether an app's large job has work (see the top): a task it would run is a MISS, or unknown, and its result is needed. */ +export function hasWork(leg: Pick, cached: Cached | undefined): boolean { + const buildMiss = !cached?.build; + if (leg.suites.length > 0) return buildMiss || !cached?.e2e; + return leg.context === 'output' && leg.build && buildMiss; } -/** What the registry holds after a run: every app's digest, and in repro mode the two builds compared layer by layer. */ -export async function report( - ctx: Context, - registry: Registry, - legs: Leg[], - mode: Mode, - runId: string, -): Promise { - const apps = [...new Set(legs.map((l) => l.app))].sort(); - const out: Comparison[] = []; - for (const app of apps) { - const hash = legs.find((l) => l.app === app)?.hash ?? ''; - const c: Comparison = { app, hash, digest: await digestOf(ctx, registry, app, `build-${hash}`) }; - ctx.say(`${app} build-${hash}: ${c.digest ?? 'missing'}`); - if (mode === 'repro') { - const [one, two] = await Promise.all([ - digestOf(ctx, registry, app, `repro-${runId}-1`), - digestOf(ctx, registry, app, `repro-${runId}-2`), - ]); - const identical = one !== undefined && one === two; - const [l1, l2] = identical - ? [[], []] - : await Promise.all([ - layersOf(ctx, registry, app, `repro-${runId}-1`), - layersOf(ctx, registry, app, `repro-${runId}-2`), - ]); - const differing: string[] = []; - const a = l1 ?? []; - const b = l2 ?? []; - for (let i = 0; i < Math.max(a.length, b.length); i++) { - if (a[i]?.digest !== b[i]?.digest) - differing.push( - `layer ${i + 1}: ${a[i]?.digest ?? '-'} (${a[i]?.size ?? '-'}) vs ${b[i]?.digest ?? '-'} (${b[i]?.size ?? '-'})`, - ); - } - c.repro = { one, two, identical, layers: a.length, same: a.length - differing.length, differing }; - if (identical) ctx.say(` reproducible: both builds are ${one}`); - else { - ctx.say( - ` not identical: ${one ?? '-'} vs ${two ?? '-'}; layers: ${a.length} in each, ${a.length - differing.length} identical`, - ); - for (const d of differing) ctx.say(` ${d}`); - } - } - out.push(c); - } - return out; +/** + * What the dry run said of an app's tasks, as the plan says it: Turbo's HIT or + * MISS for each, a MISS being an entry not found, or a cache that did not + * answer for it (a server that answers 500 gives a MISS without a warning). + */ +function holds(hits: Record | undefined): string { + if (!hits) return 'the trusted cache was not asked'; + const said = Object.entries(hits).map(([task, hit]) => `${task} ${hit ? 'HIT' : 'MISS'}`); + const miss = Object.values(hits).includes(false) ? ' (a MISS: not found, or not answered)' : ''; + return `in the trusted cache, ${said.join(', ')}${miss}`; +} + +/** The outputs of a plan for the workflow: the large jobs' matrix, every app for publish, the deploys, the environment. */ +export function outputsOf(result: Plan): Record<'matrix' | 'apps' | 'deploys' | 'environment', string> { + return { + matrix: JSON.stringify(result.legs.filter((l) => l.large)), + apps: JSON.stringify(result.legs), + deploys: JSON.stringify(result.deploys), + environment: result.environment, + }; } diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts new file mode 100644 index 00000000..67b93d9c --- /dev/null +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -0,0 +1,374 @@ +// The plan asks Turbo's trusted cache, in its dry run, which tasks of an app's +// large job it holds, and gives the app a large job only where there is work. +// The dry runs here hold the shape Turbo 2.11.13 gives a task when a remote +// cache is named, `cache: { local, remote, status, source, timeSaved }`, seen +// against the cache server the step starts; a Turbo that drops or renames it +// fails these tests, and the plan then gives every app its job. +import assert from 'node:assert/strict'; +import type { PassThrough } from 'node:stream'; +import { test } from 'node:test'; +import { Context } from '@plexus-ms/lib'; +import { app, REPO } from '../testing/checkout.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; +import { hashesOf, outputsOf, plan, readHashes } from './plan.ts'; + +type Status = 'HIT' | 'MISS' | undefined; + +/** A task of a dry run with the cache named: its cache status, or no cache field at all where `status` is undefined. */ +function task(id: string, hash: string, command: string, status: Status, extra: object = {}) { + const [pkg] = id.split('#'); + const cache = + status === 'HIT' + ? { local: false, remote: true, status, source: 'REMOTE', timeSaved: 2119 } + : { local: false, remote: false, status, timeSaved: 0 }; + return { taskId: id, package: pkg, hash, command, ...(status ? { cache } : {}), ...extra }; +} + +/** + * The dry run of `build e2e` for website (two suites), my-app (no suite, from + * the output), solver (a Dockerfile of its own, no suite) and worker (a + * Dockerfile of its own, a suite), with the statuses given. + */ +function dryRun(s: { + website?: Status; + websiteE2e?: Status; + websiteSmoke?: Status; + myApp?: Status; + solver?: Status; + worker?: Status; + workerE2e?: Status; + nonexistent?: Status; +}) { + return JSON.stringify({ + tasks: [ + task('@acme/website#build', '0f2a', 'next build', s.website), + task('@acme/website-e2e#e2e', 'e2e1', 'playwright test', s.websiteE2e, { + directory: 'e2e/website', + dependencies: ['@acme/website#build'], + }), + // A second suite of website: `mise run e2e website` runs both. + task('@acme/website-smoke#e2e', 'e2e6', 'playwright test', s.websiteSmoke, { + directory: 'e2e/website-smoke', + dependencies: ['@acme/website#build'], + }), + // A task the package does not define: always MISS, never work. + task('@acme/website#e2e', 'e2e2', '', s.nonexistent ?? 'MISS', { directory: 'apps/website' }), + // A package that waits for website's build and has no e2e of its own: no suite, never work. + task('@acme/docs#e2e', 'e2e5', '', s.nonexistent ?? 'MISS', { + directory: 'docs', + dependencies: ['@acme/website#build'], + }), + task('@acme/my-app#build', 'c51b', 'next build', s.myApp), + task('@acme/my-app#e2e', 'e2e3', '', s.nonexistent ?? 'MISS', { directory: 'apps/my-app' }), + task('@acme/solver#build', '9e1d', 'make', s.solver), + task('@acme/worker#build', '7a7a', 'make', s.worker), + task('@acme/worker-e2e#e2e', 'e2e4', 'node e2e.js', s.workerE2e, { + directory: 'e2e/worker', + dependencies: ['@acme/worker#build'], + }), + ], + }); +} + +const packages = { + website: '@acme/website', + 'my-app': '@acme/my-app', + solver: '@acme/solver', + worker: '@acme/worker', +}; +const run = { runId: '41', attempt: '1' }; + +/** REPO with worker, an app with a Dockerfile of its own, and a turbow at the root unless `turbow` is false. */ +function checkout(turbow = true): Tree { + const tree = structuredClone(REPO); + const repo = tree.repo as Tree; + (repo.apps as Tree).worker = app('@acme/worker', []); + if (turbow) repo.turbow = '#!/bin/sh\n'; + return tree; +} + +/** What a context narrated so far. */ +function narrated(ctx: Context): string { + const chunks: string[] = []; + for (let chunk = (ctx.io.stderr as PassThrough).read(); chunk !== null; chunk = (ctx.io.stderr as PassThrough).read()) + chunks.push(String(chunk)); + return chunks.join(''); +} + +/** The plan of the four apps for a dry run, the forge's registry holding `holds`; the apps that get a large job. */ +async function large(statuses: Parameters[0], holds: string[] = []): Promise { + const io = fakeIo(checkout(), undefined, { + crane: (_cwd, args) => (holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane')), + }); + const result = await plan(new Context({}, io), '/repo', { + apps: Object.keys(packages), + hashes: hashesOf(dryRun(statuses), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + return result.legs.filter((l) => l.large).map((l) => l.app); +} + +const ALL_HIT = { + website: 'HIT', + websiteE2e: 'HIT', + websiteSmoke: 'HIT', + myApp: 'HIT', + solver: 'HIT', + worker: 'HIT', + workerE2e: 'HIT', +} as const; +const IMAGES = ['website', 'my-app', 'solver', 'worker'].map( + (a) => `ghcr.io/acme/${a}:build-${{ website: '0f2a', 'my-app': 'c51b', solver: '9e1d', worker: '7a7a' }[a]}`, +); + +test('hashesOf reads whether the cache holds an app’s build and the e2e of all its suites; a task without a cache field leaves it unknown', () => { + const [website, myApp] = hashesOf( + dryRun({ website: 'HIT', websiteE2e: 'MISS', websiteSmoke: 'HIT', myApp: 'MISS' }), + packages, + ); + assert.deepEqual(website?.suites, ['e2e/website', 'e2e/website-smoke']); + assert.deepEqual(website?.cached, { build: true, e2e: false }); + // No suite: there is no e2e to hold, which is no work. + assert.deepEqual(myApp?.cached, { build: false, e2e: true }); + // A Turbo whose dry run gives no cache field for a task: unknown, never a hit. + assert.equal(hashesOf(dryRun({ websiteE2e: 'HIT' }), packages)[0]?.cached, undefined); + // The second suite without a status: the app's statuses are unknown, not a MISS the cache answered. + assert.equal(hashesOf(dryRun({ ...ALL_HIT, websiteSmoke: undefined }), packages)[0]?.cached, undefined); +}); + +test('an app with two suites gets a large job when the e2e of either is a MISS or unknown, and none when both are HITs', async () => { + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteSmoke: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteSmoke: undefined }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: undefined }, IMAGES), ['website']); + assert.deepEqual(await large(ALL_HIT, IMAGES), []); +}); + +test('an app with a suite gets a large job when its build or its suite’s e2e is a MISS, whatever the registry holds', async () => { + assert.deepEqual(await large(ALL_HIT, IMAGES), []); + assert.deepEqual(await large({ ...ALL_HIT, website: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: 'MISS' }, IMAGES), ['website']); +}); + +test('an app without a suite, built from the output, gets a large job only when its image is missing and its build a MISS', async () => { + // Image present: publish tags it, and its build is not needed. + assert.deepEqual(await large({ ...ALL_HIT, myApp: 'MISS' }, IMAGES), []); + const without = IMAGES.filter((i) => !i.includes('/my-app:')); + // Image missing, build a HIT: publish restores it from the trusted cache. + assert.deepEqual(await large(ALL_HIT, without), []); + // Image missing, build a MISS: its large job builds it into the trusted cache for publish. + assert.deepEqual(await large({ ...ALL_HIT, myApp: 'MISS' }, without), ['my-app']); +}); + +test('an app with a Dockerfile of its own and no suite never gets a large job; with a suite, as any app with one', async () => { + assert.deepEqual(await large({ ...ALL_HIT, solver: 'MISS' }, []).then((l) => l.filter((a) => a === 'solver')), []); + assert.deepEqual(await large({ ...ALL_HIT, workerE2e: 'MISS' }, IMAGES), ['worker']); + assert.deepEqual(await large({ ...ALL_HIT, worker: 'MISS' }, IMAGES), ['worker']); +}); + +test('a task the package does not define is no MISS that asks for a large job', async () => { + assert.deepEqual(await large({ ...ALL_HIT, nonexistent: 'MISS' }, IMAGES), []); +}); + +test('what the plan cannot find out counts as work: every task unknown gives each app whose job’s tasks are needed its job', async () => { + // No cache field anywhere: all unknown. my-app's image is there, so its build is not needed; solver has no suite. + assert.deepEqual(await large({}, IMAGES), ['website', 'worker']); + assert.deepEqual(await large({}, []), ['website', 'my-app', 'worker']); +}); + +test('the outputs: the matrix of the large jobs is the apps with work, publish fans out over every app', async () => { + const io = fakeIo(checkout(), undefined, { crane: () => notThere('crane') }); + const result = await plan(new Context({}, io), '/repo', { + apps: Object.keys(packages), + hashes: hashesOf(dryRun({ ...ALL_HIT, website: 'MISS' }), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + const outputs = outputsOf(result); + assert.deepEqual( + JSON.parse(outputs.matrix).map((l: { app: string }) => l.app), + ['website'], + ); + assert.deepEqual( + JSON.parse(outputs.apps).map((l: { app: string }) => l.app), + ['website', 'my-app', 'solver', 'worker'], + ); + assert.equal(outputs.deploys, '[]'); + assert.equal(outputs.environment, ''); +}); + +/** A checkout's Io whose turbow answers as `turbow` says: its stdout, its stderr, or a failure. */ +function asking(tree: Tree, turbow: { out?: string; err: string; fails?: boolean }, npx: string = dryRun({})) { + const calls: { command: string; args: string[]; env?: NodeJS.ProcessEnv }[] = []; + const io = fakeIo(tree, undefined, { + mktemp: () => '/scratch/plx-ci-turbo', + chmod: () => '', + rm: (_cwd, args) => { + calls.push({ command: 'rm', args }); + return ''; + }, + sh: (_cwd, args, _input, env) => { + calls.push({ command: 'sh', args, env }); + // `sh -c 'exec ./turbow "$@" 2>"$0"' …`: turbow's stderr goes to the file. + const file = args[2] ?? ''; + const parts = file.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = turbow.err; + return turbow.fails ? undefined : turbow.out; + }, + npx: (_cwd, args) => { + calls.push({ command: 'npx', args }); + return npx; + }, + }); + return { ctx: new Context({}, io), calls }; +} + +const PLATFORM = { PLX_PLATFORM: 'linux-x64', PATH: '/usr/bin' }; + +test('readHashes asks the trusted cache through turbow, with the Turbo the lockfile has first on its PATH', async () => { + const { ctx, calls } = asking(checkout(), { + out: dryRun(ALL_HIT), + err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n', + }); + const read = await readHashes(ctx, '/repo', ['website', 'my-app'], PLATFORM); + assert.equal(read.why, ''); + assert.deepEqual(read.hashes[0]?.cached, { build: true, e2e: true }); + const [sh] = calls; + assert.deepEqual(sh?.args, [ + '-c', + 'exec ./turbow "$@" 2>"$0"', + '/scratch/plx-ci-turbo/turbow.err', + 'trusted', + 'run', + 'build', + 'e2e', + '--dry-run=json', + ]); + assert.equal(sh?.env?.PATH, '/scratch/plx-ci-turbo:/usr/bin'); + assert.equal(calls.filter((c) => c.command !== 'rm').length, 1, 'no second dry run'); +}); + +test('a plan that cannot ask the cache says why in one line and leaves every status unknown', async () => { + const cases: [string, Tree, Parameters[1], RegExp][] = [ + [ + 'a tenant without the bucket', + checkout(), + { out: dryRun({ website: 'MISS' }), err: 'turbow: without a remote cache: the tenant has no trusted bucket\n' }, + /^the tenant has no trusted bucket$/, + ], + [ + 'a job without the step', + checkout(), + { + fails: true, + err: 'turbow: in a job of the forge, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one\n', + }, + /this job started none/, + ], + [ + 'a dry run without cache fields', + checkout(), + { out: dryRun({}), err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n' }, + /^Turbo’s dry run \(turbo@2\.11\.13\) gave no cache status for @acme\/website#build$/, + ], + [ + 'a server that does not answer', + checkout(), + { + out: dryRun({ + website: 'MISS', + websiteE2e: 'MISS', + myApp: 'MISS', + solver: 'MISS', + worker: 'MISS', + workerE2e: 'MISS', + }), + // What Turbo 2.11.13 writes when the named server does not answer; every status is then a MISS. + err: [ + 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web', + ' WARNING • Remote caching unavailable (Could not connect to "http://127.0.0.1:8586")', + ' WARNING Remote artifact cache is temporarily unavailable; retrying after a 30-second cooldown', + '', + ].join('\n'), + }, + /^Remote caching unavailable \(Could not connect to "http:\/\/127\.0\.0\.1:8586"\)$/, + ], + [ + 'a turbow that fails with words of its own', + checkout(), + { fails: true, err: 'something went wrong first\nboom: the end of it\n' }, + /^turbow failed: boom: the end of it$/, + ], + [ + 'a checkout without turbow', + checkout(false), + { err: '' }, + /^the checkout has no turbow to name the trusted cache with$/, + ], + ]; + for (const [name, tree, turbow, why] of cases) { + const { ctx } = asking(tree, turbow); + const read = await readHashes(ctx, '/repo', ['website'], PLATFORM); + assert.match(read.why, why, name); + assert.equal(read.hashes[0]?.cached, undefined, name); + assert.equal(read.hashes[0]?.hash, '0f2a', name); + } +}); + +test('the plan says what it asked and which apps get a large job', async () => { + const io = fakeIo(checkout(), undefined, { + crane: (_cwd, args) => (IMAGES.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane')), + }); + const ctx = new Context({}, io); + await plan(ctx, '/repo', { + apps: ['website', 'my-app'], + hashes: hashesOf(dryRun({ ...ALL_HIT, websiteE2e: 'MISS' }), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + assert.equal( + narrated(ctx), + [ + 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', + 'website: in the trusted cache, build HIT, e2e/website MISS, e2e/website-smoke HIT (a MISS: not found, or not answered); a large job', + 'my-app: ghcr.io/acme/my-app:build-c51b exists; publish tags it', + 'my-app: in the trusted cache, build HIT; no large job', + '', + ].join('\n'), + ); +}); + +test('the turbo turbow runs is the lockfile’s, and its directory is removed whatever the dry run ended in', async () => { + const cases: [string, Parameters[1]][] = [ + [ + 'asked', + { out: dryRun(ALL_HIT), err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n' }, + ], + [ + 'a server that does not answer', + { + out: dryRun({}), + err: ' WARNING • Remote caching unavailable (Could not connect to "http://127.0.0.1:8586")\n', + }, + ], + ['a failing turbow', { fails: true, err: 'boom\n' }], + ]; + for (const [name, turbow] of cases) { + const tree = checkout(); + const { ctx, calls } = asking(tree, turbow); + await readHashes(ctx, '/repo', ['website'], PLATFORM); + const shim = ((tree.scratch as Tree)['plx-ci-turbo'] as Tree).turbo; + assert.equal(shim, '#!/bin/sh\nexec npx --yes turbo@2.11.13 "$@"\n', name); + assert.deepEqual(calls.at(-1), { command: 'rm', args: ['-rf', '/scratch/plx-ci-turbo'] }, name); + } +}); diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index 07bba66f..9e34c06f 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -1,99 +1,231 @@ import assert from 'node:assert/strict'; +import { tmpdir } from 'node:os'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; +import { REPO } from '../testing/checkout.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; import { publish } from './publish.ts'; -const own = { kind: 'own' } as const; +const SHA = 'deadbeef'; +const KEY = 'the-apps-key'; -test('a publish copies the tested manifest when the forge’s registry lacks it, and only tags when it is there', async () => { - const calls: string[][] = []; - const io = (there: boolean) => - fakeIo({}, undefined, { - crane: (_cwd, args) => { - calls.push(args); - if (args[0] === 'digest') return there ? 'sha256:abc' : notThere('crane'); - return ''; - }, - curl: (_cwd, args) => (args.at(-1)?.includes(':5000/') ? '' : notThere('curl')), - }); - const options = { - app: 'my-app', - build: 'b1', - test: 't1', - sha: 'deadbeef', - prefix: 'ghcr.io/acme', - registry: own, +/** A command a publish ran: its name, arguments, directory, and the environment it was given beyond the process's. */ +interface Call { + command: string; + args: string[]; + cwd: string; + env?: NodeJS.ProcessEnv; +} + +/** + * The checkout of REPO with the build outputs `outputs` (app → the BUILD_ID a + * restore leaves), and a forge registry holding `holds`; every command is + * recorded. `docker buildx build` writes the digest to its metadata file, as + * BuildKit does; `docker buildx inspect` finds no builder unless `builders` + * names it. + */ +function world(options: { holds?: string[]; outputs?: Record; builders?: string[] } = {}) { + const tree = structuredClone(REPO); + const calls: Call[] = []; + const record = + (command: string, answer: (args: string[]) => string | undefined = () => '') => + (cwd: string, args: string[], _input?: string, env?: NodeJS.ProcessEnv) => { + calls.push({ command, args, cwd, ...(env ? { env } : {}) }); + return answer(args); + }; + const put = (path: string, content: string) => { + const parts = path.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = content; }; + const io = fakeIo(tree, undefined, { + crane: record('crane', (args) => + args[0] !== 'digest' ? '' : (options.holds ?? []).includes(args[1] ?? '') ? 'sha256:there' : notThere(), + ), + mise: record('mise', (args) => { + // `mise run build `: the restore leaves the output and its BUILD_ID. + const app = args[2] ?? ''; + const id = options.outputs?.[app]; + if (id !== undefined) put(`/repo/apps/${app}/.next/standalone/apps/${app}/.next/BUILD_ID`, id); + return ''; + }), + docker: record('docker', (args) => { + if (args[1] === 'inspect') return (options.builders ?? []).includes(args[2] ?? '') ? '' : undefined; + const metadata = args[args.indexOf('--metadata-file') + 1]; + if (args[1] === 'build' && metadata) put(metadata, JSON.stringify({ 'containerimage.digest': 'sha256:built' })); + return ''; + }), + npx: record('npx'), + rm: record('rm'), + cp: record('cp'), + mkdir: record('mkdir'), + }); + return { ctx: new Context({}, io), calls }; +} + +const options = { + hash: '0f2a', + sha: SHA, + prefix: 'ghcr.io/Acme', + dir: '/repo', + encryptionKey: KEY, +}; + +const buildOf = (calls: Call[]) => calls.find((c) => c.command === 'docker' && c.args[1] === 'build'); - const copied = await publish(new Context({}, io(false)), options); - assert.equal(copied.copied, true); - assert.deepEqual(copied.tags, ['build-b1', 'deadbeef', 'test-t1']); +test('an image the forge’s registry holds gets the commit’s tag, and nothing is built or restored', async () => { + const { ctx, calls } = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); + const result = await publish(ctx, { ...options, app: 'website', context: 'output' }); + assert.deepEqual(result, { + app: 'website', + image: 'ghcr.io/acme/website', + built: false, + tags: ['build-0f2a', SHA], + }); assert.deepEqual( - calls.filter((c) => c[0] !== 'digest'), + calls.map((c) => [c.command, ...c.args]), [ - ['copy', '--insecure', 'localhost:5000/my-app:test-t1', 'ghcr.io/acme/my-app:build-b1'], - ['tag', 'ghcr.io/acme/my-app:build-b1', 'deadbeef'], - ['tag', 'ghcr.io/acme/my-app:build-b1', 'test-t1'], + ['crane', 'digest', 'ghcr.io/acme/website:build-0f2a'], + ['crane', 'tag', 'ghcr.io/acme/website:build-0f2a', SHA], ], ); +}); - calls.length = 0; - const tagged = await publish(new Context({}, io(true)), { ...options, test: undefined }); - assert.equal(tagged.copied, false); +test('a missing image of an app from app-nextjs: a fresh restore of its output through the verb, copied into the image', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + const result = await publish(ctx, { ...options, app: 'website', context: 'output' }); + assert.equal(result.built, true); + assert.equal(result.digest, 'sha256:built'); + assert.deepEqual(result.tags, ['build-0f2a', SHA]); + // The output is removed, restored by the verb, then built from; the scratch directory of the build goes after it. + const order = calls.filter((c) => c.command !== 'crane').map((c) => `${c.command} ${c.args.join(' ')}`); + const at = (line: RegExp) => order.findIndex((o) => line.test(o)); + assert.ok(at(/^rm -rf \/repo\/apps\/website\/\.next\/standalone$/) === 0, order.join('\n')); + assert.ok(at(/^mise run build website$/) === 1, order.join('\n')); + assert.ok(at(/^docker buildx build /) > 1, order.join('\n')); + assert.ok(order.at(-1)?.startsWith(`rm -rf ${tmpdir()}/plx-ci-build-`), order.at(-1)); + // The repo's own verb, in the checkout, with the key a build that misses the cache needs. + const restore = calls.find((c) => c.command === 'mise'); + assert.deepEqual(restore?.args, ['run', 'build', 'website']); + assert.equal(restore?.cwd, '/repo'); + assert.equal(restore?.env?.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + const build = buildOf(calls); + assert.deepEqual(build?.args.slice(0, 7), [ + 'buildx', + 'build', + '/repo/apps/website/.next/standalone', + '--file', + '/repo/apps/website/docker/Dockerfile', + '--platform', + 'linux/amd64', + ]); + const args = build?.args.join(' ') ?? ''; + assert.match(args, /--build-arg APP=website/); + assert.match(args, /--tag ghcr\.io\/acme\/website:build-0f2a --tag ghcr\.io\/acme\/website:deadbeef/); + // No rewrite-timestamp: the runner's Docker of the forge refuses it beside the unpack of its image store. + assert.match(args, /--output type=image,push=true,oci-mediatypes=true /); + assert.doesNotMatch(args, /rewrite-timestamp/); + assert.match(args, /--provenance=false --sbom=false/); + // No layer cache, no key and no package token: the build output holds what the image runs. + assert.doesNotMatch(args, /--cache-from|--cache-to|:cache|--secret|BUILD_HASH/); + // Without BUILDKIT_HOST, as under github, the runner's own Docker builds: no builder is made. + assert.doesNotMatch(args, /--builder/); + assert.ok(!calls.some((c) => c.command === 'docker' && c.args[1] === 'create')); + assert.equal(build?.env?.SOURCE_DATE_EPOCH, '0'); +}); + +test('with BUILDKIT_HOST, as a slot of a runner host has it, the image is built by that BuildKit service', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + await publish(ctx, { ...options, app: 'website', context: 'output', buildkit: 'tcp://127.0.0.1:4321' }); assert.deepEqual( - calls.filter((c) => c[0] !== 'digest'), - [['tag', 'ghcr.io/acme/my-app:build-b1', 'deadbeef']], + calls.filter((c) => c.command === 'docker' && c.args[1] !== 'build').map((c) => c.args), + [ + ['buildx', 'inspect', 'plexus-buildkit'], + ['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:4321'], + ], ); + assert.match(buildOf(calls)?.args.join(' ') ?? '', /--builder plexus-buildkit/); + // A builder of the name made by an earlier publish on the machine is used as it is. + const again = world({ outputs: { website: '0f2a' }, builders: ['plexus-buildkit'] }); + await publish(again.ctx, { ...options, app: 'website', context: 'output', buildkit: 'tcp://127.0.0.1:4321' }); + assert.ok(!again.calls.some((c) => c.args[1] === 'create')); }); -test('a publish without the tested tag in the sidecar is an error', async () => { - const io = fakeIo({}, undefined, { - crane: (_cwd, args) => (args[0] === 'digest' ? notThere('crane') : ''), - curl: () => notThere('curl'), - }); +test('publish builds from the context the plan gave it and reads no marker', async () => { + // website's marker lists app-nextjs; told `pruned`, publish prunes. + const { ctx, calls } = world(); + await publish(ctx, { ...options, app: 'website', context: 'pruned' }); + assert.ok(calls.some((c) => c.command === 'npx' && c.args.includes('prune'))); + assert.ok(!calls.some((c) => c.command === 'mise')); +}); + +test('an output whose BUILD_ID is not the plan’s hash is not published under it', async () => { + const { ctx, calls } = world({ outputs: { website: '9999' } }); await assert.rejects( - publish(new Context({}, io), { app: 'a', build: 'b', test: 't', sha: 's', prefix: 'ghcr.io/o', registry: own }), - /a:test-t is in no registry here; the tests did not pass/, + publish(ctx, { ...options, app: 'website', context: 'output' }), + /apps\/website\/\.next\/standalone holds the build 9999, not 0f2a/, ); + assert.equal(buildOf(calls), undefined); }); -test('where the candidates live in the forge’s registry, the tested manifest only gets the commit’s tag', async () => { - const calls: string[][] = []; - const io = (tested: boolean) => - fakeIo({}, undefined, { - crane: (_cwd, args) => { - calls.push(args); - if (args[0] === 'digest') return tested ? 'sha256:abc' : notThere('crane'); - return ''; - }, - }); - const options = { - app: 'website', - build: 'b1', - test: 't1', - sha: 'deadbeef', - prefix: 'ghcr.io/plexus-ms-tenant', - registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' } as const, - }; - const result = await publish(new Context({}, io(true)), options); - assert.equal(result.copied, false); - assert.deepEqual(result.tags, ['build-b1', 'test-t1', 'deadbeef']); - assert.deepEqual(calls, [ - ['digest', 'ghcr.io/plexus-ms-tenant/website:test-t1'], - ['tag', 'ghcr.io/plexus-ms-tenant/website:test-t1', 'deadbeef'], - ]); - await assert.rejects(publish(new Context({}, io(false)), options), /website:test-t1 is in no registry here/); +test('an output without BUILD_ID under apps/ is not published: the Dockerfile would start nothing', async () => { + const { ctx, calls } = world({ outputs: {} }); + await assert.rejects( + publish(ctx, { ...options, app: 'website', context: 'output' }), + /no apps\/website\/\.next\/BUILD_ID/, + ); + assert.equal(buildOf(calls), undefined); }); -test('a dry run publishes where crane is missing, on a placeholder', async () => { - const io = fakeIo({}, undefined, { - crane: () => { - throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); - }, +test('a missing image of an app with a Dockerfile of its own is built from its pruned context, by the lockfile’s Turbo', async () => { + const { ctx, calls } = world(); + const result = await publish(ctx, { + ...options, + app: 'solver', + hash: '9e1d', + context: 'pruned', + npmrc: '/run/npmrc', }); - const options = { app: 'website', build: 'b1', test: 't1', sha: 'deadbeef', prefix: 'ghcr.io/o' }; - const dry = new Context({ dryRun: true }, io); - assert.equal((await publish(dry, { ...options, registry: { kind: 'ghcr', prefix: 'ghcr.io/o' } })).copied, false); - assert.equal((await publish(dry, { ...options, registry: own })).copied, true); + assert.equal(result.built, true); + assert.ok(!calls.some((c) => c.command === 'mise'), 'no restore of a build output'); + const prune = calls.find((c) => c.command === 'npx'); + assert.deepEqual(prune?.args.slice(0, 5), ['--yes', 'turbo@2.11.13', 'prune', '@acme/solver', '--docker']); + const out = prune?.args.at(-1) ?? ''; + const build = buildOf(calls); + assert.equal(build?.args[2], `${out}/full`); + assert.deepEqual(build?.args.slice(3, 5), ['--file', `${out}/full/apps/solver/docker/Dockerfile`]); + const args = build?.args.join(' ') ?? ''; + assert.match(args, /--build-arg APP=solver --build-arg BUILD_HASH=9e1d/); + assert.match(args, /--secret id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY/); + assert.match(args, /--secret id=npmrc,src=\/run\/npmrc/); + assert.match(args, /--tag ghcr\.io\/acme\/solver:build-9e1d --tag ghcr\.io\/acme\/solver:deadbeef/); + assert.doesNotMatch(args, /--cache-from|--cache-to|:cache/); + assert.equal(build?.env?.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + // The key reaches the build as a secret from the environment, never as a build argument or on the command line. + assert.ok(!build?.args.some((a) => a.includes(KEY)), args); + assert.deepEqual( + build?.args.filter((a, i) => build.args[i - 1] === '--build-arg'), + ['APP=solver', 'BUILD_HASH=9e1d'], + ); + // The pruned context goes after the build. + assert.deepEqual(calls.at(-1)?.args, ['-rf', out]); +}); + +test('a publish that would build refuses without the app’s key; one that only tags needs none', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + await assert.rejects( + publish(ctx, { ...options, app: 'website', context: 'output', encryptionKey: '' }), + /NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty/, + ); + assert.ok(!calls.some((c) => c.command !== 'crane')); + const there = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); + assert.equal( + (await publish(there.ctx, { ...options, app: 'website', context: 'output', encryptionKey: '' })).built, + false, + ); }); diff --git a/packages/cli-ci/src/core/publish.ts b/packages/cli-ci/src/core/publish.ts index daa0bab3..aa4396f6 100644 --- a/packages/cli-ci/src/core/publish.ts +++ b/packages/cli-ci/src/core/publish.ts @@ -1,60 +1,60 @@ -// Publish one app's tested image under its commit, to the registry -// production pulls from (§ 8 PLX-Delivery). With a registry of the tenant's -// own: copy the manifest, by digest and without an index, from the sidecar to -// the forge's registry as build-, then tag it test- and ; or, -// when it is there already (a promotion, a re-run), only add the tags. Where -// the candidates live in the forge's registry itself, nothing is copied: the -// tested manifest gets the tag . Either way the tag test- is the -// proof the tests passed, and an image without it is not published. crane -// does the copying and tagging, logged in to the forge's registry by the job. +// Publish one app's image under its commit in the forge's registry, the one +// production pulls from (§ 4 PLX-Delivery). Where the registry holds +// `build-` already, the image built for the same content by an earlier +// run, a promotion's among them, gets the commit's tag and nothing is built +// (crane, logged in to the registry by the job). Where it lacks it, the image +// is built and pushed under both tags (build.ts says how). The registry is +// the one place that says whether an image exists; publish records nothing +// else, and that the image was tested is the order of the jobs: a run's +// publish of an app follows that run's test and e2e jobs. import type { Context } from '@plexus-ms/lib'; import { run } from '@plexus-ms/lib'; -import { craneDigest, findTag, imageName, type Registry } from './registry.ts'; +import { build } from './build.ts'; +import type { ImageContext } from './plan.ts'; +import { craneDigest, imageName } from './registry.ts'; export interface PublishOptions { app: string; /** Turbo's hash of the app's build task. */ - build: string; - /** Turbo's hash of the app's test task when it has one; the tag the image is read from, proof the tests passed. */ - test?: string; + hash: string; + /** The commit, the tag a deploy takes. */ sha: string; /** Where the published images live, `ghcr.io/`; lower-cased, as registries want. */ prefix: string; - /** Where the candidates live. */ - registry: Registry; + /** The checkout. */ + dir: string; + /** What the image is made from, as the plan says (plan.ts's imageContextOf). */ + context: ImageContext; + /** The app's server-actions key, which a build needs and a tag does not. */ + encryptionKey: string; + /** A user-level npmrc with the token of the tenant's private package registry. */ + npmrc?: string; + /** The BuildKit service to build through, `tcp://
:`; without it the runner's Docker. */ + buildkit?: string; } export interface Published { app: string; image: string; - /** Whether the manifest was copied, or found there already. */ - copied: boolean; + /** Whether the image was built here, or found under build-. */ + built: boolean; tags: string[]; + digest?: string; } export async function publish(ctx: Context, options: PublishOptions): Promise { - const { app, build, test, sha, registry } = options; + const { app, hash, sha } = options; const image = imageName(options.prefix, app); - const target = `${image}:build-${build}`; - const source = test ? `test-${test}` : `build-${build}`; - const missing = `${app}:${source} is in no registry here; ${test ? 'the tests did not pass on this build' : 'the build never ran'}`; - - if (registry.kind === 'ghcr') { - const ref = `${image}:${source}`; - if ((await craneDigest(ctx, ref)) === undefined && !ctx.dryRun) throw new Error(missing); - ctx.say(`publish: ${ref} as ${sha}`); - await ctx.apply([run('crane', ['tag', ref, sha])]); - return { app, image, copied: false, tags: [`build-${build}`, ...(test ? [`test-${test}`] : []), sha] }; + const target = `${image}:build-${hash}`; + if ((await craneDigest(ctx, target)) !== undefined) { + ctx.say(`publish: ${target} is there already, tagging it ${sha}`); + await ctx.apply([run('crane', ['tag', target, sha])]); + return { app, image, built: false, tags: [`build-${hash}`, sha] }; } - - const copied = (await craneDigest(ctx, target)) === undefined; - if (copied) { - const from = await findTag(ctx, registry, app, source); - if (from === undefined && !ctx.dryRun) throw new Error(missing); - ctx.say(`publish: ${app}:${source} -> ${target}`); - await ctx.apply([run('crane', ['copy', '--insecure', from ?? `localhost:5000/${app}:${source}`, target])]); - } else ctx.say(`publish: ${target} is there already, tagging only`); - const tags = [sha, ...(test ? [`test-${test}`] : [])]; - await ctx.apply(tags.map((t) => run('crane', ['tag', target, t]))); - return { app, image, copied, tags: [`build-${build}`, ...tags] }; + const { context } = options; + ctx.say( + `publish: ${target} is missing, building it from ${context === 'output' ? 'the build output' : 'a pruned context'}`, + ); + const built = await build(ctx, { ...options, image }); + return { app, image, built: true, tags: built.tags, ...(built.digest ? { digest: built.digest } : {}) }; } diff --git a/packages/cli-ci/src/core/registry.test.ts b/packages/cli-ci/src/core/registry.test.ts index 4d8ebc67..76d966ab 100644 --- a/packages/cli-ci/src/core/registry.test.ts +++ b/packages/cli-ci/src/core/registry.test.ts @@ -2,79 +2,18 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context, ExecError } from '@plexus-ms/lib'; import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { - candidateRef, - digestOf, - findTag, - imageName, - layersOf, - loggedIn, - registryOf, - rotateBuckets, - startSidecars, -} from './registry.ts'; +import { craneDigest, imageName } from './registry.ts'; -const november = new Date('2026-11-06T12:00:00Z'); - -test('where :5000 answers already, nothing is started and no key is needed', async () => { - const commands: string[] = []; - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => { - commands.push(`curl ${args.at(-1)}`); - return args.at(-1)?.includes(':5000/') ? '{}' : undefined; - }, - docker: () => { - commands.push('docker'); - return ''; - }, - exo: () => { - commands.push('exo'); - return ''; - }, - }); - const sidecars = await startSidecars(new Context({}, io), undefined, 'acme', november); - assert.deepEqual(sidecars, { - current: 'acme-ci-registry-2026-w45', - previous: 'acme-ci-registry-2026-w44', - previousAnswers: false, - }); - assert.deepEqual(commands, ['curl http://127.0.0.1:5000/v2/', 'curl http://127.0.0.1:5001/v2/']); -}); - -test('where nothing answers, the key is needed', async () => { - const io = fakeIo({}, undefined, { curl: () => undefined }); - await assert.rejects( - startSidecars(new Context({}, io), undefined, 'acme', november), - /REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed/, - ); +test('an image name is the prefix, lower-cased, and the app', () => { + assert.equal(imageName('ghcr.io/Plexus-MS-Tenant/', 'website'), 'ghcr.io/plexus-ms-tenant/website'); }); -test('the image name is the lower-cased prefix and the app', () => { - assert.equal(imageName('ghcr.io/Acme/', 'website'), 'ghcr.io/acme/website'); -}); - -test('a candidate is written to this week’s sidecar, or to the forge’s registry', () => { - assert.equal(candidateRef(registryOf('own', ''), 'website', 'build-0f2a'), 'localhost:5000/website:build-0f2a'); - assert.equal( - candidateRef(registryOf('ghcr', 'ghcr.io/Plexus-MS-Tenant'), 'website', 'build-0f2a'), - 'ghcr.io/plexus-ms-tenant/website:build-0f2a', - ); -}); - -test('findTag answers with the ref that holds the tag: either sidecar, or the forge’s registry through crane', async () => { - const previous = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.includes(':5001/') ? '' : notThere('curl')), - }); - assert.equal( - await findTag(new Context({}, previous), { kind: 'own' }, 'website', 'build-x'), - 'localhost:5001/website:build-x', - ); - const ghcr = fakeIo({}, undefined, { - crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a' : notThere('crane')), +test('craneDigest answers the digest, or undefined where the registry holds no such manifest', async () => { + const io = fakeIo({}, undefined, { + crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a\n' : notThere()), }); - const registry = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; - assert.equal(await findTag(new Context({}, ghcr), registry, 'website', 'build-x'), 'ghcr.io/o/website:build-x'); - assert.equal(await findTag(new Context({}, ghcr), registry, 'website', 'build-y'), undefined); + assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-x'), 'sha256:a'); + assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-y'), undefined); }); test('crane that cannot run is an error, never a missing tag', async () => { @@ -83,13 +22,10 @@ test('crane that cannot run is an error, never a missing tag', async () => { throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); }, }); - const registry = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; - await assert.rejects(findTag(new Context({}, missing), registry, 'website', 'build-x'), /crane could not run/); - await assert.rejects(layersOf(new Context({}, missing), registry, 'website', 'build-x'), /crane could not run/); + await assert.rejects(craneDigest(new Context({}, missing), 'ghcr.io/o/website:build-x'), /crane could not run/); }); -test('only the registry’s “not there” is a missing tag; a refused login or a silent sidecar is an error', async () => { - const ghcr = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; +test('only the registry’s “not there” is a missing tag; a refused login is an error', async () => { const refused = fakeIo({}, undefined, { crane: () => { throw new ExecError( @@ -100,27 +36,9 @@ test('only the registry’s “not there” is a missing tag; a refused login or }, }); await assert.rejects( - findTag(new Context({}, refused), ghcr, 'website', 'build-x'), + craneDigest(new Context({}, refused), 'ghcr.io/o/website:build-x'), /could not look up ghcr.io\/o\/website:build-x: .*UNAUTHORIZED/s, ); - - const down = (port: string) => - fakeIo({}, undefined, { - curl: (_cwd, args) => { - if (args.at(-1)?.includes(`:${port}/`)) throw new ExecError('curl', 7, 'curl: (7) Failed to connect\n'); - return notThere('curl'); - }, - }); - await assert.rejects( - findTag(new Context({}, down('5000')), { kind: 'own' }, 'website', 'build-x'), - /could not look up localhost:5000\/website:build-x/, - ); - await assert.rejects( - digestOf(new Context({}, down('5000')), { kind: 'own' }, 'website', 'build-x'), - /Failed to connect/, - ); - // Last week's sidecar is optional: its silence is absence. - assert.equal(await findTag(new Context({}, down('5001')), { kind: 'own' }, 'website', 'build-x'), undefined); }); test('under --dry-run a look-up that cannot be made is taken for absent, and said', async () => { @@ -128,90 +46,11 @@ test('under --dry-run a look-up that cannot be made is taken for absent, and sai crane: () => { throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); }, - curl: () => { - throw new ExecError('curl', 7, 'curl: (7) Failed to connect\n'); - }, }); let said = ''; io.stderr.on('data', (chunk: Buffer) => { said += chunk; }); - const dry = new Context({ dryRun: true }, io); - assert.equal(await findTag(dry, { kind: 'ghcr', prefix: 'ghcr.io/o' }, 'website', 'build-x'), undefined); - assert.equal(await findTag(dry, { kind: 'own' }, 'website', 'build-x'), undefined); + assert.equal(await craneDigest(new Context({ dryRun: true }, io), 'ghcr.io/o/website:build-x'), undefined); assert.match(said, /\[dry-run\] crane could not run to look up ghcr.io\/o\/website:build-x/); - assert.match(said, /\[dry-run\] could not look up localhost:5000\/website:build-x/); -}); - -test('a login is an entry for the host in the Docker config, or a credential store', async () => { - const env = { DOCKER_CONFIG: '/cfg' }; - const config = (data: unknown) => new Context({}, fakeIo({ cfg: { 'config.json': JSON.stringify(data) } })); - assert.equal(await loggedIn(config({ auths: { 'ghcr.io': { auth: 'x' } } }), 'ghcr.io', env), true); - assert.equal(await loggedIn(config({ credsStore: 'osxkeychain' }), 'ghcr.io', env), true); - assert.equal(await loggedIn(config({ auths: { 'docker.io': {} } }), 'ghcr.io', env), false); - assert.equal(await loggedIn(new Context({}, fakeIo({})), 'ghcr.io', env), false); -}); - -test('rotate creates this week’s bucket when it is missing and removes the one from two weeks ago, objects first', async () => { - const calls: string[] = []; - let objects = ['docker/registry/v2/a', 'docker/registry/v2/b&c']; - const io = fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const url = (input.match(/url = "([^"]+)"/)?.[1] ?? '').replace('https://s3.example', ''); - const method = /^head$/m.test(input) ? 'HEAD' : (input.match(/request = "(\w+)"/)?.[1] ?? ''); - calls.push(`${method} ${url}`); - assert.match(input, /aws-sigv4 = "aws:amz:r1:s3"/); - assert.match(input, /user = "k:s"/); - // 2026-w45 is missing, 2026-w43 is still there. - if (method === 'HEAD') return url.endsWith('2026-w43') ? '\n200' : '\n404'; - if (method === 'GET' && url.includes('list-type=2')) { - const xml = `${objects.map((k) => `${k.replace('&', '&')}`).join('')}`; - return `${xml}\n200`; - } - if (method === 'POST') { - assert.match(input, /docker\/registry\/v2\/b&c<\/Key>/); - assert.match(input, /Content-MD5: /); - objects = []; - return '\n200'; - } - if (method === 'GET' && url.includes('uploads=')) - return 'docker/x yu1\n200'; - return method === 'DELETE' ? '\n204' : '\n200'; - }, - }); - const storage = { endpoint: 'https://s3.example/', region: 'r1', accessKey: 'k', secretKey: 's' }; - const result = await rotateBuckets(new Context({}, io), storage, 'acme', november); - assert.deepEqual(result, { created: 'acme-ci-registry-2026-w45', removed: 'acme-ci-registry-2026-w43' }); - assert.deepEqual(calls, [ - 'HEAD /acme-ci-registry-2026-w45', - 'PUT /acme-ci-registry-2026-w45', - 'HEAD /acme-ci-registry-2026-w43', - 'GET /acme-ci-registry-2026-w43?list-type=2&max-keys=1000', - 'POST /acme-ci-registry-2026-w43?delete=', - 'GET /acme-ci-registry-2026-w43?list-type=2&max-keys=1000', - 'GET /acme-ci-registry-2026-w43?uploads=', - 'DELETE /acme-ci-registry-2026-w43/docker/x%20y?uploadId=u1', - 'DELETE /acme-ci-registry-2026-w43', - ]); -}); - -test('a dry run of rotate lists once and deletes nothing; an answer outside 2xx is an error', async () => { - const calls: string[] = []; - const io = (status: string) => - fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const method = /^head$/m.test(input) ? 'HEAD' : (input.match(/request = "(\w+)"/)?.[1] ?? ''); - calls.push(method); - if (method === 'HEAD') return '\n200'; - if (method === 'GET') return 'a\n200'; - return `no\n${status}`; - }, - }); - const storage = { endpoint: 'https://s3.example', region: 'r1', accessKey: 'k', secretKey: 's' }; - await rotateBuckets(new Context({ dryRun: true }, io('200')), storage, 'acme', november); - assert.deepEqual(calls, ['HEAD', 'HEAD', 'GET']); - await assert.rejects( - rotateBuckets(new Context({}, io('403')), storage, 'acme', november), - /deleting 1 objects of acme-ci-registry-2026-w43 answered 403/, - ); }); diff --git a/packages/cli-ci/src/core/registry.ts b/packages/cli-ci/src/core/registry.ts index 5f020a72..e48d6c17 100644 --- a/packages/cli-ci/src/core/registry.ts +++ b/packages/cli-ci/src/core/registry.ts @@ -1,328 +1,32 @@ -// Where a run's candidates live (§ 8 PLX-Delivery), behind one shape. `own` -// is the registry pair: `registry:2` on 127.0.0.1:5000 for this week's -// bucket, read-write, and on 127.0.0.1:5001 for the previous week's, -// read-only; both the same registry API over the tenant's object storage, -// nothing reads the bucket layout directly. A runner host keeps the pair -// running; a forge runner, a launched instance or a large slot starts it for -// the length of its job. In the first week the previous bucket does not -// exist and registry:2 answers 503 (its storage health check fails): that -// sidecar is optional, and a build names it as a cache source only when it -// answers 200. `ghcr` is the forge's registry itself, where the published -// images live too: nothing to start, the job logs in, and crane and docker -// reach it. +// What a verb asks the forge's registry (§ 4 PLX-Delivery), where the published +// images and the `build-` tags live: whether it holds a manifest, with +// crane, which the job has logged in to the registry. Nothing is started here. import type { Context } from '@plexus-ms/lib'; -import { ExecError, orAbsent, run } from '@plexus-ms/lib'; -import { sleep } from './exoscale.ts'; -import { type ObjectStorage, S3 } from './s3.ts'; -import type { RegistryKind } from './strategy.ts'; -import { registryBuckets } from './time.ts'; - -/** The registry the candidates of a run live in; `prefix` is where the images of the forge's registry live, `ghcr.io/`. */ -export type Registry = { kind: 'own' } | { kind: 'ghcr'; prefix: string }; +import { ExecError, orAbsent } from '@plexus-ms/lib'; export const imageName = (prefix: string, app: string): string => `${prefix.toLowerCase().replace(/\/$/, '')}/${app}`; -export function registryOf(kind: RegistryKind, prefix: string): Registry { - return kind === 'own' ? { kind } : { kind, prefix }; -} - -export type { ObjectStorage }; - -export const CURRENT_PORT = 5000; -export const PREVIOUS_PORT = 5001; -export const REGISTRY_IMAGE = 'registry:2'; -const ACCEPT = - 'application/vnd.oci.image.manifest.v1+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json'; - -/** The storage from the environment the vault item bucket-registry fills. */ -export function storageFromEnv(env: NodeJS.ProcessEnv = process.env): ObjectStorage | undefined { - const { REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY, REGISTRY_SECRET_KEY } = env; - if (!REGISTRY_ENDPOINT || !REGISTRY_REGION || !REGISTRY_ACCESS_KEY || !REGISTRY_SECRET_KEY) return undefined; - return { - endpoint: REGISTRY_ENDPOINT, - region: REGISTRY_REGION, - accessKey: REGISTRY_ACCESS_KEY, - secretKey: REGISTRY_SECRET_KEY, - }; -} - -/** The `docker run` of one sidecar; the key on argv is the same exposure as the job's own secrets. */ -export function sidecarArgs( - name: string, - port: number, - bucket: string, - storage: ObjectStorage, - readOnly: boolean, -): string[] { - return [ - 'run', - '-d', - '--name', - name, - '--restart', - readOnly ? 'on-failure:3' : 'unless-stopped', - '-p', - `127.0.0.1:${port}:5000`, - '-e', - 'REGISTRY_STORAGE=s3', - '-e', - `REGISTRY_STORAGE_S3_REGIONENDPOINT=${storage.endpoint}`, - '-e', - `REGISTRY_STORAGE_S3_REGION=${storage.region}`, - '-e', - `REGISTRY_STORAGE_S3_BUCKET=${bucket}`, - '-e', - `REGISTRY_STORAGE_S3_ACCESSKEY=${storage.accessKey}`, - '-e', - `REGISTRY_STORAGE_S3_SECRETKEY=${storage.secretKey}`, - '-e', - 'REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true', - '-e', - // registry:2 panics on the read-only flag as one nested variable - // (…_READONLY_ENABLED=true): the map it builds from it has the wrong - // type. The whole key as one YAML value is read as from a config file. - readOnly ? 'REGISTRY_STORAGE_MAINTENANCE_READONLY={"enabled":true}' : 'REGISTRY_STORAGE_DELETE_ENABLED=true', - REGISTRY_IMAGE, - ]; -} - -/** Whether a sidecar answers `/v2/`. */ -export async function answers(ctx: Context, port: number): Promise { - try { - await ctx.read('curl', ['-fsS', '--max-time', '3', `http://127.0.0.1:${port}/v2/`]); - return true; - } catch { - return false; - } -} - -export interface Sidecars { - current: string; - previous: string; - /** Whether the previous week's sidecar answers. */ - previousAnswers: boolean; -} - -/** - * Create this week's bucket when it does not exist yet (the ci-storage key - * may), start both sidecars, wait for the current one and briefly for the - * previous one. Where the current one answers already, the machine runs the - * pair for its jobs (a slot of a runner host, actions_runners, which keeps - * the pair on this week's buckets and gives the slot no Docker socket): - * nothing is started and no bucket is touched. - */ -export async function startSidecars( - ctx: Context, - storage: ObjectStorage | undefined, - owner: string, - now = new Date(), -): Promise { - const buckets = registryBuckets(owner, now); - if (!ctx.dryRun && (await answers(ctx, CURRENT_PORT))) { - const previousAnswers = await answers(ctx, PREVIOUS_PORT); - ctx.say(`registry: :${CURRENT_PORT} answers already, the host's pair; nothing started`); - return { current: buckets.current, previous: buckets.previous, previousAnswers }; - } - if (!storage) - throw new Error('REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed'); - const s3 = new S3(ctx, storage); - if (!(await s3.bucketExists(buckets.current))) { - ctx.say(`→ creating the bucket ${buckets.current}`); - await s3.makeBucket(buckets.current); - } - await ctx.apply([ - run('docker', sidecarArgs('registry', CURRENT_PORT, buckets.current, storage, false)), - run('docker', sidecarArgs('registry-previous', PREVIOUS_PORT, buckets.previous, storage, true)), - ]); - if (!ctx.dryRun) { - for (let i = 0; i < 30 && !(await answers(ctx, CURRENT_PORT)); i++) await sleep(1000); - for (let i = 0; i < 5 && !(await answers(ctx, PREVIOUS_PORT)); i++) await sleep(1000); - } - const previousAnswers = ctx.dryRun ? false : await answers(ctx, PREVIOUS_PORT); - ctx.say( - `registry: :${CURRENT_PORT} on ${buckets.current} (read-write), :${PREVIOUS_PORT} on ${buckets.previous} (${previousAnswers ? 'read-only' : 'not answering, bucket missing?'})`, - ); - return { current: buckets.current, previous: buckets.previous, previousAnswers }; -} - -/** curl's exit under --fail when the server answers 404: the one failure that means "not there". */ -export const curlNotFound = (error: ExecError): boolean => error.code === 22 && /\b404\b/.test(error.stderr); - /** crane's answer that the registry holds no such manifest, or no such repository. */ const craneNotFound = (error: ExecError): boolean => /MANIFEST_UNKNOWN|NAME_UNKNOWN|\b404\b/.test(error.stderr); /** - * One look-up of `ref`: the tool's output, or undefined when the registry - * says it holds no such thing (`absent` reads that off the failed command). - * Any other failure is an error: a tool that cannot run, a login the - * registry refuses or a sidecar that does not answer is the job's fault, and - * reporting it as a missing image sends the reader after a build that ran. + * The digest of `ref` on a registry crane is logged in to, or undefined when + * the registry says it holds no such manifest. Any other failure is an error: + * a crane that cannot run or a login the registry refuses is the job's fault, + * and reporting it as a missing image sends the reader after a build that ran. * Under --dry-run the failure is narrated and taken for absent, so a preview - * runs where there is no crane, no login or no sidecar. + * runs where there is no crane or no login. */ -async function lookUp( - ctx: Context, - ref: string, - command: string, - args: string[], - absent: (error: ExecError) => boolean, -): Promise { +export async function craneDigest(ctx: Context, ref: string): Promise { try { - return await orAbsent(ctx.read(command, args), absent); + return (await orAbsent(ctx.read('crane', ['digest', ref]), craneNotFound))?.trim() || undefined; } catch (error) { const why = error instanceof ExecError ? `could not look up ${ref}: ${error.message}` - : `${command} could not run to look up ${ref}; is it installed in this job?`; + : `crane could not run to look up ${ref}; is it installed in this job?`; if (!ctx.dryRun) throw new Error(why, { cause: error }); ctx.say(`[dry-run] ${why.split('\n')[0]}; taken for absent`); return undefined; } } - -const manifestUrl = (port: number, app: string, tag: string): string => - `http://127.0.0.1:${port}/v2/${app}/manifests/${tag}`; - -/** A manifest HEAD against one sidecar: its headers, or undefined where `absent` says so (a 404). */ -const head = (ctx: Context, port: number, app: string, tag: string, absent = curlNotFound) => - lookUp( - ctx, - `localhost:${port}/${app}:${tag}`, - 'curl', - ['-fsS', '-I', '-H', `Accept: ${ACCEPT}`, manifestUrl(port, app, tag)], - absent, - ); - -/** - * The port of the sidecar that holds `app:tag`, or undefined. This week's - * sidecar has to answer; the previous week's is optional (see the top), so - * any failure there is absence. - */ -export async function tagExists(ctx: Context, app: string, tag: string): Promise { - if ((await head(ctx, CURRENT_PORT, app, tag)) !== undefined) return CURRENT_PORT; - if ((await head(ctx, PREVIOUS_PORT, app, tag, () => true)) !== undefined) return PREVIOUS_PORT; - return undefined; -} - -/** The digest of `app:tag` on one sidecar, or undefined. */ -export async function digest(ctx: Context, app: string, tag: string, port = CURRENT_PORT): Promise { - return (await head(ctx, port, app, tag))?.match(/^docker-content-digest:\s*(\S+)/im)?.[1]; -} - -export interface Layer { - digest: string; - size: number; -} - -/** The layers of `app:tag`'s manifest on one sidecar, or undefined. */ -export async function layers( - ctx: Context, - app: string, - tag: string, - port = CURRENT_PORT, -): Promise { - const manifest = await lookUp( - ctx, - `localhost:${port}/${app}:${tag}`, - 'curl', - ['-fsS', '-H', `Accept: ${ACCEPT}`, manifestUrl(port, app, tag)], - curlNotFound, - ); - return manifest === undefined ? undefined : layersIn(manifest); -} - -const layersIn = (manifest: string): Layer[] => - ((JSON.parse(manifest) as { layers?: Layer[] }).layers ?? []).map((l) => ({ digest: l.digest, size: l.size })); - -/** Where a run writes `app:tag`: this week's sidecar, or the forge's registry. */ -export function candidateRef(registry: Registry, app: string, tag: string): string { - return registry.kind === 'own' - ? `localhost:${CURRENT_PORT}/${app}:${tag}` - : `${imageName(registry.prefix, app)}:${tag}`; -} - -/** The digest of `ref` on a registry crane is logged in to, or undefined when the registry holds no such manifest. */ -export async function craneDigest(ctx: Context, ref: string): Promise { - return (await lookUp(ctx, ref, 'crane', ['digest', ref], craneNotFound))?.trim() || undefined; -} - -/** The ref under which the registry holds `app:tag`, either sidecar's under `own`, or undefined. */ -export async function findTag(ctx: Context, registry: Registry, app: string, tag: string): Promise { - if (registry.kind === 'own') { - const port = await tagExists(ctx, app, tag); - return port === undefined ? undefined : `localhost:${port}/${app}:${tag}`; - } - const ref = candidateRef(registry, app, tag); - return (await craneDigest(ctx, ref)) === undefined ? undefined : ref; -} - -/** The digest of `app:tag` where a run writes, or undefined. */ -export function digestOf(ctx: Context, registry: Registry, app: string, tag: string): Promise { - return registry.kind === 'own' ? digest(ctx, app, tag) : craneDigest(ctx, candidateRef(registry, app, tag)); -} - -/** The layers of `app:tag` where a run writes, or undefined. */ -export async function layersOf( - ctx: Context, - registry: Registry, - app: string, - tag: string, -): Promise { - if (registry.kind === 'own') return layers(ctx, app, tag); - const ref = candidateRef(registry, app, tag); - const manifest = await lookUp(ctx, ref, 'crane', ['manifest', ref], craneNotFound); - return manifest === undefined ? undefined : layersIn(manifest); -} - -/** - * Whether this machine holds a login for the forge's registry: an entry in - * the Docker config crane and docker both read, or a credential store that - * answers for it. Read from the file, so that no secret passes through here. - */ -export async function loggedIn(ctx: Context, host: string, env: NodeJS.ProcessEnv = process.env): Promise { - const file = `${env.DOCKER_CONFIG || `${env.HOME}/.docker`}/config.json`; - try { - const config = JSON.parse(await ctx.readFile(file)) as { - auths?: Record; - credsStore?: string; - credHelpers?: Record; - }; - return Boolean(config.auths?.[host] || config.credHelpers?.[host] || config.credsStore); - } catch { - return false; - } -} - -export interface Rotation { - /** This week's bucket, when it had to be created. */ - created?: string; - /** The bucket from two weeks ago, when it was still there. */ - removed?: string; -} - -/** - * Retention by rotation: this week's bucket exists, the one from two weeks - * ago is deleted whole. Writes go to the current week, reads consult the - * current and the previous, so nothing reads what goes. - */ -export async function rotateBuckets( - ctx: Context, - storage: ObjectStorage, - owner: string, - now = new Date(), -): Promise { - const buckets = registryBuckets(owner, now); - const s3 = new S3(ctx, storage); - const result: Rotation = {}; - if (!(await s3.bucketExists(buckets.current))) { - ctx.say(`rotate: creating the bucket ${buckets.current}`); - await s3.makeBucket(buckets.current); - result.created = buckets.current; - } - if (await s3.bucketExists(buckets.expired)) { - ctx.say(`rotate: the registry bucket ${buckets.expired} is two weeks old`); - await s3.removeBucket(buckets.expired); - result.removed = buckets.expired; - } - return result; -} diff --git a/packages/cli-ci/src/core/s3.ts b/packages/cli-ci/src/core/s3.ts deleted file mode 100644 index 0913f02f..00000000 --- a/packages/cli-ci/src/core/s3.ts +++ /dev/null @@ -1,164 +0,0 @@ -// The registry's buckets, through the S3 API itself with curl (§ 8 -// PLX-Delivery): whether a bucket exists, creating it, and deleting it whole. -// Plain S3, signed by curl (`--aws-sigv4`), so that the store is any -// S3-compatible one and the job needs no provider's CLI; the runner host's -// own script (actions_runners, ci-registry-refresh) speaks to it the same way. -// Path-style addressing, as the registry is configured. The key goes to curl -// as a config on stdin, never on argv. -import { createHash } from 'node:crypto'; -import type { Context } from '@plexus-ms/lib'; -import { run } from '@plexus-ms/lib'; - -export interface ObjectStorage { - /** The S3 endpoint, `https://…`, without a bucket. */ - endpoint: string; - region: string; - accessKey: string; - secretKey: string; -} - -interface Call { - method: 'HEAD' | 'GET' | 'PUT' | 'POST' | 'DELETE'; - /** The path below the endpoint, `` or `/`, and its query. */ - path: string; - query?: string; - body?: string; - headers?: string[]; -} - -interface Answer { - status: number; - body: string; -} - -const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex'); -const md5 = (text: string): string => createHash('md5').update(text).digest('base64'); - -const unescapeXml = (text: string): string => - text - .replaceAll('<', '<') - .replaceAll('>', '>') - .replaceAll('"', '"') - .replaceAll(''', "'") - .replaceAll('&', '&'); -const escapeXml = (text: string): string => - text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); - -/** Every `…` of an S3 answer, unescaped. */ -export function elements(xml: string, tag: string): string[] { - return [...xml.matchAll(new RegExp(`<${tag}>([^<]*)`, 'g'))].map((m) => unescapeXml(m[1] ?? '')); -} - -/** The uploads a ListMultipartUploads answer names: a key and its upload id each. */ -export function uploads(xml: string): { key: string; id: string }[] { - return [...xml.matchAll(/(.*?)<\/Upload>/gs)].flatMap((m) => { - const key = elements(m[1] ?? '', 'Key')[0]; - const id = elements(m[1] ?? '', 'UploadId')[0]; - return key !== undefined && id !== undefined ? [{ key, id }] : []; - }); -} - -/** The body of a DeleteObjects call for up to a thousand keys. */ -export function deleteBody(keys: string[]): string { - return `true${keys.map((k) => `${escapeXml(k)}`).join('')}`; -} - -export class S3 { - readonly ctx: Context; - private readonly storage: ObjectStorage; - - constructor(ctx: Context, storage: ObjectStorage) { - this.ctx = ctx; - this.storage = storage; - } - - /** The curl config of one call: the URL, the signature's inputs, the body, and the status after the answer. */ - private config(call: Call): string { - const { endpoint, region, accessKey, secretKey } = this.storage; - const url = `${endpoint.replace(/\/$/, '')}/${call.path}${call.query ? `?${call.query}` : ''}`; - const body = call.body ?? ''; - const lines = [ - `url = ${JSON.stringify(url)}`, - call.method === 'HEAD' ? 'head' : `request = "${call.method}"`, - 'silent', - 'show-error', - 'max-time = 60', - `user = ${JSON.stringify(`${accessKey}:${secretKey}`)}`, - `aws-sigv4 = "aws:amz:${region}:s3"`, - // Stated, not left to curl: its versions differ in whether they send it, and S3 wants it signed. - `header = "x-amz-content-sha256: ${sha256(body)}"`, - ...(call.headers ?? []).map((h) => `header = ${JSON.stringify(h)}`), - ...(call.body === undefined ? [] : [`data-binary = ${JSON.stringify(body)}`]), - 'write-out = "\\n%{http_code}"', - ]; - return `${lines.join('\n')}\n`; - } - - private answer(out: string): Answer { - const at = out.lastIndexOf('\n'); - return { status: Number(out.slice(at + 1)), body: out.slice(0, at) }; - } - - private async read(call: Call): Promise { - return this.answer(await this.ctx.read('curl', ['-K', '-'], { input: this.config(call) })); - } - - /** An effect: its answer, or undefined under --dry-run. A status outside 2xx is an error. */ - private async effect(call: Call, what: string): Promise { - const out = await this.ctx.effect(run('curl', ['-K', '-'], { input: this.config(call) })); - if (out === undefined) return undefined; - const answer = this.answer(out); - if (answer.status < 200 || answer.status >= 300) - throw new Error(`${what} answered ${answer.status}: ${answer.body.slice(0, 300)}`); - return answer; - } - - async bucketExists(bucket: string): Promise { - const { status } = await this.read({ method: 'HEAD', path: bucket }); - if (status === 200) return true; - if (status === 404) return false; - throw new Error(`looking up the bucket ${bucket} answered ${status}`); - } - - async makeBucket(bucket: string): Promise { - await this.effect({ method: 'PUT', path: bucket }, `creating the bucket ${bucket}`); - } - - /** - * Delete a bucket whole: its objects a thousand at a time, the uploads - * something left unfinished, then the bucket, which S3 refuses while - * either remains. A dry run lists once and says what would go. - */ - async removeBucket(bucket: string): Promise { - let removed = 0; - for (;;) { - const page = await this.read({ method: 'GET', path: bucket, query: 'list-type=2&max-keys=1000' }); - if (page.status !== 200) throw new Error(`listing the bucket ${bucket} answered ${page.status}`); - const keys = elements(page.body, 'Key'); - if (keys.length === 0) break; - const body = deleteBody(keys); - const answer = await this.effect( - { method: 'POST', path: bucket, query: 'delete=', body, headers: [`Content-MD5: ${md5(body)}`] }, - `deleting ${keys.length} objects of ${bucket}`, - ); - if (answer === undefined) { - this.ctx.say(` (the objects of ${bucket}, ${keys.length} in the first listing, then the bucket)`); - return; - } - const failed = elements(answer.body, 'Message'); - if (answer.body.includes('')) - throw new Error(`deleting objects of ${bucket} failed: ${failed[0] ?? answer.body.slice(0, 300)}`); - removed += keys.length; - } - const pending = await this.read({ method: 'GET', path: bucket, query: 'uploads=' }); - for (const upload of pending.status === 200 ? uploads(pending.body) : []) { - const key = upload.key.split('/').map(encodeURIComponent).join('/'); - await this.effect( - { method: 'DELETE', path: `${bucket}/${key}`, query: `uploadId=${encodeURIComponent(upload.id)}` }, - `aborting an unfinished upload in ${bucket}`, - ); - } - await this.effect({ method: 'DELETE', path: bucket }, `deleting the bucket ${bucket}`); - this.ctx.say(`removed the bucket ${bucket} and its ${removed} object(s)`); - } -} diff --git a/packages/cli-ci/src/core/strategy.test.ts b/packages/cli-ci/src/core/strategy.test.ts index 24b8e6de..9443666f 100644 --- a/packages/cli-ci/src/core/strategy.test.ts +++ b/packages/cli-ci/src/core/strategy.test.ts @@ -2,12 +2,10 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { runnerOf, settingsOf } from './strategy.ts'; -test('the settings default to the forge’s runners and registry, and the registry follows the strategy', () => { - assert.deepEqual(settingsOf({}), { strategy: 'github', registry: 'ghcr', overlay: 'none' }); - assert.deepEqual(settingsOf({ CI_STRATEGY: 'hybrid' }), { strategy: 'hybrid', registry: 'own', overlay: 'none' }); - assert.deepEqual(settingsOf({ CI_STRATEGY: 'on-prem', CI_REGISTRY: 'ghcr', CI_OVERLAY: 'netbird' }), { +test('the settings default to the forge’s runners and no overlay', () => { + assert.deepEqual(settingsOf({}), { strategy: 'github', overlay: 'none' }); + assert.deepEqual(settingsOf({ CI_STRATEGY: 'on-prem', CI_OVERLAY: 'netbird' }), { strategy: 'on-prem', - registry: 'ghcr', overlay: 'netbird', }); assert.equal(settingsOf({ CI_STRATEGY: 'hybrid' }, 'github').strategy, 'github'); @@ -18,7 +16,6 @@ test('an answer outside its set is a usage error that names the set', () => { () => settingsOf({ CI_STRATEGY: 'cloud' }), /the strategy is "cloud"; it is one of github, on-prem, hybrid/, ); - assert.throws(() => settingsOf({ CI_REGISTRY: 'dockerhub' }), /CI_REGISTRY is "dockerhub"/); assert.throws(() => settingsOf({ CI_OVERLAY: 'tailscale' }), /CI_OVERLAY is "tailscale"/); }); diff --git a/packages/cli-ci/src/core/strategy.ts b/packages/cli-ci/src/core/strategy.ts index 856f0f2b..e2f1f9fc 100644 --- a/packages/cli-ci/src/core/strategy.ts +++ b/packages/cli-ci/src/core/strategy.ts @@ -1,25 +1,19 @@ -// The three answers a repo gives about its CI (§ 8 PLX-Delivery), read once: -// the strategy (where the jobs of each size run), the registry (where the -// candidates live) and the overlay (how a deploy reaches the hosts; the -// deploy mount acts on it, the commands only check it). The -// reusable workflows set them as CI_STRATEGY, CI_REGISTRY and CI_OVERLAY from -// their inputs; `--strategy` overrides the first by hand. Pure, so that the -// tests pin the defaults and the labels. +// The two answers a repo gives about its CI (§ 8 PLX-Delivery), read once: +// the strategy (where the jobs of each size run) and the overlay (how a +// deploy reaches the hosts; the deploy mount acts on it, the commands only +// check it). The reusable workflows set them as CI_STRATEGY and CI_OVERLAY +// from their inputs; `--strategy` overrides the first by hand. Pure, so that +// the tests pin the defaults and the labels. import { UsageError } from '@plexus-ms/lib'; export const STRATEGIES = ['github', 'on-prem', 'hybrid'] as const; export type Strategy = (typeof STRATEGIES)[number]; -export const REGISTRIES = ['ghcr', 'own'] as const; -/** `ghcr`: the candidates live beside the published images; `own`: in the registry pair on the tenant's object storage. */ -export type RegistryKind = (typeof REGISTRIES)[number]; - export const OVERLAYS = ['none', 'netbird'] as const; export type Overlay = (typeof OVERLAYS)[number]; export interface Settings { strategy: Strategy; - registry: RegistryKind; overlay: Overlay; } @@ -32,14 +26,12 @@ function oneOf(name: string, value: string, allowed: readonly /** * The settings from the environment, `flag` (--strategy) before CI_STRATEGY. * Without a strategy it is `github`, the forge's runners, where everything - * runs without a host or a cloud. The registry defaults from the strategy: - * `ghcr` under `github`, `own` otherwise. + * runs without a host or a cloud. */ export function settingsOf(env: NodeJS.ProcessEnv = process.env, flag?: string): Settings { const strategy = oneOf('the strategy', flag || env.CI_STRATEGY || 'github', STRATEGIES); - const registry = oneOf('CI_REGISTRY', env.CI_REGISTRY || (strategy === 'github' ? 'ghcr' : 'own'), REGISTRIES); const overlay = oneOf('CI_OVERLAY', env.CI_OVERLAY || 'none', OVERLAYS); - return { strategy, registry, overlay }; + return { strategy, overlay }; } export type Size = 'small' | 'medium' | 'large'; diff --git a/packages/cli-ci/src/core/test.test.ts b/packages/cli-ci/src/core/test.test.ts deleted file mode 100644 index 8a5a382c..00000000 --- a/packages/cli-ci/src/core/test.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { composeArgs, overrideEnv, specEnv } from './test.ts'; - -test('the override’s x-plexus-ci.env is the specs’ environment, beside the port and the base URL', () => { - const env = overrideEnv( - 'x-plexus-ci:\n env:\n DATABASE_URL: postgres://u:p@127.0.0.1:5432/db\nservices:\n db: {}\n', - ); - assert.deepEqual(env, { DATABASE_URL: 'postgres://u:p@127.0.0.1:5432/db' }); - assert.deepEqual(specEnv(3000, env), { - CI: '1', - PLEXUS_LOOPBACK_PORT: '3000', - E2E_BASE_URL: 'http://127.0.0.1:3000', - DATABASE_URL: 'postgres://u:p@127.0.0.1:5432/db', - }); - assert.deepEqual(overrideEnv('services: {}\n'), {}); - assert.throws(() => overrideEnv('x-plexus-ci:\n env: nope\n'), /not a map/); -}); - -test('every stack command names the project and both files', () => { - assert.deepEqual(composeArgs('ci-my-app'), [ - 'compose', - '--project-name', - 'ci-my-app', - '--file', - 'compose.yaml', - '--file', - 'compose.ci.yaml', - ]); -}); diff --git a/packages/cli-ci/src/core/test.ts b/packages/cli-ci/src/core/test.ts deleted file mode 100644 index cf8c177b..00000000 --- a/packages/cli-ci/src/core/test.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Test one app's candidate image (§ 8 PLX-Delivery): on a large runner, the -// app's own compose.yaml with the CI override beside it, the candidate -// pulled from the registry, `migrate` once, `up --wait`, then the -// app's test script against the running stack, and on success the tag -// test- on the very manifest that was tested. The specs run on the -// runner, outside the containers: the override's `x-plexus-ci.env` says how -// they reach the stack (the database's published port), beside what every -// app gets: CI, PLEXUS_LOOPBACK_PORT and E2E_BASE_URL, the app's loopback origin. -import { join } from 'node:path'; -import type { Context } from '@plexus-ms/lib'; -import { run, UsageError } from '@plexus-ms/lib'; -import { parse } from 'yaml'; -import { candidateRef, digestOf, findTag, type Registry } from './registry.ts'; - -export const OVERRIDE = 'compose.ci.yaml'; - -export interface TestOptions { - app: string; - /** Turbo's hash of the app's test task; the tag the tested image gets. */ - hash: string; - /** Turbo's hash of the app's build task; the candidate's tag. */ - build: string; - /** The port the stack publishes the app on; the override reads it as PLEXUS_LOOPBACK_PORT. */ - port?: number; - /** The checkout; default the cwd. */ - dir?: string; - /** Where the candidates live. */ - registry: Registry; -} - -export interface TestResult { - app: string; - hash: string; - image: string; - tag: string; - digest?: string; - /** Seconds the stack took to come up, and the tests to run. */ - stackSeconds: number; - testSeconds: number; -} - -/** What the override tells the runner side: `x-plexus-ci.env`, the specs' environment. */ -export function overrideEnv(text: string): Record { - // The override may carry compose's own tags (`!override`), which are not ours to resolve. - const data: unknown = parse(text, { logLevel: 'silent' }); - const x = data !== null && typeof data === 'object' ? (data as Record)['x-plexus-ci'] : undefined; - const env = x !== null && typeof x === 'object' ? (x as Record).env : undefined; - if (env === undefined) return {}; - if (env === null || typeof env !== 'object') throw new UsageError(`${OVERRIDE}: x-plexus-ci.env is not a map`); - return Object.fromEntries(Object.entries(env as Record).map(([k, v]) => [k, String(v)])); -} - -/** The `docker compose` prefix every stack command shares: the project, both files. */ -export function composeArgs(project: string): string[] { - return ['compose', '--project-name', project, '--file', 'compose.yaml', '--file', OVERRIDE]; -} - -/** The environment the specs run with. */ -export function specEnv(port: number, fromOverride: Record): NodeJS.ProcessEnv { - return { - CI: '1', - PLEXUS_LOOPBACK_PORT: String(port), - E2E_BASE_URL: `http://127.0.0.1:${port}`, - ...fromOverride, - }; -} - -export async function test(ctx: Context, options: TestOptions): Promise { - const { app, hash, build, registry } = options; - const dir = options.dir ?? '.'; - const port = options.port ?? 3000; - const appDir = join(dir, 'apps', app); - const composeDir = join(appDir, 'docker'); - const project = `ci-${app}`; - - const image = - (await findTag(ctx, registry, app, `build-${build}`)) ?? - (ctx.dryRun ? candidateRef(registry, app, `build-${build}`) : undefined); - if (image === undefined) - throw new Error(`${app}:build-${build} is in no registry here; the build failed or never ran`); - const tag = `test-${hash}`; - - const fromOverride = overrideEnv(await ctx.readFile(join(composeDir, OVERRIDE))); - const composeEnv = { PLEXUS_DEPLOYMENT_IMAGE: image, PLEXUS_LOOPBACK_PORT: String(port) }; - const compose = (args: string[]) => - run('docker', [...composeArgs(project), ...args], { cwd: composeDir, env: composeEnv }); - - let stackSeconds = 0; - let testSeconds = 0; - let t = Date.now(); - try { - ctx.say(`test: ${app} ${image} as ${project} on :${port}`); - await ctx.apply([ - compose(['--profile', 'migrate', 'pull', '--quiet']), - compose(['run', '--rm', '--quiet-pull', 'migrate']), - compose(['up', '--detach', '--wait', '--quiet-pull']), - ]); - stackSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`test: stack up ${stackSeconds}s`); - t = Date.now(); - // The specs' output is the job's log: inherited, not captured. - await ctx.apply([run('pnpm', ['test'], { cwd: appDir, env: specEnv(port, fromOverride), interactive: true })]); - testSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`test: tests ${testSeconds}s`); - } catch (error) { - if (!ctx.dryRun) { - const logs = await ctx - .read('docker', [...composeArgs(project), 'logs', '--no-color', '--tail', '200'], { - cwd: composeDir, - env: composeEnv, - }) - .catch(() => ''); - if (logs) ctx.say(`test: the stack's last lines\n${logs}`); - } - throw error; - } finally { - await ctx.apply([compose(['--profile', 'migrate', 'down', '--volumes', '--remove-orphans', '--timeout', '10'])]); - } - - // The tag goes on the manifest that was tested, copied into this week's - // registry when the candidate came from the previous one. - await ctx.apply([ - run('docker', ['buildx', 'imagetools', 'create', '--tag', candidateRef(registry, app, tag), image]), - ]); - const result: TestResult = { app, hash, image, tag, stackSeconds, testSeconds }; - if (!ctx.dryRun) { - result.digest = await digestOf(ctx, registry, app, tag); - ctx.say(`test: ${app} ${tag} -> ${result.digest ?? ''}`); - } - return result; -} diff --git a/packages/cli-ci/src/core/time.test.ts b/packages/cli-ci/src/core/time.test.ts index 62eb4823..1e23ab64 100644 --- a/packages/cli-ci/src/core/time.test.ts +++ b/packages/cli-ci/src/core/time.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { deadline, iso, registryBuckets, turboBucket, week } from './time.ts'; +import { deadline, iso } from './time.ts'; const now = new Date('2026-11-04T10:40:27.123Z'); @@ -12,27 +12,3 @@ test('a deadline is minutes from now, in UTC', () => { assert.equal(deadline(now, 5), '2026-11-04T10:45:27Z'); assert.equal(deadline(now, 30), '2026-11-04T11:10:27Z'); }); - -test('weeks are ISO weeks in UTC and roll over the year', () => { - assert.equal(week(now), '2026-w45'); - assert.equal(week(now, -1), '2026-w44'); - // Monday starts a week, Sunday ends it. - assert.equal(week(new Date('2026-11-08T23:59:59Z')), '2026-w45'); - assert.equal(week(new Date('2026-11-09T00:00:00Z')), '2026-w46'); - // A week belongs to the year of its Thursday: 2026 has 53 weeks, 2025 ends in the first week of 2026. - assert.equal(week(new Date('2027-01-03T12:00:00Z')), '2026-w53'); - assert.equal(week(new Date('2027-01-04T12:00:00Z')), '2027-w01'); - assert.equal(week(new Date('2027-01-04T12:00:00Z'), -1), '2026-w53'); - assert.equal(week(new Date('2027-01-04T12:00:00Z'), -2), '2026-w52'); - assert.equal(week(new Date('2025-12-29T00:00:00Z')), '2026-w01'); - assert.equal(week(new Date('2026-01-01T00:00:00Z'), -1), '2025-w52'); -}); - -test('the bucket names follow the convention', () => { - assert.deepEqual(registryBuckets('acme', now), { - current: 'acme-ci-registry-2026-w45', - previous: 'acme-ci-registry-2026-w44', - expired: 'acme-ci-registry-2026-w43', - }); - assert.equal(turboBucket('acme'), 'acme-ci-turbo'); -}); diff --git a/packages/cli-ci/src/core/time.ts b/packages/cli-ci/src/core/time.ts index e9e2b332..d73c533c 100644 --- a/packages/cli-ci/src/core/time.ts +++ b/packages/cli-ci/src/core/time.ts @@ -1,7 +1,5 @@ // The clock, in one place: deadlines as absolute UTC times (what the instance -// labels and the sweep compare), and the registry's week names (§ 8 -// PLX-Delivery: writes to this week's bucket, reads this and the previous, -// the one before is deleted whole). Pure, so that the tests pin the arithmetic. +// labels and the sweep compare). Pure, so that the tests pin the arithmetic. /** `2026-11-04T10:40:27Z`, the shape every label and log line uses. */ export function iso(at: Date): string { @@ -12,25 +10,3 @@ export function iso(at: Date): string { export function deadline(now: Date, minutes: number): string { return iso(new Date(now.getTime() + minutes * 60_000)); } - -/** - * `YYYY-wWW`, the ISO week `offset` weeks from `now`'s (0 this week, -1 the - * previous), in UTC: weeks start on Monday, and a week belongs to the year - * its Thursday is in, as `date +%G-w%V` prints it. - */ -export function week(now: Date, offset = 0): string { - const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + offset * 7)); - // To the Thursday of the week, whose year is the week's. - d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); - const days = (d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 1)) / 86_400_000; - return `${d.getUTCFullYear()}-w${String(Math.floor(days / 7) + 1).padStart(2, '0')}`; -} - -/** The registry bucket names of one owner: by convention `-ci-registry-`. */ -export function registryBuckets(owner: string, now: Date): { current: string; previous: string; expired: string } { - const name = (offset: number) => `${owner}-ci-registry-${week(now, offset)}`; - return { current: name(0), previous: name(-1), expired: name(-2) }; -} - -/** The Turbo cache bucket of one owner, `-ci-turbo`. */ -export const turboBucket = (owner: string): string => `${owner}-ci-turbo`; diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index e0abc5d4..d6bebb3b 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -3,8 +3,9 @@ import { test } from 'node:test'; import { placeholders, RUNNER_USER_DATA, render } from './userData.ts'; test('the templates name their placeholders, digits included', () => { - assert.ok(placeholders(RUNNER_USER_DATA).includes('RUNNER_SHA256')); + assert.ok(placeholders(RUNNER_USER_DATA).includes('NO_JOB_MINUTES')); assert.ok(placeholders(RUNNER_USER_DATA).includes('JITCONFIG')); + assert.ok(placeholders(RUNNER_USER_DATA).includes('IMAGE')); }); test('render fills every placeholder and refuses a leftover', () => { @@ -17,10 +18,63 @@ test('render fills every placeholder and refuses a leftover', () => { ); }); -test('the runner template is cloud-config that arms the timers first and runs the runner last', () => { +test('the runner template is cloud-config that arms the timers first, pulls the image, and runs the runner last', () => { assert.ok(RUNNER_USER_DATA.startsWith('#cloud-config')); const start = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-no-job.timer'); + const pull = RUNNER_USER_DATA.indexOf('docker pull -q @@IMAGE@@'); const runner = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-runner.service'); - assert.ok(start > 0 && runner > start); + assert.ok(start > 0 && pull > start && runner > pull); assert.match(RUNNER_USER_DATA, /SELF_LAYERS=@@SELF_LAYERS@@/); }); + +/** The line of the runner's unit that starts with `key=`, trimmed. */ +const unitLine = (key: string) => + RUNNER_USER_DATA.slice(RUNNER_USER_DATA.indexOf('path: /etc/systemd/system/plexus-ci-runner.service')) + .split('\n') + .find((l) => l.trim().startsWith(`${key}=`)) + ?.trim() ?? ''; + +test('the job runs in a container of the environment image, as on a slot: the host’s network, no Docker socket', () => { + const run = unitLine('ExecStart'); + assert.match(run, /^ExecStart=\/usr\/bin\/docker run --rm --init /); + assert.match(run, / --network host /); + assert.match(run, / --env-file \/etc\/plexus-ci\/runner\.env /); + assert.match(run, / @@IMAGE@@ \.\/run\.sh$/); + assert.doesNotMatch(run, /docker\.sock|--privileged/); + assert.equal(unitLine('ExecStopPost'), 'ExecStopPost=+/usr/local/sbin/plexus-ci-self-delete runner-exit'); +}); + +test('the runner’s config reaches the container as the variable a slot’s does, in a root-only file', () => { + assert.match( + RUNNER_USER_DATA, + / {2}- path: \/etc\/plexus-ci\/runner\.env\n {4}permissions: "0600"\n {4}content: \|\n {6}ACTIONS_RUNNER_INPUT_JITCONFIG=@@JITCONFIG@@\n/, + ); +}); + +test('the runner’s log stays on the host, where the no-job layer and a kept instance’s reader look', () => { + assert.match(unitLine('ExecStart'), / -v \/opt\/runner\/_diag:\/home\/runner\/_diag /); + assert.match(RUNNER_USER_DATA, /ls \/opt\/runner\/_diag\/Worker_\*\.log/); +}); + +test('the job’s container mounts nothing but the log’s directory: an instance runs one job, so no cache is shared', () => { + assert.deepEqual(unitLine('ExecStart').match(/ -v \S+/g), [' -v /opt/runner/_diag:/home/runner/_diag']); +}); + +test('the log’s directory is the runner’s before the container mounts it, or the no-job layer deletes a running job', () => { + // Docker would create a missing mount source as root, where the image's + // runner (1001) cannot write its Worker log. + const owned = RUNNER_USER_DATA.indexOf('\n - install -d -o 1001 -g 1001 /opt/runner/_diag\n'); + const runner = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-runner.service'); + assert.ok(owned > 0 && owned < runner); +}); + +test('the instance gives the job no Docker daemon: no runner on the host, no builder, no test images', () => { + assert.doesNotMatch( + RUNNER_USER_DATA, + /actions-runner-linux|installdependencies|useradd|buildx create|docker pull -q postgres/, + ); +}); + +test('the instance starts no registry and holds no storage key beside its own', () => { + assert.doesNotMatch(RUNNER_USER_DATA, /registry|REGISTRY|:500[01]/); +}); diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 4c6c066c..a36b6d75 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -1,11 +1,15 @@ // The cloud-config an instance boots with (§ 8 PLX-Delivery), as text: a -// runner's, with every teardown layer. The placeholders `@@NAME@@` are filled -// by render(); a leftover placeholder is an error. Kept as string constants so +// runner's, with every teardown layer. The runner runs as on a runner host's +// slot: in a container of the environment image (actions_runners' ci-runner), +// on the host's network, with no Docker socket, so a job meets the same +// machine under on-prem and hybrid; the instance's own Docker runs that one +// container, and nothing for the job. The placeholders `@@NAME@@` are filled by +// render(); a leftover placeholder is an error. Kept as string constants so // that the bundle carries them and the tests render them without a loader. The // cloud-config itself is documented inline; edit here, nowhere else. // // The three deadlines, minutes the caller passes (NO_JOB_MINUTES, -// DEATH_MINUTES, POWEROFF_MINUTES in _verify.yml): +// DEATH_MINUTES, POWEROFF_MINUTES in _e2e.yml): // // no-job no job has started by then: the instance deletes itself, no mail // death it mails the alerts address and deletes itself, whatever runs; @@ -37,9 +41,8 @@ export const RUNNER_USER_DATA = `#cloud-config # cloud-init does not get past it (the hostname stays \`localhost\`, no # network, no SSH), so every layer is a systemd timer started in runcmd. # -# The self-delete key and the registry bucket's write key sit in -# /etc/plexus-ci/env, readable by root; the job that runs here could read -# them anyway (§ 8 PLX-Delivery). +# The self-delete key sits in /etc/plexus-ci/env, readable by root on the +# host; the job's container mounts none of /etc/plexus-ci (§ 8 PLX-Delivery). hostname: @@LABEL@@ write_files: @@ -60,17 +63,12 @@ write_files: SMTP_PASSWORD=@@SMTP_PASSWORD@@ MAIL_FROM=@@MAIL_FROM@@ MAIL_TO=@@MAIL_TO@@ - REGISTRY_ENDPOINT=@@REGISTRY_ENDPOINT@@ - REGISTRY_REGION=@@REGISTRY_REGION@@ - REGISTRY_BUCKET=@@REGISTRY_BUCKET@@ - REGISTRY_PREVIOUS_BUCKET=@@REGISTRY_PREVIOUS_BUCKET@@ - REGISTRY_ACCESS_KEY=@@REGISTRY_ACCESS_KEY@@ - REGISTRY_SECRET_KEY=@@REGISTRY_SECRET_KEY@@ - RUNNER_VERSION=@@RUNNER_VERSION@@ - RUNNER_SHA256=@@RUNNER_SHA256@@ - - path: /etc/plexus-ci/jitconfig + # The runner's config, as a slot's container gets it (ci-runner-jit): the + # runner reads the variable and clears it before any job step runs. + - path: /etc/plexus-ci/runner.env permissions: "0600" - content: "@@JITCONFIG@@" + content: | + ACTIONS_RUNNER_INPUT_JITCONFIG=@@JITCONFIG@@ # The cloud's API with curl, signed with the self-delete key (EXO2-HMAC-SHA256, # as egoscale signs: method and path, body, the query's values, the signed @@ -138,9 +136,10 @@ write_files: content: | #!/bin/sh # Layer 1b: the runner spawns a Worker process for a job and nothing - # else, and logs it as _diag/Worker_*.log; _work itself exists, empty, - # from the runner's start, so it tells nothing. No Worker log by now - # means no job ever came, and nothing will. + # else, and logs it as _diag/Worker_*.log, which the container writes + # to /opt/runner/_diag on the host; _work itself exists, empty, from + # the runner's start, so it tells nothing. No Worker log by now means + # no job ever came, and nothing will. set -u if ! ls /opt/runner/_diag/Worker_*.log >/dev/null 2>&1; then logger -t plexus-ci "no job started, deleting" @@ -234,22 +233,26 @@ write_files: dpkg --configure -a logger -t plexus-ci "apt-free: apt timers masked, dpkg lock free after \${i}s" - # The runner, one job, then layer 1: ExecStopPost runs as root (the +) when - # the runner exits for any reason. + # The runner, one job in a container of the environment image, then layer + # 1: ExecStopPost runs as root (the +) when the container ends for any + # reason, a runner that could not start included. The container is the + # one a small slot of a runner host starts (ci-runner-slot): the host's + # network and no Docker socket. It mounts no cache: the instance runs this + # one job and is deleted, so nothing is shared between jobs, and what the + # job installs goes with the container. Its only mount, _diag, is the + # host's /opt/runner/_diag, which layer 1b reads and which a kept instance's + # disk keeps. - path: /etc/systemd/system/plexus-ci-runner.service content: | [Unit] Description=plexus-ci: GitHub Actions runner @@LABEL@@, one job After=network-online.target docker.service Wants=network-online.target + Requires=docker.service [Service] Type=simple - User=runner - WorkingDirectory=/opt/runner - Environment=HOME=/home/runner - ExecStart=/bin/sh -c 'exec ./run.sh --jitconfig "$(cat /etc/plexus-ci/jitconfig)"' + ExecStart=/usr/bin/docker run --rm --init --name runner --network host --env-file /etc/plexus-ci/runner.env -v /opt/runner/_diag:/home/runner/_diag @@IMAGE@@ ./run.sh ExecStopPost=+/usr/local/sbin/plexus-ci-self-delete runner-exit - KillMode=process TimeoutStopSec=2min runcmd: @@ -257,17 +260,12 @@ runcmd: - systemctl daemon-reload - systemctl start plexus-ci-no-job.timer plexus-ci-death.timer plexus-ci-poweroff.timer - plexus-ci-apt-free - - export DEBIAN_FRONTEND=noninteractive; apt-get update -q && apt-get install -yq --no-install-recommends ca-certificates curl jq git tar unzip + - export DEBIAN_FRONTEND=noninteractive; apt-get update -q && apt-get install -yq --no-install-recommends ca-certificates curl - curl -fsSL https://get.docker.com | sh - - useradd -m -s /bin/bash -G docker runner && echo 'runner ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/runner - - cp /etc/plexus-ci/jitconfig /etc/plexus-ci/jitconfig.runner && chown runner:runner /etc/plexus-ci/jitconfig.runner && mv /etc/plexus-ci/jitconfig.runner /etc/plexus-ci/jitconfig - - . /etc/plexus-ci/env && mkdir -p /opt/runner && cd /opt/runner && curl -fsSLo runner.tgz "https://github.com/actions/runner/releases/download/v\${RUNNER_VERSION}/actions-runner-linux-x64-\${RUNNER_VERSION}.tar.gz" && echo "\${RUNNER_SHA256} runner.tgz" | sha256sum -c - && tar -xzf runner.tgz && rm runner.tgz && ./bin/installdependencies.sh >/dev/null && chown -R runner:runner /opt/runner - # The registry sidecars, when the launch named a bucket (§ 8 PLX-Delivery): :5000 on this week's bucket, read-write; :5001 on the previous week's, read-only. The same two containers as .github/ci/registry.sh starts on a GitHub runner. - - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry --restart unless-stopped -p 127.0.0.1:5000:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e REGISTRY_STORAGE_DELETE_ENABLED=true registry:2 >/dev/null; fi - - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry-previous --restart on-failure:3 -p 127.0.0.1:5001:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_PREVIOUS_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e 'REGISTRY_STORAGE_MAINTENANCE_READONLY={"enabled":true}' registry:2 >/dev/null; fi - # A builder: the docker driver cannot export a registry cache, so BuildKit runs in its own container on the host's network, where localhost:5000 is the sidecar; bootstrapped now so that the build does not wait for it. Every instance gets it and the test's images: there is one kind of instance, whatever its leg owes. - - su -s /bin/bash runner -c 'docker buildx create --name ci --driver docker-container --driver-opt network=host --bootstrap >/dev/null' & - - docker pull -q postgres:18.6 >/dev/null & docker pull -q rustfs/rustfs:1.0.4 >/dev/null & + # The image's user runner (1001) writes the runner's log here. + - install -d -o 1001 -g 1001 /opt/runner/_diag + # Pulled here rather than by the runner's unit, so that the log says how long the pull took. + - docker pull -q @@IMAGE@@ - systemctl start plexus-ci-runner.service `; diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index f6dbf4a8..272e187b 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -35,18 +35,8 @@ test('help lists the global options', () => { test('the universal commands take --strategy, and hybrid holds the instances’ three', () => { const program = buildProgram(); const names = program.commands.map((c) => c.name()); - assert.deepEqual(names, [ - 'registry', - 'plan', - 'build', - 'test', - 'publish', - 'display-versions', - 'tag-display-version', - 'report', - 'hybrid', - ]); - for (const name of ['registry', 'plan', 'build', 'test', 'publish', 'report']) { + assert.deepEqual(names, ['plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); + for (const name of ['plan']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), diff --git a/packages/cli-ci/src/testing/checkout.ts b/packages/cli-ci/src/testing/checkout.ts new file mode 100644 index 00000000..ab070932 --- /dev/null +++ b/packages/cli-ci/src/testing/checkout.ts @@ -0,0 +1,59 @@ +// A checkout as plan and publish read it, for the tests: an app repo with three +// apps, website and my-app from app-nextjs and solver with a Dockerfile of its +// own, and an E2E suite for website alone. Not shipped (excluded in tsconfig). +import type { Tree } from './fakeIo.ts'; + +/** The lockfile of pnpm 11 and later: the package manager's document, then the workspace's. */ +export const LOCKFILE = [ + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' packageManagerDependencies:', + ' pnpm:', + ' specifier: 12.21.0', + ' version: 12.21.0', + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' devDependencies:', + ' turbo:', + ' specifier: ^2.9.0', + ' version: 2.11.13', + ' apps/site:', + ' dependencies:', + ' next:', + ' specifier: ^16', + ' version: 16.4.6', + '', +].join('\n'); + +/** An app's directory: its package.json and the marker `plx new` writes, with the templates it lists. */ +export const app = (name: string, templates: string[]): Tree => ({ + 'package.json': JSON.stringify({ name }), + 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: '${name}'\nprofile: stateless\n---\n`, +}); + +/** A suite at e2e/, the package the template e2e-playwright renders. */ +export const suite = (of: string): Tree => ({ + 'package.json': JSON.stringify({ + name: `${of}-e2e`, + scripts: { e2e: 'playwright test' }, + devDependencies: { [of]: 'workspace:*', '@playwright/test': '^1.65.1' }, + }), +}); + +/** A checkout with three apps: website and my-app from app-nextjs, solver with a Dockerfile of its own; a suite for website only. */ +export const REPO: Tree = { + repo: { + 'package.json': JSON.stringify({ devDependencies: { turbo: '^2.9.0' } }), + 'pnpm-lock.yaml': LOCKFILE, + apps: { + website: app('@acme/website', ['app-nextjs']), + 'my-app': app('@acme/my-app', ['app-nextjs']), + solver: app('@acme/solver', []), + }, + e2e: { website: suite('@acme/website'), tools: { 'package.json': JSON.stringify({ name: 'tools' }) } }, + }, +}; diff --git a/packages/cli-ci/src/testing/fakeIo.ts b/packages/cli-ci/src/testing/fakeIo.ts index bc34a0ec..8283e93d 100644 --- a/packages/cli-ci/src/testing/fakeIo.ts +++ b/packages/cli-ci/src/testing/fakeIo.ts @@ -6,13 +6,15 @@ import { ExecError, type Io } from '@plexus-ms/lib'; export type Tree = { [name: string]: string | Tree }; -export type FakeExec = (cwd: string, args: string[], input?: string) => string | undefined; +export type FakeExec = (cwd: string, args: string[], input?: string, env?: NodeJS.ProcessEnv) => string | undefined; -/** What a registry answers for a manifest it does not hold, as curl --fail and crane report it. */ -export function notThere(command: 'curl' | 'crane'): never { - throw command === 'curl' - ? new ExecError('curl', 22, 'curl: (22) The requested URL returned error: 404\n') - : new ExecError('crane', 1, 'Error: GET https://ghcr.io/v2/o/a/manifests/t: MANIFEST_UNKNOWN: manifest unknown\n'); +/** What the forge's registry answers for a manifest it does not hold, as crane reports it. */ +export function notThere(): never { + throw new ExecError( + 'crane', + 1, + 'Error: GET https://ghcr.io/v2/o/a/manifests/t: MANIFEST_UNKNOWN: manifest unknown\n', + ); } /** `git` answers git calls; `other` answers any other command, by name. */ @@ -28,7 +30,7 @@ export function fakeIo(tree: Tree, git: FakeExec = () => undefined, other: Recor exec: async (command, args, options) => { const handler = command === 'git' ? git : other[command]; assert.ok(handler, `fake io: no handler for ${command}`); - const out = handler(options?.cwd ?? '', args, options?.input); + const out = handler(options?.cwd ?? '', args, options?.input, options?.env); if (out === undefined) throw new ExecError(`${command} ${args.join(' ')}`, 1, `fake ${command} fails in ${options?.cwd}`); return out; @@ -38,7 +40,17 @@ export function fakeIo(tree: Tree, git: FakeExec = () => undefined, other: Recor if (typeof node !== 'string') throw new Error(`no file ${path}`); return node; }, - writeFile: async () => {}, + // A write lands in the tree, where a later read finds it. + writeFile: async (path, content) => { + const parts = path.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = content; + }, readDir: async (path) => { const node = at(path); if (typeof node !== 'object') throw new Error(`no directory ${path}`); diff --git a/packages/cli/src/commands/new.ts b/packages/cli/src/commands/new.ts index f2009d87..bf5f3307 100644 --- a/packages/cli/src/commands/new.ts +++ b/packages/cli/src/commands/new.ts @@ -8,8 +8,9 @@ // where the root lists templates and is on another version than this plx or // names none; anywhere else it is a new repo. The templates are the ones this // plx bundles, named as the directories of `templates/` are (repo-turbo, -// repo-operations, app-nextjs, updates). A repo is born from its repo -// template with `updates` beside it, which a repo may also go without. +// repo-operations, app-nextjs, e2e-playwright, updates). A repo is born from +// its repo template with `updates` beside it, which a repo may also go +// without. // Answers come as `-a key=value`, repeatable, and as a JSON object in a file // (`--answers`); a flag wins over the file, a value is cast to its question's // type. Nothing is ever asked: a missing answer fails the run, listing every @@ -23,6 +24,7 @@ // // plx new ~/dev/acme/web repo-turbo updates -a tenant=acme // plx new ~/dev/acme/web/apps/shop app-nextjs -a name=shop -a profile=stateful +// plx new ~/dev/acme/web/e2e/shop e2e-playwright -a app=shop // plx new ./ops repo-operations updates --answers ops.json // plx -n new ./web repo-turbo updates -a tenant=acme # what it would write and run import { resolve } from 'node:path'; diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts index 55a9c229..18660152 100644 --- a/packages/cli/src/commands/update.ts +++ b/packages/cli/src/commands/update.ts @@ -1,10 +1,12 @@ // plx update [dir]: this repo takes a version by its step and a schedule (§ 3 // PLX-Updates), as a pull request on `plexus/`: the templates of the // version the repo is on and of the one it takes, rendered and merged at every -// site, the version in the root marker, the lockfile, the workflow refs; how, -// is lib's update.ts. A patch (a hotfix) is taken at once, a -// minor (routine) once the oldest version not taken is as old as the repo's -// interval, a major (a changed contract) only when asked (--now, or --to); +// site, the version in the root marker, the answers no template asks any more +// out of the markers, each named in the run and the pull request, the +// lockfile, the workflow refs; how, is lib's update.ts. A patch (a hotfix) is +// taken at once, a minor (routine) once the oldest version not taken is as old +// as the repo's interval, a major (a changed contract) only when asked (--now, +// or --to); // otherwise the repo rests and says why. The pull request asks the users the // root marker's answer pr_reviewers names for a review, or those --reviewer names // instead (repeatable or comma-separated; an empty one asks nobody), once, @@ -49,7 +51,7 @@ export function register(program: Command): void { program .command('update') .description( - 'take a version as a pull request on plexus/ (the templates merged at every site, the version in the root marker, the lockfile, the workflow refs): a patch at once, a minor at the next scheduled pull (--max-age), a major only when asked; -r in every repo generated from the templates under a directory', + 'take a version as a pull request on plexus/ (the templates merged at every site, the version in the root marker, the answers no template asks any more out of the markers, the lockfile, the workflow refs): a patch at once, a minor at the next scheduled pull (--max-age), a major only when asked; -r in every repo generated from the templates under a directory', ) .argument('[dir]', 'a repo whose root PLEXUS.md names its version; with -r, a directory the repos sit under', '.') .option('-r, --recursive', 'run in every repo generated from the templates under the directory, at any depth') diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 15fc525e..d277e1dd 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -58,6 +58,7 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { chmodSync, + cpSync, existsSync, mkdirSync, mkdtempSync, @@ -75,12 +76,15 @@ import { after, test } from 'node:test'; import { apply, Context, + diagnose, + examine, type FetchVersion, isClean, newSite, type Options, type RecursiveOptions, realIo, + removeMarkerKeys, type Summary, setMarkerKeys, summarize, @@ -280,6 +284,10 @@ const miseToml = (version: string) => /** A template of the fixture refuses to render: it gains a question without a default (`templatesFor`). */ let REQUIRING: string | undefined; +/** What a test adds to a template's manifest at a version: lines below `questions:`, below `reads:`, and at its top level. */ +let ASKED: (template: string, version: string) => { questions?: string[]; reads?: string[]; top?: string[] } = + () => ({}); + /** * The templates of `version` below `root`: the web repo's root (`repo-turbo`), * its app (`app-nextjs`), and the operations repo (`repo-operations`). After @@ -302,13 +310,17 @@ function templatesFor(version: string, root: string): string { template === 'app-nextjs' ? { 'files/layout.txt': `layout of ${version}\n`, policies: ['policies:', ' layout.txt: born-once'] } : undefined; + const asked = ASKED(template, version); const questions = [ ...(template === 'repo-turbo' && version !== '0.1.0' ? [' lint:', ' default: strict'] : []), ...(REQUIRING === template && version !== '0.1.0' ? [' region:', ' type: str'] : []), + ...(asked.questions ?? []), ]; const manifest = [ `name: ${template}`, ...(questions.length ? ['questions:', ...questions] : []), + ...(asked.reads?.length ? ['reads:', ...asked.reads] : []), + ...(asked.top ?? []), ...(born?.policies ?? []), '', ].join('\n'); @@ -358,6 +370,7 @@ const withOrigin = (path: string, name: string) => { function fixture(name: string, kind: 'engine' | 'uncrossed' = 'engine'): void { WS = join(TMP, `ws-${name}`); REQUIRING = undefined; + ASKED = () => ({}); FETCHED = []; FETCHED_INTO = []; FETCH_FAILS = false; @@ -1104,6 +1117,26 @@ test('a versioned repo that fails plx requirements stops the version before anyt assert.match(dry.error ?? '', /plx requirements fails in 2 versioned repos/); }); +test('a version that removes a requirement name passes the preflight, and writes an index without it', async () => { + fixture('removed-name'); + // Put together, not written out: this repo's own citation check reads this file. + const [alpha, beta, delta] = ['Alpha', 'Beta', 'Delta'].map((m) => ['§', '1', `PLX-${m}`].join(' ')); + const gone = ['PLX-Beta', 'Gone'].join('/'); + // Tooling carries the index of the version before, which named a requirement of beta's the compendium has dropped. + const prim = up('tooling'); + const index = join(prim, 'packages/lib/src/standard-index.json'); + put(index, `${JSON.stringify({ version: '0.1.0', citable: [alpha, beta, gone] }, null, 2)}\n`); + commit(prim, 'the index of 0.1.0'); + git(prim, 'push', '--quiet', 'origin', 'main'); + + const dry = await run({ dryRun: true }); + assert.equal(dry.error, undefined, dry.out); + const { error, out } = await run({ yes: true }); + assert.equal(error, undefined, out); + assert.ok(allTagged('0.2.0') && allReleased('0.2.0')); + assert.deepEqual(JSON.parse(read(index)), { version: '0.2.0', citable: [alpha, beta, delta] }); +}); + test("a run that stops at the compendium's release leaves the version unseen by any repo; the re-run releases it", async () => { fixture('last-release'); process.env.FAKE_GH_CREATE_FAIL = 'compendium'; @@ -1781,6 +1814,356 @@ test('update: a born-once file the old render holds and a site lacks stays missi ); }); +// ── a version that no longer asks a question ───────────────────────────────── +// At 0.1.0 the web repo's root template asks `registry`, `blocky`, `note`, +// `unanswered` and `moved`, and reads `borrowed`; at 0.2.0 it asks none of them +// but `kept`, which it asks at both, and `moved` has gone to the app's +// template. The app's template asks `app_only` at 0.1.0 only, the operations +// template `registry` at 0.1.0 only. +const asksLess = (template: string, version: string) => { + const old = version === '0.1.0'; + const ask = (name: string, ...fields: string[]) => [` ${name}:`, ...fields.map((f) => ` ${f}`)]; + if (template === 'repo-turbo') + return { + questions: [ + ...(old + ? [ + ...ask('registry', 'default: ghcr'), + ...ask('blocky', 'type: yaml', 'default: []'), + ...ask('note', 'default: ""'), + ...ask('unanswered', 'default: x'), + ...ask('moved', 'default: m'), + ] + : []), + ...ask('kept', 'default: k'), + ], + reads: old ? [' borrowed: {default: b}'] : [], + }; + if (template === 'app-nextjs') return { questions: old ? ask('app_only', 'default: a') : ask('moved', 'default: m') }; + if (template === 'repo-operations') return { questions: old ? ask('registry', 'default: ghcr') : [] }; + return {}; +}; + +/** The web repo's root marker at 0.1.0: answers to questions 0.1.0 asks and 0.2.0 does not, written as a human might. */ +const ROOT_ASKED_LESS = [ + '---', + 'version: 0.1.0', + 'templates: [repo-turbo]', + '# the registry, decided once', + 'registry: own # ours', + 'kept: mine-too', + 'moved: here', + 'borrowed: mine', + 'blocky:', + ' - a', + ' # between', + ' - b', + 'note: |', + ' line one', + ' line two', + '', + 'mine: hand', + 'deviations: [PLX-Repo/Verbs]', + '---', + '', + '- A tenant repo.', + '- `PLX-Repo/Verbs`: registry: own, a reason in the body.', + '', +].join('\n'); + +/** A fixture whose templates ask less at 0.2.0 (`asksLess`), its markers answering what 0.1.0 asks. */ +function askedLess(name: string): { web: string; platform: string } { + fixture(name); + ASKED = asksLess; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + put(join(web, 'PLEXUS.md'), ROOT_ASKED_LESS); + put(join(web, 'apps/site/PLEXUS.md'), marker('templates: [app-nextjs]\napp_only: a1\n')); + commit(web, 'answers 0.1.0 asks for'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const platform = join(WS, 'acme/platform'); + put(join(platform, 'PLEXUS.md'), marker('version: 0.1.0\ntemplates: [repo-operations]\nregistry: ghcr\n')); + commit(platform, 'answers 0.1.0 asks for'); + git(platform, 'push', '--quiet', 'origin', 'main'); + return { web, platform }; +} + +test('update: an answer to a question the version no longer asks or reads leaves the marker, and the run and the pull request name it', async () => { + const { web, platform } = askedLess('update-asked-less'); + const { result, error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.conflicted, [], out); + assert.equal( + `${onVersion('acme-web', '0.2.0', 'PLEXUS.md')}\n`, + [ + '---', + 'version: 0.2.0', + 'templates: [repo-turbo]', + '# the registry, decided once', + 'kept: mine-too', + 'moved: here', + '', + 'mine: hand', + 'deviations: [PLX-Repo/Verbs]', + 'lint: strict', + '---', + '', + '- A tenant repo.', + '- `PLX-Repo/Verbs`: registry: own, a reason in the body.', + '', + ].join('\n'), + 'the entries of registry, borrowed, blocky and note gone, every other byte as it was: the comment above, the blank line after, the key that never was a question, the key asked on both sides, the key that moved to the template of a nested marker, deviations, the body', + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\n').trimEnd(), + "the nested marker's own answer goes too", + ); + for (const [marker, key] of [ + ['PLEXUS.md', 'registry'], + ['PLEXUS.md', 'borrowed'], + ['PLEXUS.md', 'blocky'], + ['PLEXUS.md', 'note'], + ['apps/site/PLEXUS.md', 'app_only'], + ] as const) { + assert.ok(has(out, `removed from ${marker}, since no template asks or reads it at 0.2.0: ${key}`), out); + assert.match(pull('acme-web', '0.2.0', '.body'), new RegExp(`^- \`${key}\` from \`${marker}\`\\.$`, 'm')); + } + for (const key of ['kept', 'moved', 'mine', 'unanswered', 'version', 'templates', 'deviations']) + assert.doesNotMatch(out, new RegExp(`^ *removed from .*: ${key}$`, 'm'), `${key} is not named`); + assert.match( + pull('acme-web', '0.2.0', '.body'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `registry` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m, + 'one line per marker and key', + ); + assert.match( + git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- PLEXUS\.md: blocky\n- PLEXUS\.md: borrowed\n- PLEXUS\.md: note\n- PLEXUS\.md: registry\n- apps\/site\/PLEXUS\.md: app_only$/m, + 'and the commit', + ); + assert.deepEqual(result?.clean, ['web', 'web/apps/site'], 'a removed answer needs no hand'); + assert.equal(pull('acme-web', '0.2.0', '.draft'), 'false'); + + const ops = await runUpdate({ yes: true }, { repo: platform }); + assert.equal(ops.error, undefined, ops.out); + assert.equal( + onVersion('acme-platform', '0.2.0', 'PLEXUS.md'), + marker('version: 0.2.0\ntemplates: [repo-operations]\n').trimEnd(), + ); + assert.ok(has(ops.out, 'removed from PLEXUS.md, since no template asks or reads it at 0.2.0: registry'), ops.out); +}); + +test('update: the dry run says which answers would be removed, and removes none', async () => { + const { web } = askedLess('update-asked-less-dry'); + const { error, out } = await runUpdate({ dryRun: true, yes: true }, { repo: web }); + assert.equal(error, undefined, out); + for (const [marker, key] of [ + ['PLEXUS.md', 'registry'], + ['apps/site/PLEXUS.md', 'app_only'], + ] as const) + assert.ok(has(out, `to be removed from ${marker}, since no template asks or reads it at 0.2.0: ${key}`), out); + assert.doesNotMatch(out, /^ *removed from /m, 'never that it was'); + assert.throws(() => onVersion('acme-web', '0.2.0', 'PLEXUS.md'), 'nothing pushed'); + assert.ok(!fakeLog().some((l) => has(l, 'pr create')), 'no pull request'); + assert.equal(read(join(web, 'PLEXUS.md')), ROOT_ASKED_LESS, 'the checkout keeps every key'); + assert.equal(git(web, 'status', '--porcelain'), '', 'checkout clean'); +}); + +test('update: a later run still names the answers removed, read from the commit, but no longer one the branch holds again', async () => { + const { web } = askedLess('update-asked-less-later'); + const first = await runUpdate({ yes: true }, { repo: web }); + assert.equal(first.error, undefined, first.out); + const removed = + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `registry` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m; + assert.match(pull('acme-web', '0.2.0', '.body'), removed); + + const later = await runUpdate({ yes: true }, { repo: web }); + assert.equal(later.error, undefined, later.out); + assert.match(pull('acme-web', '0.2.0', '.body'), /^Ready for review: /m); + assert.match(pull('acme-web', '0.2.0', '.body'), removed, 'the body a later run writes names them as well'); + + // Somebody puts one back on the branch: it is no longer removed. + const human = join(WS, 'human'); + git(WS, 'clone', '--quiet', '--branch', 'plexus/0.2.0', remote('acme-web'), human); + put(join(human, 'PLEXUS.md'), setMarkerKeys(read(join(human, 'PLEXUS.md')), { registry: 'own' })); + commit(human, 'we keep the registry answered'); + git(human, 'push', '--quiet', 'origin', 'plexus/0.2.0'); + const again = await runUpdate({ yes: true }, { repo: web }); + assert.equal(again.error, undefined, again.out); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /`registry`/); + assert.match( + pull('acme-web', '0.2.0', '.body'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m, + ); +}); + +test('update: a marker that never answered the question, or holds only keys the version still knows, keeps every byte', async () => { + fixture('update-asked-less-unanswered'); + ASKED = asksLess; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + const root = marker('version: 0.1.0\ntemplates: [repo-turbo]\n# ours\nkept: k2 # asked at both\nmine: hand\n'); + put(join(web, 'PLEXUS.md'), root); + commit(web, 'answers 0.2.0 still asks for, and a key of our own'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const { error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.equal( + onVersion('acme-web', '0.2.0', 'PLEXUS.md'), + root.replace('version: 0.1.0', 'version: 0.2.0').replace('mine: hand\n', 'mine: hand\nlint: strict\n').trimEnd(), + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\nmoved: m\n').trimEnd(), + 'the question that moved to its template is answered there by its default', + ); + assert.doesNotMatch(out, /removed from/); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); + assert.doesNotMatch(git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), /^Removed from/m); +}); + +/** + * A plx-template of a version whose manifests this plx cannot read: it knows + * the top-level key `future`, which it takes out of each template it is handed + * before it renders as this workspace's does. + */ +function futureEngine(): string { + const path = join(WS, 'future-plx-template.mjs'); + put( + path, + `import { spawnSync } from 'node:child_process'; +import { cpSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, join } from 'node:path'; +const copies = mkdtempSync(join(${JSON.stringify(WS)}, 'future-')); +const args = process.argv.slice(2).map((arg) => { + const manifest = join(arg, 'template.yml'); + if (!existsSync(manifest)) return arg; + const copy = join(copies, basename(arg)); + cpSync(arg, copy, { recursive: true }); + writeFileSync(join(copy, 'template.yml'), readFileSync(manifest, 'utf8').replace(/^future:.*\\n/m, '')); + return copy; +}); +const result = spawnSync(process.execPath, [${JSON.stringify(PLX_TEMPLATE)}, ...args], { stdio: 'inherit' }); +process.exit(result.status ?? 1); +`, + ); + return path; +} + +test('update: where this plx cannot read the templates of the version taken, no answer is removed, and the run says why', async () => { + const { web } = askedLess('update-asked-less-unread'); + const asked = ASKED; + ASKED = (template, version) => ({ + ...asked(template, version), + ...(template === 'repo-turbo' && version === '0.2.0' ? { top: ['future: 1'] } : {}), + }); + const fetch: FetchVersion = async (_ctx, version, into) => { + FETCHED.push(version); + return { plxTemplate: futureEngine(), templates: templatesFor(version, join(into, 'templates')) }; + }; + const { result, error, out } = await runUpdate({ yes: true }, { repo: web, fetch }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.conflicted, [], out); + assert.ok(has(out, '! no answer is removed from the markers: this plx cannot read the templates of 0.2.0: '), out); + assert.doesNotMatch(out, /^ *removed from /m); + assert.equal( + `${onVersion('acme-web', '0.2.0', 'PLEXUS.md')}\n`, + ROOT_ASKED_LESS.replace('version: 0.1.0', 'version: 0.2.0').replace( + 'deviations: [PLX-Repo/Verbs]\n', + 'deviations: [PLX-Repo/Verbs]\nlint: strict\n', + ), + 'every key stays', + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\napp_only: a1\n').trimEnd(), + ); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); +}); + +test('update: an answer to a question the version moved to a template the marker does not list stays, for whoever adds that template', async () => { + fixture('update-moved-away'); + // At 0.1.0 the web root's template asks it, at 0.2.0 only the operations template, which the web repo does not list. + ASKED = (template, version) => + template === (version === '0.1.0' ? 'repo-turbo' : 'repo-operations') + ? { questions: [' elsewhere:', ' default: e'] } + : {}; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + put(join(web, 'PLEXUS.md'), marker('version: 0.1.0\ntemplates: [repo-turbo]\nelsewhere: here\n')); + commit(web, 'an answer to a question that moves'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const { error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.equal( + onVersion('acme-web', '0.2.0', 'PLEXUS.md'), + marker('version: 0.2.0\ntemplates: [repo-turbo]\nelsewhere: here\nlint: strict\n').trimEnd(), + 'the version still has the question', + ); + assert.doesNotMatch(out, /removed from/); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); +}); + +test('update: a repo of the real templates whose version no longer asks a question takes it, and plx doctor passes on the branch with no hand edit', async () => { + fixture('asked-less-doctor'); + // The version the repo is on: this checkout's templates, with a question repo-turbo asks no more. + const before = join(WS, 'before-templates'); + cpSync(templatesRoot(), before, { recursive: true }); + const manifest = join(before, 'repo-turbo', 'template.yml'); + put( + manifest, + read(manifest).replace('\nquestions:\n', '\nquestions:\n old_choice:\n type: str\n default: ghcr\n\n'), + ); + const dir = join(WS, 'acme', 'repo-turbo'); + await newSite(new Context({ yes: true }, { ...realIo(), stderr: new PassThrough() }), { + dir, + templates: ['repo-turbo'], + answers: { tenant: 'acme', old_choice: 'own' }, + plxVersion: '0.1.0', + root: before, + }); + const born = read(join(dir, 'PLEXUS.md')); + assert.match(born, /^old_choice: own$/m); + put(join(dir, 'PLEXUS.md'), born.replace(/^old_choice: own$/m, '# chosen once\nold_choice: own # ours')); + // An app repo: the version lands on develop. + git(dir, 'checkout', '--quiet', '-B', 'develop'); + commit(dir, 'born, an answer commented'); + withOrigin(dir, 'acme-repo-turbo'); + const start = read(join(dir, 'PLEXUS.md')); + + const fetchBefore: FetchVersion = async (_ctx, version) => { + FETCHED.push(version); + return { plxTemplate: PLX_TEMPLATE, templates: before }; + }; + const { result, error, out } = await runUpdate( + { yes: true }, + { repo: dir, plxVersion: CURRENT, templates: templatesRoot(), fetch: fetchBefore, to: CURRENT }, + ); + assert.equal(error, undefined, out); + assert.deepEqual(FETCHED, ['0.1.0'], out); + assert.deepEqual(result?.conflicted, [], out); + assert.equal( + `${onVersion('acme-repo-turbo', CURRENT, 'PLEXUS.md')}\n`, + start.replace('version: 0.1.0', `version: ${CURRENT}`).replace('old_choice: own # ours\n', ''), + 'the answer and its line gone, the comment above it kept, every other byte as it was', + ); + assert.ok(has(out, `removed from PLEXUS.md, since no template asks or reads it at ${CURRENT}: old_choice`), out); + assert.match(pull('acme-repo-turbo', CURRENT, '.body'), /^- `old_choice` from `PLEXUS\.md`\.$/m); + + const human = join(WS, 'human-doctor'); + git(WS, 'clone', '--quiet', '--branch', `plexus/${CURRENT}`, remote('acme-repo-turbo'), human); + const ctx = new Context({ yes: true }, { ...realIo(), stderr: new PassThrough() }); + const { facts } = await examine(ctx, human, CURRENT); + const report = diagnose(facts); + const findings = report.units.flatMap((u) => u.findings.map((f) => `${u.path}: ${f.requirement ?? ''} ${f.problem}`)); + // The harness's mise lists no tasks of a real mise.toml, so the verbs are not the doctor's to judge here. + assert.deepEqual( + findings.filter((f) => !f.includes('PLX-Repo/Verbs mise could not list the tasks')), + [], + 'every other check passes, the markers against the templates of the version among them', + ); +}); + // ── a version that moves files from one template to another ──────────────── // The real templates on both sides: a repo born from the repo templates of // 0.132.0 (lib's testing/before.ts, "fetched" as the made-up version 0.1.0) @@ -1850,7 +2233,11 @@ for (const [template, answers, edits] of [ (dir: string) => { const onPr = join(dir, '.github/workflows/on_pr.yml'); put(onPr, read(onPr).replace(' pull_request:\n', ' pull_request:\n types: [opened, synchronize]\n')); - put(join(dir, 'mise.toml'), `${read(join(dir, 'mise.toml'))}\n[tasks.mine]\nrun = "echo mine"\n`); + // Beside [settings], which no change of the template touches: the end of the file is where its tasks change. + put( + join(dir, 'mise.toml'), + read(join(dir, 'mise.toml')).replace('[settings]\n', '[tasks.mine]\nrun = "echo mine"\n\n[settings]\n'), + ); }, ], [ @@ -1861,7 +2248,7 @@ for (const [template, answers, edits] of [ }, ], ] as const) - test(`update: ${template} loses the files updates now holds, and adding updates on the branch gives back the repo as it was`, async () => { + test(`update: ${template} loses the files updates now holds, keeps its local edits, and gets those files back, with the marker, when updates is added on the branch`, async () => { fixture(`move-${template}`); const { dir, name, start } = await bornBefore(template, answers, edits); for (const path of MOVED) assert.ok(path in start, `born with ${path}`); @@ -1878,10 +2265,17 @@ for (const [template, answers, edits] of [ assert.match(marker, new RegExp(`^---\\nversion: ${CURRENT}\\ntemplates: \\[${template}\\]\\n`)); assert.match(marker, /\npr_reviewers: alice\n/, 'the answers stay in the marker'); assert.equal(pull(name, CURRENT, '.reviewers'), 'alice', 'and are read'); + if (template === 'repo-operations') + assert.match(onVersion(name, CURRENT, 'inventory/hosts.yml'), /^# our hosts$/m, 'the local edit kept'); if (template === 'repo-turbo') { const onPr = onVersion(name, CURRENT, '.github/workflows/on_pr.yml'); assert.doesNotMatch(onPr, /^ {2}changeset:$/m, "no job writes the bot's changesets without updates"); assert.match(onPr, /types: \[opened, synchronize\]/, 'the local edit merged'); + assert.match( + onVersion(name, CURRENT, 'mise.toml'), + /^\[tasks\.mine\]\nrun = "echo mine"$/m, + 'and the local task', + ); } const { human, applied } = await addUpdates(name, template); @@ -1889,7 +2283,16 @@ for (const [template, answers, edits] of [ const end = snapshot(human); const expected = { ...start }; expected['PLEXUS.md'] = { - text: setMarkerKeys(start['PLEXUS.md']?.text ?? '', { version: CURRENT, templates: [template, 'updates'] }), + // The question repo-turbo has gained since the move is spliced into the marker, as an empty answer, and the + // answer to ci_registry, which the version no longer asks, leaves it (the package repo was never asked it). + text: removeMarkerKeys( + setMarkerKeys(start['PLEXUS.md']?.text ?? '', { + version: CURRENT, + templates: [template, 'updates'], + ...(template === 'repo-turbo' ? { postgres: '' } : {}), + }), + template === 'repo-operations' ? ['ci_registry'] : [], + ), executable: false, }; const workflow = start[MOVED[0] ?? '']; @@ -1897,8 +2300,9 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - // repo-turbo's template has changed since the move (its changesets configuration), so what the update took in of it is - // no longer the repo as it was: the marker and the files the move concerns are compared. + // Both templates have changed since the move (their verbs, their hooks, a question more in repo-turbo), so what the + // update took in of them is no longer the repo as it was: the marker, with that question added, and the files the + // move concerns are compared. const concerned = (files: typeof end) => Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))); assert.deepEqual(concerned(end), concerned(expected)); diff --git a/packages/dev/src/ship.ts b/packages/dev/src/ship.ts index 71e15418..946de2f8 100644 --- a/packages/dev/src/ship.ts +++ b/packages/dev/src/ship.ts @@ -23,8 +23,8 @@ // dry run is the one place consumers still appear: it previews the unreleased // templates against the workspace's consumers (preview.ts), a maintainer's // test. That the templates are sound is no preflight of ship's: `mise ship` -// depends on the `newborn` task, which creates each template with `plx new`, -// runs its own verify and the doctor of this build over it (newborns/). +// depends on the `e2e` task, which creates each template with `plx new` and +// runs its own verbs and the doctor of this build over it (newborns/). // // Every release lists the subjects of the commits since the previous version, // each a code span, so a tenant can read what a version concerns. The step of @@ -52,10 +52,10 @@ // ship runs from the source of the tooling checkout it cuts, never as a // published package: the tool that releases the version is never itself a // release that could lag behind it. Run it with `mise ship` there, which first -// runs the `newborn` task, every template created and passing its own verify -// with this checkout's own build of the packages a newborn installs, whether -// or not that version is on npm yet (newborns/); `plx-dev ship` run directly has -// no such guard. +// runs `build` and the `e2e` task, every template created and passing its own +// verbs with this checkout's own build of the packages a newborn installs, +// whether or not that version is on npm yet (newborns/); `plx-dev ship` run +// directly has no such guard. // // mise ship # next version = minor+1 over the latest // mise ship -- --to 1.0.0 # explicit Plexus version; also what finishes a half-cut one @@ -189,8 +189,8 @@ async function preflightImmutable(ctx: Context, versioned: Versioned): Promise { const compendium = versioned.repos.find((r) => r.name === COMPENDIUM)?.path; diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 5a75b5bc..3a0c59da 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -12,7 +12,6 @@ test('an app is rendered with its docker files and its source', async () => { '.gitignore', 'PLEXUS.md', 'docker/Dockerfile', - 'docker/compose.ci.yaml', 'docker/compose.yaml', 'next.config.ts', 'package.json', @@ -21,6 +20,7 @@ test('an app is rendered with its docker files and its source', async () => { 'src/app/layout.tsx', 'src/app/page.tsx', 'tsconfig.json', + 'turbo.json', ]); }); @@ -61,7 +61,13 @@ test('the profile is stateless unless the app says stateful', async () => { assert.ok('migrate' in scripts && 'seed' in scripts); assert.match(textOf(stateful, 'docker/compose.yaml'), /profiles: \["migrate"\]/); assert.match(textOf(stateful, 'PLEXUS.md'), /`migrate` and `seed`/); - assert.notEqual(textOf(stateful, 'docker/compose.ci.yaml'), textOf(stateless, 'docker/compose.ci.yaml')); +}); + +test('the Dockerfile has one stage on the Debian slim base, which builds and installs nothing', async () => { + const dockerfile = textOf(await render(), 'docker/Dockerfile'); + assert.equal(dockerfile.match(/^FROM /gm)?.length, 1); + assert.match(dockerfile, /^FROM node:\d+-slim@sha256:[0-9a-f]{64}$/m); + assert.doesNotMatch(dockerfile, /^RUN /m); }); test('a profile is one of the two the app contract names', async () => { @@ -77,6 +83,14 @@ test('the source an author edits and the marker are written once, the rest is me assert.equal(origin.policy, once.includes(path) ? 'born-once' : 'merge', path); }); +test('the marker names the verbs an app has, what its test script runs, and what its build leaves', async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) assert.match(marker, new RegExp(`mise :${verb} `)); + assert.doesNotMatch(marker, /verify/); + assert.match(marker, /`node --test`.*\*\*\/\*\.test\.\{cts,mts,ts\}/); + assert.match(marker, /static files and `public\/`/); +}); + test('the marker has no frontmatter, which plx writes', async () => { assert.ok(!textOf(await render({ profile: 'stateful' }), 'PLEXUS.md').startsWith('---')); }); diff --git a/packages/lib/src/apply.test.ts b/packages/lib/src/apply.test.ts index 4425fa09..e5a76fb8 100644 --- a/packages/lib/src/apply.test.ts +++ b/packages/lib/src/apply.test.ts @@ -249,6 +249,24 @@ test('apply deletes the unedited files of a template removed from a site, keeps assert.equal(applied.conflicted, 1); }); +test('apply removes no key from a marker, not even an answer no template it lists asks any more', async () => { + const { repo, templates } = fixture(); + git(repo, 'rm', '-q', '--cached', 'PLEXUS.md'); + write(repo, { + 'PLEXUS.md': both('width: 9\n'), + 'shelf.txt': 'a shelf\n', + 'bench.txt': 'a bench\n', + 'width.txt': '9 wide\n', + }); + git(repo, 'add', '-A'); + git(repo, 'commit', '-q', '-m', 'shelf'); + const dropped = marker(`version: ${VERSION}\ntemplates: [basket]\nfruit: apple\nwidth: 9\n`); + write(repo, { 'PLEXUS.md': dropped }); + await apply(quietContext(), options(repo, templates)); + assert.equal(existsSync(join(repo, 'width.txt')), false, 'the template is dropped'); + assert.equal(text(repo, 'PLEXUS.md'), dropped, "its answer is the human's to remove, as the doctor says"); +}); + test('apply renders a site whose marker is new, from nothing, once git tracks it', async () => { const { repo, templates } = fixture(); write(repo, { 'apps/crate/PLEXUS.md': CRATE }); diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 441b7087..bae35658 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; -import { REGULAR, render, type Tree as Template } from '@plexus-ms/cli-template'; +import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli-template'; import { type Compose, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts } from './doctor.ts'; @@ -12,6 +12,7 @@ import { unitsOf } from './model.ts'; import { overview } from './overview.ts'; import type { MarkerSite } from './sites.ts'; import type { Bundled } from './siteTemplates.ts'; +import { templatesRoot } from './templatesRoot.ts'; import { type FakeExec, fakeIo, link, type Tree, UNREADABLE } from './testing/fakeIo.ts'; import { UsageError } from './version.ts'; @@ -37,13 +38,31 @@ test('the checks are exactly the requirements the contract pages say doctor chec // --- fixtures: a repo and its apps that pass every check ------------------------- +/** The five repo verbs, as `plx doctor` asks for them. */ +const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; + +/** The hooks `hk.pkl` of a repo that meets PLX-Repo/Hooks wires. */ +const HOOKS = ['pre-commit', 'pre-push']; + +/** What `plx doctor` says of a verb the repo lacks, and what to write: a no-op that passes for the three a repo may have no use for. */ +const NO_USE = 'add one, a no-op that passes where the repo has no use for it'; +const ADVICE: Record = { + dev: NO_USE, + build: NO_USE, + check: "add one that runs the repo's static checks", + test: "add one that runs `check` and then the repo's tests", + e2e: NO_USE, +}; +const noTask = (verb: string) => `no root mise task \`${verb}\`: ${ADVICE[verb]}`; + const reasoned = (names: string[]) => names.map((n) => `- \`${n}\`: the reason.`).join('\n'); const repo = (over: Partial = {}): RepoFacts => ({ kind: 'repo', path: 'r', marker: { declaration: { deviations: [], body: '' } }, - tasks: { names: ['dev', 'build', 'verify', 'lint', 'check', 'test', 'install'] }, + tasks: { names: [...VERBS, 'lint', 'install'] }, + hk: HOOKS, tracked: ['mise.toml', 'apps/a/docker/compose.yaml'], apps: ['apps/a'], ...over, @@ -103,21 +122,21 @@ const FAILING: Record Facts; problem: unit: () => repo({ marker: { problem: 'PLEXUS.md: no frontmatter: expected a `---` block at the top' } }), problem: /^PLEXUS\.md: no frontmatter/, }, - 'PLX-Repo/Verbs': { + 'PLX-Repo/Hooks': { unit: (deviations = []) => repo({ - tasks: { names: ['dev', 'verify', 'lint', 'check', 'test'] }, + hk: ['pre-commit'], marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^no root mise task `build`$/, + problem: /^hk\.pkl wires no `pre-push` hook$/, }, - 'PLX-Repo/SubVerbs': { + 'PLX-Repo/Verbs': { unit: (deviations = []) => repo({ - tasks: { names: ['dev', 'build', 'verify', 'check', 'test'] }, + tasks: { names: VERBS.filter((v) => v !== 'build') }, marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^no root mise task `lint`$/, + problem: /^no root mise task `build`: add one, a no-op that passes/, }, 'PLX-App/Marker': { unit: (d) => app(undefined, {}, d), @@ -296,6 +315,136 @@ test('mise could not list the tasks: PLX-Repo/Verbs says why, once', () => { ]); }); +// --- the five verbs and the hooks ---------------------------------------------------- + +test('a repo with the five verbs passes, with or without a lint task; each one missing is a finding naming it', () => { + assert.deepEqual(findings(repo({ tasks: { names: VERBS } })), []); + for (const verb of VERBS) + assert.deepEqual(findings(repo({ tasks: { names: VERBS.filter((v) => v !== verb) } })), [ + { requirement: 'PLX-Repo/Verbs', problem: noTask(verb) }, + ]); +}); + +test('a leftover verify task is a finding of PLX-Repo/Verbs that names its replacement', () => { + const found = findings(repo({ tasks: { names: [...VERBS, 'verify'] } })); + assert.equal(found.length, 1); + assert.equal(found[0]?.requirement, 'PLX-Repo/Verbs'); + assert.match(found[0]?.problem ?? '', /^a root mise task `verify` is left over: `check` and `test` replace it/); +}); + +test('PLX-Repo/Hooks: hk.pkl must wire a pre-commit and a pre-push hook, one finding for each that is missing', () => { + assert.deepEqual(findings(repo({ hk: HOOKS })), []); + assert.deepEqual( + findings(repo({ hk: ['pre-push'] })).map((f) => f.problem), + ['hk.pkl wires no `pre-commit` hook'], + ); + assert.deepEqual( + findings(repo({ hk: ['pre-commit'] })).map((f) => f.problem), + ['hk.pkl wires no `pre-push` hook'], + ); + assert.deepEqual( + findings(repo({ hk: ['commit-msg'] })).map((f) => f.problem), + ['hk.pkl wires no `pre-commit` hook', 'hk.pkl wires no `pre-push` hook'], + ); + const { hk: _, ...bare } = repo(); + assert.deepEqual( + findings(bare).map((f) => f.problem), + ['no hk.pkl, which wires the git hooks'], + ); +}); + +/** The findings of the repo at /ws/web whose hk.pkl is as given. */ +async function hooksOver(pkl: string | undefined) { + const tree = ws(); + const web = tree.web as Tree; + if (pkl === undefined) delete web['hk.pkl']; + else web['hk.pkl'] = pkl; + const git = (cwd: string, args: string[]) => (args[0] === 'ls-files' && cwd === '/ws/web' ? '' : undefined); + const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: miseTasks({ '/ws/web': ALL_TASKS }) })); + return diagnose((await examine(ctx, '/ws/web')).facts).units[0]?.findings.map((f) => f.problem); +} + +const STEP = '{ steps { ["s"] { check = "mise :check" } } }'; +const PKL = (hooks: string) => `amends "package://example.org/hk@1/Config.pkl"\n\nhooks {\n${hooks}\n}\n`; +const WIRED = PKL(` ["pre-commit"] ${STEP}\n ["pre-push"] ${STEP}`); + +test('PLX-Repo/Hooks is existence only: a pre-push hook that runs only check passes, as does a hook without steps', async () => { + assert.deepEqual(await hooksOver(WIRED), []); + assert.deepEqual( + await hooksOver(PKL(` ["pre-commit"] {}\n ["pre-push"] ${STEP.replace('mise :check', 'true')}`)), + [], + ); +}); + +test('PLX-Repo/Hooks: no hk.pkl, and a hook of another name, are findings', async () => { + assert.deepEqual(await hooksOver(undefined), ['no hk.pkl, which wires the git hooks']); + assert.deepEqual(await hooksOver(WIRED.replace('"pre-commit"', '"commit-msg"')), [ + 'hk.pkl wires no `pre-commit` hook', + ]); + assert.deepEqual(await hooksOver(WIRED.replace('"pre-push"', '"post-merge"')), ['hk.pkl wires no `pre-push` hook']); + assert.deepEqual(await hooksOver('amends "package://example.org/hk@1/Config.pkl"\n'), [ + 'hk.pkl wires no `pre-commit` hook', + 'hk.pkl wires no `pre-push` hook', + ]); +}); + +test('PLX-Repo/Hooks: a hook behind a comment is not wired', async () => { + const noPush = ['hk.pkl wires no `pre-push` hook']; + const commit = ` ["pre-commit"] ${STEP}\n`; + assert.deepEqual(await hooksOver(PKL(`${commit} /* ["pre-push"] ${STEP} */`)), noPush, 'a block comment'); + assert.deepEqual(await hooksOver(PKL(`${commit} /*\n ["pre-push"] ${STEP}\n */`)), noPush, 'over lines'); + assert.deepEqual(await hooksOver(PKL(`${commit} // ["pre-push"] ${STEP}`)), noPush, 'a line comment'); + assert.deepEqual(await hooksOver(PKL(`${commit} // ["pre-push"] {\n }`)), noPush, 'a key line commented out'); +}); + +test('PLX-Repo/Hooks: braces and keys inside a multi-line or a custom-delimited string are text, not code', async () => { + const commit = (check: string) => ` ["pre-commit"] { steps { ["s"] { check = ${check} } } }\n`; + const push = ` ["pre-push"] ${STEP}\n`; + const noPush = ['hk.pkl wires no `pre-push` hook']; + const fake = '} } } ["pre-push"] { {'; + assert.deepEqual(await hooksOver(PKL(commit(`"""\n${fake}\n"""`))), noPush, 'a hook inside a multi-line string'); + assert.deepEqual(await hooksOver(PKL(commit(`#"x "${fake}"#`))), noPush, 'inside #"…"#'); + assert.deepEqual(await hooksOver(PKL(commit(`##"x "#${fake}"##`))), noPush, 'inside ##"…"##, a shorter closer in it'); + assert.deepEqual(await hooksOver(PKL(commit(`#"""\n${fake}\n"""#`))), noPush, 'inside #"""…"""#'); + assert.deepEqual( + await hooksOver(PKL(`${commit(`"""\nsed -i 's/}$//' file\n"""`)}${push}`)), + [], + 'an unbalanced brace', + ); + assert.deepEqual(await hooksOver(PKL(`${commit('#"sed -i \'s/}$//\'"#')}${push}`)), []); +}); + +test('PLX-Repo/Hooks: a hook not written as a key of the hooks block in this file is not seen', async () => { + const both = ['hk.pkl wires no `pre-commit` hook', 'hk.pkl wires no `pre-push` hook']; + const body = ` ["pre-commit"] ${STEP}\n ["pre-push"] ${STEP}`; + assert.deepEqual(await hooksOver(`hooks = new Mapping {\n${body}\n}\n`), both, 'hooks = new Mapping'); + const commit = ` ["pre-commit"] ${STEP}\n`; + assert.deepEqual( + await hooksOver(`local push = new Hook ${STEP}\n${PKL(`${commit} ["pre-push"] = push`)}`), + ['hk.pkl wires no `pre-push` hook'], + 'a hook assigned from a variable', + ); + assert.deepEqual(await hooksOver(PKL(`${commit} [#"pre-push"#] ${STEP}`)), ['hk.pkl wires no `pre-push` hook']); +}); + +test('PLX-Repo/Hooks: a hook name inside a string, or as a step of another hook, is not a hook', async () => { + const commit = ` ["pre-commit"] ${STEP}\n`; + const noPush = ['hk.pkl wires no `pre-push` hook']; + assert.deepEqual( + await hooksOver(PKL(`${commit} ["post-merge"] { steps { ["s"] { check = "x [\\"pre-push\\"] {" } } }`)), + noPush, + 'in a string', + ); + assert.deepEqual( + await hooksOver(PKL(` ["pre-commit"] { steps { ["pre-push"] { check = "true" } } }`)), + noPush, + 'a step of that name', + ); + assert.deepEqual(await hooksOver(PKL(`${commit} ["s"] { check = "http://x" }\n ["pre-push"] ${STEP}`)), []); + const other = `other {\n ["pre-push"] ${STEP}\n}\n${PKL(commit)}`; + assert.deepEqual(await hooksOver(other), noPush, 'a key of another block'); +}); + // --- compose's spellings ----------------------------------------------------------- const appOf = (text: string, profile = 'stateless') => app(profile, { compose: parseCompose(text, 'c') }); @@ -629,11 +778,42 @@ const miseTasks = ]); }; +/** The hk.pkl of the fixture repos: a pre-commit hook, and a pre-push hook that runs both gates. */ +const HK = `hooks { + ["pre-commit"] { + steps { + ["lint"] { + check = "mise :lint {{ files }}" + } + } + } + ["pre-push"] { + steps { + ["check"] { + check = "mise :check" + } + ["test"] { + check = "mise :test" + } + } + } +} +`; + +/** + * The deviation the fixture's operations repo lists, of a requirement without a + * check: made up, and known to the diagnosis because the test says so, so that + * no test depends on the names one version's index happens to hold. Joined at + * run time: written out, plx requirements would read it as a citation of nothing. + */ +const UNCHECKED = ['PLX-Repo', 'Unchecked'].join('/'); + const ws = (): Tree => ({ 'mise.toml': '', web: { '.git': {}, 'PLEXUS.md': MARKER, + 'hk.pkl': HK, 'mise.toml': '', apps: { site: { @@ -646,9 +826,9 @@ const ws = (): Tree => ({ }, ops: { '.git': {}, - 'PLEXUS.md': - '---\nversion: 0.1.0\ntemplates: [repo-operations]\ntenant: acme\ndeviations: [PLX-Repo/SubVerbs]\n---\n\n- `PLX-Repo/SubVerbs`: the playbooks are checked by `check`.\n', + 'PLEXUS.md': `---\nversion: 0.1.0\ntemplates: [repo-operations]\ntenant: acme\ndeviations: [${UNCHECKED}]\n---\n\n${reasoned([UNCHECKED])}\n`, 'mise.toml': '[tools]\n"npm:@plexus-ms/cli" = "0.1.0"\n', + 'hk.pkl': HK, apps: { id: { 'PLEXUS.md': '---\nprofile: stateful\n---\n', @@ -660,12 +840,13 @@ const ws = (): Tree => ({ }, }); -const VERBS = ['dev', 'build', 'verify', 'lint', 'check', 'test']; +/** What mise lists of a repo whose five verbs and lint exist. */ +const ALL_TASKS = [...VERBS, 'lint']; async function doctorOver( tree: Tree, root: string, - webTasks: string[] = VERBS, + webTasks: string[] = ALL_TASKS, tracked: Record = {}, around: Tree = {}, plx?: string, @@ -673,22 +854,22 @@ async function doctorOver( const files: Record = { '/ws/web': ['PLEXUS.md', 'apps/site/docker/compose.yaml'], ...tracked }; const git = (cwd: string, args: string[]) => args[0] === 'ls-files' && files[cwd] ? files[cwd].map((f) => `${f}\0`).join('') : undefined; - const mise = miseTasks({ '/ws/web': webTasks, '/ws/ops': ['dev', 'build', 'verify', 'check', 'test'] }); + const mise = miseTasks({ '/ws/web': webTasks, '/ws/ops': VERBS }); const ctx = new Context({}, fakeIo({ ...around, ws: tree }, git, { mise: (cwd) => mise(cwd) })); const { facts, ...examined } = await examine(ctx, root, plx); - return { ...examined, facts, ...diagnose(facts) }; + return { ...examined, facts, ...diagnose(facts, new Set([UNCHECKED])) }; } const requirements = (report: Awaited>) => report.units.map((u) => [u.path, u.kind, u.findings.map((f) => f.requirement)]); test('doctor in a repo fails on a missing build task and passes once it exists', async () => { - const verbs = ['dev', 'verify', 'lint', 'check', 'test']; + const verbs = ALL_TASKS.filter((v) => v !== 'build'); const before = await doctorOver(ws(), '/ws/web', verbs); assert.deepEqual( before.units.map((u) => [u.path, u.kind, u.findings]), [ - ['.', 'repo', [{ requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `build`' }]], + ['.', 'repo', [{ requirement: 'PLX-Repo/Verbs', problem: noTask('build') }]], ['apps/site', 'app', []], ], ); @@ -701,7 +882,7 @@ test('doctor over a workspace checks every Plexus repo beneath, apps by their re assert.deepEqual( report.units.map((u) => [u.path, u.kind, u.profile, u.deviations, u.findings]), [ - ['ops', 'operations', undefined, ['PLX-Repo/SubVerbs'], []], + ['ops', 'operations', undefined, [UNCHECKED], []], [ 'ops/apps/id', 'app', @@ -719,7 +900,7 @@ test('a repo that has not crossed over is judged by the plx it pins: what needs const tree = ws(); // Its markers say nothing yet, so this plx cannot tell the operations repo from another, and its app is third-party or built. (tree.ops as Tree)['PLEXUS.md'] = '---\n---\n\n- Third-party apps.\n'; - const report = await doctorOver(tree, '/ws/ops', VERBS, { '/ws/ops': ['PLEXUS.md', '.copier-answers.yml'] }); + const report = await doctorOver(tree, '/ws/ops', ALL_TASKS, { '/ws/ops': ['PLEXUS.md', '.copier-answers.yml'] }); const [repo, app] = report.units; assert.deepEqual( app?.findings.map((f) => f.requirement), @@ -727,7 +908,7 @@ test('a repo that has not crossed over is judged by the plx it pins: what needs 'no PLX-App/ImageRef or PLX-App/Dockerfile: the app may be third-party', ); assert.match(repo?.hints?.join('\n') ?? '', /has not crossed over.*judged by the plx it pins/); - const crossed = await doctorOver(tree, '/ws/ops', VERBS, { '/ws/ops': ['PLEXUS.md'] }); + const crossed = await doctorOver(tree, '/ws/ops', ALL_TASKS, { '/ws/ops': ['PLEXUS.md'] }); assert.ok( crossed.units[1]?.findings.some((f) => f.requirement === 'PLX-App/ImageRef'), 'a crossed-over repo is judged', @@ -828,14 +1009,14 @@ test('(e) git roots beneath make a workspace, whatever lies above; with none ben const around: Tree = { '.git': {} }; const tree = ws(); tree.notes = { 'todo.md': '- write it down\n' }; - const workspace = await doctorOver(tree, '/ws', VERBS, {}, around); + const workspace = await doctorOver(tree, '/ws', ALL_TASKS, {}, around); assert.equal(workspace.inRepo, false); assert.equal(workspace.root, '/ws'); assert.deepEqual( workspace.units.map((u) => u.path), ['ops', 'ops/apps/id', 'web', 'web/apps/site'], ); - const inside = await doctorOver(tree, '/ws/notes', VERBS, {}, around); + const inside = await doctorOver(tree, '/ws/notes', ALL_TASKS, {}, around); assert.equal(inside.inRepo, true, 'nothing beneath: the directory is part of the repo above'); assert.equal(inside.root, '/'); }); @@ -900,10 +1081,10 @@ test('(h) a symlinked directory in apps/ and a symlinked repo are not followed, const apps = webOf(tree).apps as Tree; apps.shared = link('/elsewhere/app'); apps['notes.txt'] = link('/elsewhere/file.txt'); - const workspace = await doctorOver(tree, '/ws', VERBS, {}, around); + const workspace = await doctorOver(tree, '/ws', ALL_TASKS, {}, around); assert.deepEqual(workspace.links, ['mirror', 'web/apps/shared'], 'a link to a plain directory or a file is no unit'); assert.ok(!workspace.units.some((u) => u.path.startsWith('mirror') || u.path === 'web/apps/shared')); - const repo = await doctorOver(tree, '/ws/web', VERBS, {}, around); + const repo = await doctorOver(tree, '/ws/web', ALL_TASKS, {}, around); assert.deepEqual(repo.links, ['apps/shared']); }); @@ -957,7 +1138,7 @@ test("a task's alias counts as the task, as `mise run` finds it", async () => { JSON.stringify([ task('//:dev'), task('//:build'), - task('//:verify'), + task('//:e2e'), task('//:test'), task('//:static', ['//:check']), task('biome', ['lint']), @@ -975,20 +1156,20 @@ test("a task from a file the repo includes from outside counts by its `dir`; a p JSON.stringify([ task('dev', '/ws/web/mise.toml', '/ws/web'), task('build', '/shared/tasks.toml', '/ws/web'), - task('verify', '/ws/web/../shared/more.toml', '/ws/web'), + task('e2e', '/ws/web/../shared/more.toml', '/ws/web'), task('lint', '/ws/web/mise/tasks.toml', '/elsewhere'), task('check', '/ws/mise.toml', '/ws'), task('test', '/ws/web/../mise.toml', '/ws'), ]), ); assert.deepEqual(report.units[0]?.findings, [ - { requirement: 'PLX-Repo/SubVerbs', problem: 'no root mise task `check`' }, - { requirement: 'PLX-Repo/SubVerbs', problem: 'no root mise task `test`' }, + { requirement: 'PLX-Repo/Verbs', problem: noTask('check') }, + { requirement: 'PLX-Repo/Verbs', problem: noTask('test') }, ]); }); test('a task list without `source` fails with one clear message, not every task missing', async () => { - const report = await withMise(() => JSON.stringify(VERBS.map((name) => ({ name, global: false })))); + const report = await withMise(() => JSON.stringify(ALL_TASKS.map((name) => ({ name, global: false })))); assert.deepEqual(report.units[0]?.findings, [ { requirement: 'PLX-Repo/Verbs', @@ -1146,7 +1327,7 @@ test('doctor reads the plx pin and the tracked markers, and fails the repo for e const site = (web.apps as Tree).site as Tree; site['PLEXUS.md'] = '---\nprofile: stateless\nversion: 0.131.0\n---\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/PLEXUS.md', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); assert.deepEqual( report.units.map((u) => [u.path, u.findings]), [ @@ -1180,7 +1361,7 @@ test('a repo whose root marker lists the operations template, with no answers fi (tree.web as Tree)['PLEXUS.md'] = '---\nversion: 0.131.0\ntemplates: [repo-operations]\n---\n'; (tree.web as Tree)['mise.toml'] = '[tools]\n"npm:@plexus-ms/cli" = "0.131.0"\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); assert.deepEqual( report.units.map((u) => [u.path, u.kind]), [ @@ -1197,7 +1378,7 @@ test('a tracked marker that cannot be read is a finding of its repo and stops no return tree; }; const tracked = { '/ws/web': ['PLEXUS.md', 'apps/x/PLEXUS.md', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(broken(), '/ws', VERBS, tracked); + const report = await doctorOver(broken(), '/ws', ALL_TASKS, tracked); assert.deepEqual( report.units.filter((u) => u.kind !== 'app').map((u) => [u.path, u.findings.map((f) => f.problem)]), [ @@ -1206,7 +1387,7 @@ test('a tracked marker that cannot be read is a finding of its repo and stops no ], ); const onCopier = { '/ws/web': [...(tracked['/ws/web'] ?? []), '.copier-answers.yml'] }; - const skipped = await doctorOver(broken(), '/ws/web', VERBS, onCopier); + const skipped = await doctorOver(broken(), '/ws/web', ALL_TASKS, onCopier); assert.deepEqual(skipped.units[0]?.findings, []); }); @@ -1237,7 +1418,7 @@ test('doctor reads which tracked files hold a conflict marker, and fails the rep if (args[0] === 'grep') return 'mise.toml\0'; return undefined; }; - const mise = miseTasks({ '/ws/web': VERBS }); + const mise = miseTasks({ '/ws/web': ALL_TASKS }); const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: (cwd) => mise(cwd) })); const { facts } = await examine(ctx, '/ws/web'); const report = diagnose(facts); @@ -1315,6 +1496,22 @@ test('every key of the markers is checked, each finding naming its marker', () = ]); }); +test('a marker that still holds ci_registry, a question no template asks any more, is an unknown key', async () => { + const names = ['repo-turbo', 'repo-operations']; + const real: Bundled = { + trees: new Map(await Promise.all(names.map(async (n) => [n, await readTree(join(templatesRoot(), n))] as const))), + render, + }; + for (const name of names) { + const root = site('.', { + version: '0.131.0', + templates: [name], + answers: { tenant: 'acme', ci_strategy: 'github', ci_registry: 'own' }, + }); + assert.deepEqual(findings(crossed([root], { templates: real })), [{ problem: UNKNOWN_ROOT('ci_registry') }], name); + } +}); + test('the root marker may hold answers that a template of a nested site owns or reads', () => { const root = site('.', { version: '0.131.0', @@ -1456,7 +1653,7 @@ test('doctor reads the templates this plx bundles from disk and runs the marker '---\nversion: 0.131.0\ntemplates: [repo-turbo, ghost]\ntenant: plexus\nci_strategy: cloud\nstray: 1\n---\n'; web['mise.toml'] = '[tools]\n"npm:@plexus-ms/cli" = "0.131.0"\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); const problems = report.units[0]?.findings.map((f) => f.problem) ?? []; assert.ok( problems.some((p) => p?.includes('`templates` names `ghost`, which this plx does not bundle')), @@ -1475,7 +1672,7 @@ test('doctor reads the templates this plx bundles from disk and runs the marker const turboMarker = (answers: string) => marked(`---\nversion: 0.130.0\ntemplates: [repo-turbo]\ntenant: plexus\n${answers}---\n`); const problemsOf = async (tree: Tree) => - (await doctorOver(tree, '/ws/web', VERBS, CROSSED, {}, '0.130.0')).units[0]?.findings.map((f) => f.problem); + (await doctorOver(tree, '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0')).units[0]?.findings.map((f) => f.problem); test("repo-turbo's major is a question of a repo with display versions, and a number", async () => { assert.deepEqual(await problemsOf(turboMarker('display_versions: true\nmajor: 1\n')), []); @@ -1511,12 +1708,12 @@ const marked = (marker: string) => { const BROKEN = '---\nversion: 0.130.0\ntemplates: [repo-turbo, ghost]\ntenant: plexus\nstray: 1\n---\n'; test("the marker checks against the templates run where the running plx is the root marker's version", async () => { - const report = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.ok(report.units[0]?.findings.some((f) => f.problem?.includes('`stray` is neither reserved'))); }); test("they are skipped, and a line says so, where the running plx is not the root marker's version", async () => { - const report = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.131.0'); + const report = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.131.0'); assert.deepEqual(report.units[0]?.findings, []); assert.deepEqual(report.units[0]?.hints, [ 'the markers are not checked against the templates: this plx is 0.131.0, the root marker names version 0.130.0; run the plx that version pins', @@ -1524,7 +1721,7 @@ test("they are skipped, and a line says so, where the running plx is not the roo const unset = await doctorOver( marked('---\ntemplates: [repo-turbo]\n---\n'), '/ws/web', - VERBS, + ALL_TASKS, CROSSED, {}, '0.131.0', @@ -1535,10 +1732,10 @@ test("they are skipped, and a line says so, where the running plx is not the roo }); test('the bundled templates are read only for a repo in which a marker lists templates', async () => { - const listing = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const listing = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.ok((listing.facts[0] as RepoFacts).templates); for (const marker of ['---\nversion: 0.130.0\n---\n', '---\nversion: 0.130.0\ntemplates: []\n---\n']) { - const report = await doctorOver(marked(marker), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(marked(marker), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); const facts = report.facts[0] as RepoFacts; assert.equal(facts.templates, undefined, marker); assert.equal(facts.rootAnswers, undefined, marker); @@ -1547,7 +1744,7 @@ test('the bundled templates are read only for a repo in which a marker lists tem test("the root marker's resolved answers, defaults included, are read from the templates", async () => { const valid = marked('---\nversion: 0.130.0\ntemplates: [repo-turbo]\ntenant: plexus\n---\n'); - const report = await doctorOver(valid, '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(valid, '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.equal((report.facts[0] as RepoFacts).rootAnswers?.ci_strategy, 'github'); }); diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index dd29b255..befc024f 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -10,9 +10,9 @@ // checks …", § 1.3 PLX), and a test holds the two equal. // // The checks are static: they read the marker, `docker/compose.yaml`, the -// task list as mise reports it, an app's `package.json`, and git's list of -// tracked files. They never reach a host or a running app, and need no -// compendium: the requirement names a deviation may list come from the index +// task list as mise reports it, the hooks of `hk.pkl`, an app's `package.json`, +// and git's list of tracked files. They never reach a host or a running app, +// and need no compendium: the requirement names a deviation may list come from the index // this plx carries (standardIndex.ts). A deviation the marker lists silences // its check; a deviation without a reason in the marker's body, or naming no // requirement, is a finding of its own. Findings are reported, never fixed. @@ -56,11 +56,18 @@ // apply` renders; otherwise the three are skipped and a hint says why (the // version against the pin is reported beside, as before). // +// The repo's verbs are the five of VERBS, root mise tasks: PLX-Repo/Verbs +// reports each that is missing, and a task `verify`, which no repo has any +// more, with the tasks that replace it. Only the names of the tasks are read, +// never what a task runs: the order of the gates (`check`, `test`, `build`, +// `e2e`) is kept by the tasks, and no check reads it. PLX-Repo/Hooks is +// existence only in the same way: `hk.pkl` wires a pre-commit and a pre-push +// hook (`hooksWired`), and what either runs is not read. +// // plx doctor # this repo and its apps, from anywhere inside it // plx doctor ~/dev # every Plexus repo beneath, and its apps -import { readdir, realpath } from 'node:fs/promises'; +import { realpath } from 'node:fs/promises'; import { basename, dirname, join, relative, resolve } from 'node:path'; -import { readTemplate } from './bundled.ts'; import { APP_SERVICE, type Compose, @@ -75,14 +82,13 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; -import { engine } from './engine.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, reasonGiven } from './marker.ts'; import { crossedOver, type Directory, hasMarker, isOperations, type Kind } from './model.ts'; import { appsOf, directoryAt, overview } from './overview.ts'; import { findSites, type MarkerSite, siteAnswers } from './sites.ts'; -import { type Bundled, templateFindings } from './siteTemplates.ts'; +import { type Bundled, bundledAt, templateFindings } from './siteTemplates.ts'; import { bundledIndex } from './standardIndex.ts'; import { resolvedAnswers } from './sync.ts'; import { templatesRoot } from './templatesRoot.ts'; @@ -104,6 +110,8 @@ export interface RepoFacts { marker?: MarkerRead; /** The root mise tasks, or why mise could not list them. */ tasks: { names: string[] } | { problem: string }; + /** The hooks `hk.pkl` wires, by name; undefined where there is no `hk.pkl`. */ + hk?: string[]; /** The files git tracks, relative to the repo; undefined outside a git checkout. */ tracked?: string[]; /** The tracked files that hold a conflict marker, relative to the repo. */ @@ -152,28 +160,40 @@ export type Facts = RepoFacts | AppFacts; // // Each returns what is wrong, one line per problem; an empty list passes. -const ROOT_VERBS = ['dev', 'build', 'verify']; -const SUB_VERBS = ['lint', 'check', 'test', 'verify']; +/** The repo verbs, in the order of the gates, each with what a repo that lacks it is told to write. */ +const NO_USE = 'add one, a no-op that passes where the repo has no use for it'; +const VERBS: Readonly> = { + dev: NO_USE, + build: NO_USE, + check: "add one that runs the repo's static checks", + test: "add one that runs `check` and then the repo's tests", + e2e: NO_USE, +}; function repoMarker(repo: RepoFacts): string[] { if (!repo.marker) return [`no ${MARKER_FILE} at the repo's root`]; return repo.marker.problem ? [repo.marker.problem] : []; } -const missingTasks = (repo: RepoFacts, wanted: string[]): string[] => - 'names' in repo.tasks - ? wanted - .filter((t) => !(repo.tasks as { names: string[] }).names.includes(t)) - .map((t) => `no root mise task \`${t}\``) - : []; - function verbs(repo: RepoFacts): string[] { if ('problem' in repo.tasks) return [`mise could not list the tasks: ${repo.tasks.problem}`]; - return missingTasks(repo, ROOT_VERBS); + const { names } = repo.tasks; + return [ + ...Object.entries(VERBS) + .filter(([verb]) => !names.includes(verb)) + .map(([verb, advice]) => `no root mise task \`${verb}\`: ${advice}`), + ...(names.includes('verify') + ? ['a root mise task `verify` is left over: `check` and `test` replace it, `mise test` running `check` first'] + : []), + ]; } -/** Existence only: what `verify` runs, in which order, and what `check` includes is not read (see the report). */ -const subVerbs = (repo: RepoFacts): string[] => missingTasks(repo, SUB_VERBS); +/** Existence only: what a hook runs is not read. */ +function hooks(repo: RepoFacts): string[] { + if (!repo.hk) return ['no hk.pkl, which wires the git hooks']; + const wired = repo.hk; + return ['pre-commit', 'pre-push'].filter((h) => !wired.includes(h)).map((h) => `hk.pkl wires no \`${h}\` hook`); +} function appMarker(app: AppFacts): string[] { const { declaration, problem } = app.marker; @@ -368,8 +388,8 @@ interface AppCheck { /** Every requirement doctor checks, by name: what the contract pages list, in their order. */ export const CHECKS: Readonly> = { 'PLX-Repo/Marker': { binds: 'repo', check: repoMarker }, + 'PLX-Repo/Hooks': { binds: 'repo', check: hooks }, 'PLX-Repo/Verbs': { binds: 'repo', check: verbs }, - 'PLX-Repo/SubVerbs': { binds: 'repo', check: subVerbs }, 'PLX-App/Marker': { binds: 'app', check: appMarker }, 'PLX-App/Compose': { binds: 'app', check: composeFile }, 'PLX-App/TenantLabel': { binds: 'app', check: onCompose(tenantLabel) }, @@ -648,6 +668,7 @@ async function readRepo( plxVersion?: string, ): Promise { const marker = markerOf(dir); + const hk = await ctx.readFile(join(dir.path, 'hk.pkl')).then(hooksWired, () => undefined); const tracked = await ctx .read('git', ['ls-files', '-z'], { cwd: dir.path }) .then((out) => out.split('\0').filter(Boolean)) @@ -663,6 +684,7 @@ async function readRepo( path, ...(marker ? { marker } : {}), tasks: await rootTasks(ctx, dir.path), + ...(hk ? { hk } : {}), tracked, ...(conflicted?.length ? { conflicted } : {}), apps: [], @@ -705,14 +727,7 @@ let bundled: Promise | undefined; /** The templates this plx bundles, each read from `templatesRoot()`, once per run. */ function bundledTemplates(): Promise { - bundled ??= (async () => { - const root = templatesRoot(); - const names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); - const trees = await Promise.all( - names.sort().map(async (name) => [name, (await readTemplate(root, name)).tree] as const), - ); - return { trees: new Map(trees), render: (await engine()).render }; - })(); + bundled ??= bundledAt(templatesRoot()); return bundled; } @@ -725,6 +740,45 @@ async function readSites(ctx: Context, repo: string): Promise { + if (string) return; + if (text === '{') depth++; + else if (text === '}') depth--; + if (depth === 0) inside = false; + const next = tokens.slice(i + 1, i + 4).map((t) => (t.string ? '"' : t.text)); + if (depth === 0 && text === 'hooks' && next[0] === '{') inside = true; + const key = tokens[i + 1]; + if (inside && depth === 1 && text === '[' && next.join('') === '"]{' && key) wired.push(key.text); + }); + return wired; +} + /** * The repo's root mise tasks, hidden ones included, as mise lists them, so * that tasks from every file mise reads count; a task counts under its name diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts new file mode 100644 index 00000000..1b97f7ae --- /dev/null +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -0,0 +1,320 @@ +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { gitMergeFile, merge, readTree, render as renderTrees, type Tree } from '@plexus-ms/cli-template'; +import { templatesRoot } from './templatesRoot.ts'; +import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; + +const render = (answers: Record = { app: '@acme/web' }) => renderBundled(['e2e-playwright'], answers); + +test('a suite is rendered as a package of its own: its Playwright configuration, its setup, a spec and its marker', async () => { + const result = await render(); + assert.deepEqual(result.errors, []); + assert.deepEqual(pathsOf(result), [ + '.gitignore', + 'PLEXUS.md', + 'package.json', + 'playwright.config.ts', + 'run.ts', + 'setup.ts', + 'specs/home.spec.ts', + 'tsconfig.json', + 'turbo.json', + ]); +}); + +test('the app is required, and the error carries its help', async () => { + const result = await renderBundled(['e2e-playwright'], {}); + assert.equal(result.errors[0]?.question, 'app'); + assert.match(result.errors[0]?.message ?? '', /package name/); +}); + +test('the package lists the app as a workspace dependency and has two scripts, check and e2e', async () => { + const manifest = JSON.parse(textOf(await render({ app: '@acme/shop' }), 'package.json')); + assert.equal(manifest.name, '@acme/shop-e2e'); + assert.equal(manifest.private, true); + assert.deepEqual(Object.keys(manifest.scripts), ['check', 'e2e']); + const dependencies = { ...manifest.dependencies, ...manifest.devDependencies }; + assert.equal(dependencies['@acme/shop'], 'workspace:*'); + assert.ok(dependencies['@playwright/test'], 'Playwright'); + assert.ok(dependencies['@plexus-ms/test-postgres'], 'the throwaway PostgreSQL of a stateful app'); +}); + +/** A JSON file of a template that may hold whole-line comments, as tsconfig.json and turbo.json do. */ +const jsonc = (text: string) => JSON.parse(text.replace(/^\s*\/\/.*$/gm, '')); + +/** The app as app-nextjs renders it. */ +const appRender = () => renderBundled(['app-nextjs'], { tenant: 'acme', name: '@acme/web' }); + +test('check type-checks the suite, running no test, with the TypeScript, the node types and the shared config the app pins', async () => { + const manifest = JSON.parse(textOf(await render(), 'package.json')); + const app = JSON.parse(textOf(await appRender(), 'package.json')); + assert.equal(manifest.scripts.check, 'tsc --noEmit'); + for (const name of ['typescript', '@types/node', '@plexus-ms/config']) + assert.equal(manifest.devDependencies[name], app.devDependencies[name], name); +}); + +test("tsconfig.json extends the app's own tsconfig.json, through the suite's workspace link to the app, and maps no alias of its own", async () => { + const config = jsonc(textOf(await render({ app: '@acme/shop' }), 'tsconfig.json')); + // Not the package's name: TypeScript would resolve it through the app's exports, which need not export the file. + assert.equal(config.extends, './node_modules/@acme/shop/tsconfig.json'); + // The app's own options, its paths, target, lib and jsx among them, are the app's; the suite sets only its own. + assert.equal(config.compilerOptions.paths, undefined); + assert.equal(config.compilerOptions.target, undefined); +}); + +test("the app's tsconfig.json, which a suite extends, is at the app's root as app-nextjs renders it", async () => { + assert.ok(pathsOf(await appRender()).includes('tsconfig.json')); +}); + +test("tsconfig.json overrides only what is the suite's: its files, no emit and no build info, no editor plugin of the app's, the .ts imports, node's types", async () => { + const config = jsonc(textOf(await render(), 'tsconfig.json')); + // The specs, setup.ts, run.ts and playwright.config.ts; include and exclude are never inherited. + assert.deepEqual(config.include, ['**/*.ts']); + assert.deepEqual(config.exclude, ['node_modules']); + assert.deepEqual(config.compilerOptions, { + noEmit: true, + // tsc 6 reused its build info across a change of the extended config's target alone, both ways (tried). + incremental: false, + plugins: [], + allowImportingTsExtensions: true, + types: ['node'], + }); +}); + +test('tsconfig.json says whose options it reads, and that plx update merges it', async () => { + const text = textOf(await render(), 'tsconfig.json'); + assert.match(text, /the app's own/); + assert.match(text, /plx update merges/); +}); + +test("setup.ts finds the app as Node finds a package, through node_modules, and not through the app's exports", async () => { + const setup = textOf(await render(), 'setup.ts'); + assert.doesNotMatch(setup, /resolve\(`\$\{APP\}\/package\.json`\)/); + assert.match(setup, /'node_modules', APP/); +}); + +test("the incremental check's record is ignored, so that it is no input of a task", async () => { + assert.match(textOf(await render(), '.gitignore'), /^\*\.tsbuildinfo$/m); +}); + +test("the suite's check depends on the checks of its dependencies, the app's among them; its e2e keeps the root's, its test has none", async () => { + const config = jsonc(textOf(await render(), 'turbo.json')); + assert.deepEqual(config.extends, ['//']); + // What the suite's check reads of the app is the app's source, which only the hash of the app's check carries. + assert.deepEqual(config.tasks.check, { dependsOn: ['^check'] }); + assert.deepEqual(config.tasks.test, { dependsOn: [] }); + assert.equal(config.tasks.e2e, undefined); +}); + +test("the spec looks for the app's name, which its page shows", async () => { + assert.match(textOf(await render({ app: '@acme/shop' }), 'specs/home.spec.ts'), /toHaveText\('@acme\/shop'\)/); +}); + +test('no file imports by a relative path out of the suite, starts Next itself, or takes a running app', async () => { + const result = await render(); + for (const path of pathsOf(result).filter((p) => p.endsWith('.ts'))) { + const text = textOf(result, path); + assert.doesNotMatch(text, /(from |import\(|require\()\s*['"]\.\.\//, path); + assert.doesNotMatch(text, /next (start|dev)|webServer/, path); + } +}); + +test("the marker names the verb that runs the suite: mise e2e at the repo's root, with the app's name", async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + assert.match(marker, /`mise e2e ` at the repo's root/); + assert.doesNotMatch(marker, /mise :e2e/); +}); + +test('the marker, the spec and run.ts are written once, the rest is merged', async () => { + const result = await render(); + const once = ['PLEXUS.md', 'run.ts', 'specs/home.spec.ts']; + for (const [path, origin] of result.files) + assert.equal(origin.policy, once.includes(path) ? 'born-once' : 'merge', path); +}); + +test('the marker has no frontmatter, which plx writes, and nothing runs at birth', async () => { + const result = await render(); + assert.ok(!textOf(result, 'PLEXUS.md').startsWith('---')); + assert.deepEqual(result.birth, []); +}); + +test('repo-turbo makes room for suites: e2e/* is a workspace glob, and its package files are sources of install', async () => { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme' }); + const packages = /^packages:\n((?: {2}- .*\n)+)/m.exec(textOf(result, 'pnpm-workspace.yaml'))?.[1] ?? ''; + const globs = [...packages.matchAll(/"([^"]+)"/g)].map((m) => m[1] as string); + assert.ok(globs.includes('e2e/*'), globs.join(' ')); + const sources = /^sources = \[(.*)\]$/m.exec(textOf(result, 'mise.toml').split('[tasks.install]')[1] ?? '')?.[1]; + for (const glob of globs) + assert.match(sources ?? '', new RegExp(`"${glob.replace('*', '\\*')}/package\\.json"`), glob); +}); + +test("setup.ts says it is generated and that what the run needs goes in run.ts; run.ts says it is the repo's", async () => { + const result = await render(); + const head = (path: string) => textOf(result, path).split('\n').slice(0, 4).join('\n'); + assert.match(head('setup.ts'), /^\/\/ Generated from plexus-ms\/tooling, templates\/e2e-playwright: /); + assert.match(head('setup.ts'), /run\.ts/); + assert.match(head('run.ts'), /the repo's own/); + assert.match(head('run.ts'), /never touched by an update/); +}); + +test('run.ts as generated asks for nothing, and setup.ts names no setting of any app', async () => { + const result = await render({ app: '@acme/shop' }); + assert.match(textOf(result, 'run.ts'), /return \{\};/); + assert.doesNotMatch(textOf(result, 'run.ts'), /@acme\/shop/); + // The names the setup gives values to are its own and Next's, never an app's. + const named = [...textOf(result, 'setup.ts').matchAll(/\b([A-Z][A-Z0-9]*_[A-Z0-9_]+|PORT|HOSTNAME)\b(?=\s*[:=])/g)]; + assert.deepEqual([...new Set(named.map((m) => m[1]))].sort(), [ + 'DATABASE_URL', + 'HOSTNAME', + 'NODE_ENV', + 'PLX_E2E_BASE_URL', + 'PORT', + ]); +}); + +/** The template's render, its own run.ts replaced by `runTs` where given, or left out where null. */ +async function suite( + runTs?: string | null, +): Promise<{ tree: Tree; files: Awaited>['files'] }> { + const template = new Map(await readTree(join(templatesRoot(), 'e2e-playwright'))); + if (runTs === null) { + // The template before it had run.ts: neither the file nor its policy. + template.delete('files/run.ts'); + const manifest = template.get('template.yml'); + assert.ok(manifest); + const text = new TextDecoder().decode(manifest.bytes).replace(/^ {2}run\.ts: born-once\n/m, ''); + template.set('template.yml', { ...manifest, bytes: new TextEncoder().encode(text) }); + } else if (runTs !== undefined) + template.set('files/run.ts', { bytes: new TextEncoder().encode(runTs), mode: 0o100644 }); + const result = await renderTrees([template], { app: '@acme/web' }); + assert.deepEqual(result.errors, []); + return { tree: result.tree, files: result.files }; +} + +const noMerge = async () => { + throw new Error('no file of these merges is merged by content'); +}; + +test("an update leaves an edited run.ts alone, also where the template's own run.ts changes between the versions", async () => { + const [old, next] = [await suite(), await suite('// the next version\nexport default () => ({});\n')]; + const edited = new TextEncoder().encode( + '// the app says what its run needs\nexport default () => ({ env: { A: "b" } });\n', + ); + const current = new Map(old.tree).set('run.ts', { bytes: edited, mode: 0o100644 }); + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.deepEqual(merged.tree.get('run.ts')?.bytes, edited); + assert.deepEqual( + merged.report.filter((entry) => entry.path === 'run.ts'), + [{ path: 'run.ts', outcome: 'kept' }], + ); +}); + +test('a suite born before run.ts existed gets it as generated from its next update', async () => { + const [old, next] = [await suite(null), await suite()]; + const merged = await merge( + { old: old.tree, new: next.tree, current: old.tree, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.deepEqual(merged.tree.get('run.ts')?.bytes, next.tree.get('run.ts')?.bytes); + assert.deepEqual( + merged.report.filter((entry) => entry.path === 'run.ts'), + [{ path: 'run.ts', outcome: 'added' }], + ); +}); + +test("the marker says run.ts is the suite's own, and names every place its env reaches", async () => { + const line = textOf(await render(), 'PLEXUS.md') + .split('\n') + .find((l) => l.includes('`run.ts`')); + assert.ok(line); + for (const place of ['migrate', 'seed', 'server', 'specs', 'further processes']) + assert.match(line, new RegExp(place), place); + assert.match(line, /suite's own/); +}); + +test("run.ts names the setup's names, which it may not set, and what Turbo lets it read", async () => { + const text = textOf(await render(), 'run.ts'); + for (const name of ['DATABASE_URL', 'PORT', 'HOSTNAME', 'PLX_E2E_BASE_URL', 'NODE_ENV']) + assert.match(text, new RegExp(`\\b${name}\\b`), name); + assert.match(text, /turbo\.json/); + assert.match(text, /\$TURBO_EXTENDS\$/); +}); + +/** The template as it was before a suite was type-checked: no tsconfig.json, one script, no TypeScript of its own. */ +async function untyped(): Promise<{ tree: Tree; files: Awaited>['files'] }> { + const template = new Map(await readTree(join(templatesRoot(), 'e2e-playwright'))); + const file = (text: string) => ({ bytes: new TextEncoder().encode(text), mode: 0o100644 }); + template.delete('files/tsconfig.json.jinja'); + template.set('files/.gitignore.jinja', file('/test-results/\n/playwright-report/\n')); + template.set( + 'files/package.json.jinja', + file( + [ + '{', + ' "name": "{{ app }}-e2e",', + ' "private": true,', + ' "type": "module",', + ' "scripts": {', + ' "e2e": "playwright test"', + ' },', + ' "devDependencies": {', + ' "{{ app }}": "workspace:*",', + ' "@playwright/test": "^1.65.1",', + ' "@plexus-ms/test-postgres": "^0.1.0"', + ' }', + '}', + '', + ].join('\n'), + ), + ); + const result = await renderTrees([template], { app: '@acme/web' }); + assert.deepEqual(result.errors, []); + return { tree: result.tree, files: result.files }; +} + +/** An update from the untyped suite to this version's, of `current`, with git's merge of a file both sides changed. */ +async function typed(edit: (tree: Tree) => void = () => {}) { + const [old, next] = [await untyped(), await suite()]; + const current = new Map(old.tree); + edit(current); + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + gitMergeFile, + ); + const text = (path: string) => new TextDecoder().decode(merged.tree.get(path)?.bytes); + return { merged, next, text, outcome: (path: string) => merged.report.find((e) => e.path === path)?.outcome }; +} + +test('a suite born before the type check gets tsconfig.json and the check script from its next update, as this version renders them', async () => { + const { merged, next, text, outcome } = await typed(); + assert.equal(outcome('tsconfig.json'), 'added'); + for (const path of ['tsconfig.json', 'package.json', '.gitignore', 'turbo.json']) + assert.deepEqual(merged.tree.get(path)?.bytes, next.tree.get(path)?.bytes, path); + assert.equal(JSON.parse(text('package.json')).scripts.check, 'tsc --noEmit'); +}); + +test('a suite whose package.json gained a dependency of its own gets the check script, and one conflict among the dependencies', async () => { + // As `pnpm add -D @types/pg` in the suite writes it: the new dependency last, in order. + const { text, outcome } = await typed((tree) => { + const entry = tree.get('package.json'); + assert.ok(entry); + const edited = new TextDecoder() + .decode(entry.bytes) + .replace( + '"@plexus-ms/test-postgres": "^0.1.0"\n', + '"@plexus-ms/test-postgres": "^0.1.0",\n "@types/pg": "^8"\n', + ); + tree.set('package.json', { ...entry, bytes: new TextEncoder().encode(edited) }); + }); + assert.equal(outcome('package.json'), 'conflicted'); + const merged = text('package.json'); + // The scripts merge: check beside e2e, outside any conflict. + assert.match(merged, /"scripts": \{\n {4}"check": "tsc --noEmit",\n {4}"e2e": "playwright test"\n {2}\},/); + const hunks = [...merged.matchAll(/^<<<<<<< current\n([\s\S]*?)^>>>>>>> new render\n/gm)]; + assert.equal(hunks.length, 1, merged); + assert.match(hunks[0]?.[1] ?? '', /"@types\/pg": "\^8"[\s\S]*"@types\/node": "\^24"/); +}); diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 20ee0a4d..4293623c 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -117,6 +117,7 @@ export { parseMarkerConfig, RESERVED_KEYS, reasonGiven, + removeMarkerKeys, setMarkerKeys, splitFrontmatter, } from './marker.ts'; diff --git a/packages/lib/src/io.ts b/packages/lib/src/io.ts index 3011c303..e4176562 100644 --- a/packages/lib/src/io.ts +++ b/packages/lib/src/io.ts @@ -138,7 +138,7 @@ export function onInterrupt(cleanup: () => void): () => void { * rejects with an ExecError that `absent` accepts, the error otherwise. By * default any exit is that answer (`git show` of a path the commit lacks, a * check on a host); a read whose tool fails for other reasons too (a registry - * that refuses the login, a sidecar that does not answer) names its own. A + * that refuses the login, a host that does not answer) names its own. A * tool that could not start at all is never "not there". */ export async function orAbsent( diff --git a/packages/lib/src/marker.ts b/packages/lib/src/marker.ts index 9f70fd92..50679fe9 100644 --- a/packages/lib/src/marker.ts +++ b/packages/lib/src/marker.ts @@ -19,10 +19,11 @@ // sites.ts's to enforce. A marker without `templates` is valid and renders // nothing. // -// The one writer of a marker's keys is `setMarkerKeys`. It never re-serialises -// the frontmatter, which a human wrote: it splices the text of each key it -// sets, so that comments, order, quoting and blank lines, and the body, stay -// as they were. +// The writers of a marker's keys are `setMarkerKeys`, and `removeMarkerKeys` +// for the answers `plx update` takes out (update.ts). Neither re-serialises the +// frontmatter, which a human wrote: each splices the text of each key it sets +// or removes, so that comments, order, quoting and blank lines, and the body, +// stay as they were. import { isDeepStrictEqual } from 'node:util'; import { Document, @@ -175,6 +176,49 @@ export function setMarkerKeys(text: string, keys: Record): stri return text.slice(0, start) + written + text.slice(start + yaml.length); } +/** + * The marker with the entry of each of the given frontmatter keys taken out, + * and every other byte as it was: the key's line, the comment on it, and the + * lines its value continues on, a block list or block scalar whole; the comment + * lines above the key, the blank lines around it and whatever follows its + * value stay. A key the frontmatter lacks leaves the text as it is. A reserved + * key is never removed: it is refused. + * + * Where a splice could change what it does not remove, it throws rather than + * guess, naming the key: what `setMarkerKeys` refuses of the frontmatter, an + * explicit key (`? a`), a key with an anchor or tag of its own, and a value + * carrying an anchor that an alias refers to. + */ +export function removeMarkerKeys(text: string, keys: readonly string[]): string { + const { yaml, start } = frontmatterOf(text); + let written = yaml; + for (const key of keys) { + if (isReserved(key)) throw new Error(`marker: \`${key}\` is reserved, and plx never removes it`); + written = removeKey(written, key); + } + return text.slice(0, start) + written + text.slice(start + yaml.length); +} + +/** + * One key taken out of a frontmatter's YAML by splicing its text: from the + * start of its line to the end of its value's last line. A block value's + * range ends past its last line's line break already; any other value's line + * ends after it, with what comment it holds. + */ +function removeKey(yaml: string, key: string): string { + const { doc, pairs } = blockMapping(yaml); + const pair = pairs.find((p) => nameOf(p) === key); + if (!pair) return yaml; + const { key: keyNode, value } = pair; + const from = lineStart(yaml, keyNode.range[0]); + if (value === null || yaml.slice(from, keyNode.range[0]).trim() !== '') + throw new Error(`marker: \`${key}\` is not written as \`${key}: value\` on a line of its own; remove it by hand`); + refuseShared(doc, value, key, 'remove'); + const end = value.range[1]; + const to = yaml[end - 1] === '\n' && end > keyNode.range[1] ? end : yaml.indexOf('\n', end) + 1 || yaml.length; + return yaml.slice(0, from) + yaml.slice(to); +} + /** How a written value is serialised: on one line however long, flow lists without padding. */ const STYLE = { lineWidth: 0, flowCollectionPadding: false } as const; @@ -185,6 +229,15 @@ const STYLE = { lineWidth: 0, flowCollectionPadding: false } as const; * is always found by `indexOf('\n', …)`. */ function setKey(yaml: string, key: string, value: unknown, eol: string): string { + const { doc, pairs } = blockMapping(yaml); + const pair = pairs.find((p) => nameOf(p) === key); + return pair + ? replaceValue(yaml, doc, pair, key, value, eol) + : insertKey(yaml, pairs, key, doc.createNode(value), eol); +} + +/** A frontmatter's YAML parsed, and its pairs; throws where it is no block mapping a splice can work on. */ +function blockMapping(yaml: string): { doc: Document; pairs: readonly Pair[] } { const doc = parseDocument(yaml); if (doc.errors.length > 0) throw new Error(`frontmatter is not YAML: ${doc.errors[0]?.message}`); const map = doc.contents; @@ -193,11 +246,7 @@ function setKey(yaml: string, key: string, value: unknown, eol: string): string // `...` at a line's start, alone or before a blank, ends a YAML document: a line after it would start another. if (/^\.\.\.(?:[ \t]|\r?$)/m.test(yaml)) throw new Error('frontmatter ends its YAML document early with `...`; remove that line'); - const pairs = map?.items ?? []; - const pair = pairs.find((p) => nameOf(p) === key); - return pair - ? replaceValue(yaml, doc, pair, key, value, eol) - : insertKey(yaml, pairs, key, doc.createNode(value), eol); + return { doc, pairs: (map as YAMLMap.Parsed | null)?.items ?? [] }; } /** @@ -279,19 +328,21 @@ function replaceValue(yaml: string, doc: Document, pair: Pair, key: string, valu } /** - * Throws when the value is an alias (`*x`), or carries an anchor (`&x`) an - * alias elsewhere refers to: setting it would change another key, or a key - * written as the same value as another. + * Throws when the value carries an anchor (`&x`) an alias elsewhere refers + * to, and, setting it, when it is an alias (`*x`): setting it would change + * another key, or a key written as the same value as another, and removing it + * would leave the alias without its anchor. */ -function refuseShared(doc: Document, value: Node, key: string): void { - if (isAlias(value)) throw new Error(`marker: \`${key}\` is an alias of another value; set it by hand`); +function refuseShared(doc: Document, value: Node, key: string, act: 'set' | 'remove' = 'set'): void { + if (act === 'set' && isAlias(value)) + throw new Error(`marker: \`${key}\` is an alias of another value; set it by hand`); const referred = new Set(); visit(doc, { Alias: (_, alias) => void referred.add(alias.source) }); visit(value, { Node: (_, node) => { if (node.anchor && referred.has(node.anchor)) throw new Error( - `marker: \`${key}\` carries the anchor \`${node.anchor}\`, which an alias refers to; set it by hand`, + `marker: \`${key}\` carries the anchor \`${node.anchor}\`, which an alias refers to; ${act} it by hand`, ); }, }); diff --git a/packages/lib/src/markerConfig.test.ts b/packages/lib/src/markerConfig.test.ts index c686fc1f..01ea48a5 100644 --- a/packages/lib/src/markerConfig.test.ts +++ b/packages/lib/src/markerConfig.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { parseMarkerConfig, RESERVED_KEYS, setMarkerKeys } from './index.ts'; +import { parseMarkerConfig, RESERVED_KEYS, removeMarkerKeys, setMarkerKeys } from './index.ts'; test('parseMarkerConfig reads version, templates and deviations, and every other key as an answer', () => { const text = [ @@ -258,3 +258,84 @@ test('setMarkerKeys sets a key beside a key that is not a scalar', () => { assert.equal(setMarkerKeys(text, { b: 3 }), '---\n[x]: 1\nb: 3\n---\n'); assert.equal(setMarkerKeys(text, { templates: ['t'], c: 4 }), '---\ntemplates: [t]\n[x]: 1\nb: 2\nc: 4\n---\n'); }); + +test('removeMarkerKeys takes out the entry of each key it removes, and every other byte stays: comments, spacing, the body', () => { + const body = ['', '- `PLX-Repo/Verbs`: a reason.', '', '---', 'ci_registry: in the body, not frontmatter.', '']; + const text = [ + '---', + '# Written by hand; plx keeps what it does not remove.', + 'version: "0.131.0" # moved by plx update only', + 'templates:', + ' - repo-turbo # the base', + '', + '# the registry, decided once', + 'ci_registry: own # our own', + '', + "tenant: 'acme'", + 'deviations: [ PLX-Repo/Verbs ] # see below', + '---', + ...body, + ].join('\n'); + assert.equal( + removeMarkerKeys(text, ['ci_registry']), + [ + '---', + '# Written by hand; plx keeps what it does not remove.', + 'version: "0.131.0" # moved by plx update only', + 'templates:', + ' - repo-turbo # the base', + '', + '# the registry, decided once', + '', + "tenant: 'acme'", + 'deviations: [ PLX-Repo/Verbs ] # see below', + '---', + ...body, + ].join('\n'), + 'the comment above the key and the blank lines around it stay; the comment on its line goes with it', + ); + assert.equal(removeMarkerKeys(text, ['absent']), text, 'a key the marker lacks: nothing to take out'); + assert.equal(removeMarkerKeys(text, []), text); +}); + +test('removeMarkerKeys takes out a value written over several lines whole, and nothing after it', () => { + const list = '---\na: 1\nextra:\n - x\n # inside\n - y\n# about b\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(list, ['extra']), '---\na: 1\n# about b\nb: 2\n---\n', 'a block list'); + const block = '---\na: 1\nnote: |\n one\n two\n\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(block, ['note']), '---\na: 1\n\nb: 2\n---\n', 'a block scalar'); + const folded = '---\nnote: >-\n one\n two\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(folded, ['note']), '---\nb: 2\n---\n', 'a folded one'); + const flow = '---\nextra: [1,\n 2] # c\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(flow, ['extra']), '---\nb: 2\n---\n', 'a flow list over two lines'); + const plain = '---\nnote: some\n continued\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(plain, ['note']), '---\nb: 2\n---\n', 'a plain scalar over two lines'); + const map = '---\nextra:\n x: 1\n y: [2]\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(map, ['extra']), '---\nb: 2\n---\n', 'a block mapping'); + const empty = '---\na:\n# about b\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(empty, ['a']), '---\n# about b\nb: 2\n---\n', 'a key without a value'); +}); + +test('removeMarkerKeys takes out the last key and the only key, and keeps the line breaks of the page', () => { + assert.equal(removeMarkerKeys('---\na: 1\nb: [2]\n---\nbody\n', ['b']), '---\na: 1\n---\nbody\n'); + assert.equal(removeMarkerKeys('---\nb:\n - 2\n---\n', ['b']), '---\n---\n', 'the only key'); + assert.equal(removeMarkerKeys('---\r\na: 1\r\nb: 2\r\nc: 3\r\n---\r\n', ['b']), '---\r\na: 1\r\nc: 3\r\n---\r\n'); + assert.equal( + removeMarkerKeys('---\n a: 1\n b: 2\n---\n', ['a', 'b']), + '---\n---\n', + 'two keys of an indented frontmatter', + ); + assert.deepEqual(parseMarkerConfig(removeMarkerKeys('---\nversion: 0.1.0\nx: 1\n---\n', ['x'])).answers, {}); +}); + +test('removeMarkerKeys removes no reserved key, and refuses what it cannot take out without guessing', () => { + for (const key of RESERVED_KEYS) + assert.throws(() => removeMarkerKeys(`---\n${key}: [a]\n---\n`, [key]), new RegExp(`\`${key}\` is reserved`)); + assert.throws(() => removeMarkerKeys('# just prose', ['a']), /no frontmatter/); + assert.throws(() => removeMarkerKeys('---\n{a: 1}\n---\n', ['a']), /block mapping/); + assert.throws(() => removeMarkerKeys('---\na: 1\n...\n---\n', ['a']), /`\.\.\.`/); + assert.throws(() => removeMarkerKeys('---\n? a\n: 1\n---\n', ['a']), /`a` is not written as `a: value`/); + assert.throws(() => removeMarkerKeys('---\n&k a: 1\n---\n', ['a']), /`a` is not written as `a: value`/); + assert.throws(() => removeMarkerKeys('---\na: &x [1]\nb: *x\n---\n', ['a']), /`a` carries the anchor `x`/); + assert.equal(removeMarkerKeys('---\na: &x [1]\nb: *x\n---\n', ['b']), '---\na: &x [1]\n---\n', 'an alias goes'); + assert.equal(removeMarkerKeys('---\na: !!str 1\nb: 2\n---\n', ['a']), '---\nb: 2\n---\n', 'a tagged value goes'); +}); diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index ae90e5e6..70647b60 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -323,7 +323,6 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i assert.equal(repo.kind, 'repo'); assert.deepEqual(repo.files, [ '.dockerignore', - '.github/workflows/housekeeping.yml', '.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml', '.github/workflows/on_push.yml', @@ -339,6 +338,7 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i 'pnpm-workspace.yaml', 'renovate.json', 'turbo.json', + 'turbow', ]); assert.deepEqual( ran.map((r) => [r.command, ...r.args].join(' ')), @@ -375,7 +375,6 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i '.gitignore', 'PLEXUS.md', 'docker/Dockerfile', - 'docker/compose.ci.yaml', 'docker/compose.yaml', 'next.config.ts', 'package.json', @@ -384,6 +383,7 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i 'src/app/layout.tsx', 'src/app/page.tsx', 'tsconfig.json', + 'turbo.json', ]); // The doctor reads what git tracks, and lists the tasks of a mise.toml that `mise trust` (faked above) would have trusted. @@ -680,12 +680,12 @@ test('a repo made from app-nextjs alone, with the tenant it reads, raises no fin git(target, 'add', '-A'); const { facts } = await examine(new Context({}, realIo()), target, bundled.version); const report = diagnose(facts); - // Such a repo has no mise.toml, so the repo contract's checks fail; what is pinned is that the marker's - // keys, the read `tenant` among them, raise no finding against the templates. + // Such a repo has no mise.toml and no hk.pkl, so the repo contract's checks fail; what is pinned is that the + // marker's keys, the read `tenant` among them, raise no finding against the templates. const problems = report.units.flatMap((u) => u.findings.map((f) => f.problem)); - assert.ok(problems.length > 0, 'the repo contract finds the missing mise.toml'); + assert.ok(problems.length > 0, 'the repo contract finds the missing mise.toml and hk.pkl'); assert.deepEqual( - problems.filter((p) => !/mise|plx/.test(p)), + problems.filter((p) => !/mise|plx|hk\.pkl/.test(p)), [], ); assert.equal(report.units.length, 1); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts new file mode 100644 index 00000000..8a5ced48 --- /dev/null +++ b/packages/lib/src/pipeline.test.ts @@ -0,0 +1,350 @@ +// The pipeline of a repo from repo-turbo as its workflows mount it (§§ 1 and 2 +// PLX-Delivery), read from the rendered workflow templates and the reusable +// workflows of this repo: which job runs which verb, after which job, on which +// size and with which cache. No machine here runs a workflow: actionlint checks +// their syntax (check-ops), and newborns/pipeline.test.ts runs a newborn repo +// through the commands the jobs call, in the order and with the caches they +// give them. +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { type Answers, readTree, render as renderTrees } from '@plexus-ms/cli-template'; +import { parse } from 'yaml'; +import { templatesRoot } from './templatesRoot.ts'; +import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { CHOICES, distinct } from './testing/shapes.ts'; + +const WORKFLOWS = join(import.meta.dirname, '..', '..', '..', '.github', 'workflows'); + +interface Step { + id?: string; + name?: string; + uses?: string; + if?: string; + run?: string; + with?: Record; + env?: Record; + 'continue-on-error'?: unknown; +} +interface Job { + uses?: string; + needs?: string | string[]; + if?: string; + with?: Record; + 'runs-on'?: string; + concurrency?: { group: string; 'cancel-in-progress': boolean }; + steps?: Step[]; +} + +/** A reusable workflow of this repo, parsed. */ +const reusable = ( + name: string, +): { on: { workflow_call: { inputs: Record } }; jobs: Record } => + parse(readFileSync(join(WORKFLOWS, name), 'utf8')); + +/** The jobs of a rendered workflow of repo-turbo. */ +async function jobsOf(answers: Record, workflow: string): Promise> { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + return parse(textOf(result, `.github/workflows/${workflow}.yml`)).jobs; +} + +/** The reusable workflow a job calls, by its file name, without the ref. */ +const called = (job: Job | undefined): string => /\.github\/workflows\/([^@]+)@/.exec(job?.uses ?? '')?.[1] ?? ''; + +const needsOf = (job: Job | undefined): string[] => [job?.needs ?? []].flat(); + +const STRATEGIES = ['github', 'on-prem', 'hybrid']; + +test('an app repo’s on_commit runs the test job alone', async () => { + for (const ci_strategy of STRATEGIES) { + const jobs = await jobsOf({ ci_strategy }, 'on_commit'); + assert.deepEqual(Object.keys(jobs), ['test']); + assert.equal(called(jobs.test), '_check.yml'); + assert.equal(jobs.test?.with?.tasks ?? 'test', 'test'); + } +}); + +test('an app repo’s on_pr runs test, then e2e per app, and publishes and deploys nothing', async () => { + for (const ci_strategy of STRATEGIES) { + const jobs = await jobsOf({ ci_strategy }, 'on_pr'); + assert.deepEqual(Object.keys(jobs), ['test', 'e2e']); + assert.equal(called(jobs.test), '_check.yml'); + assert.equal(called(jobs.e2e), '_e2e.yml'); + assert.deepEqual(needsOf(jobs.e2e), ['test']); + assert.notEqual(jobs.e2e?.with?.deploy, true); + } +}); + +test('an app repo’s on_push runs test, e2e per app, then publish and deploy, which need both', async () => { + for (const display_versions of [false, true]) { + const jobs = await jobsOf({ display_versions }, 'on_push'); + assert.deepEqual(Object.keys(jobs), ['test', 'e2e', 'publish-deploy']); + assert.equal(called(jobs.test), '_check.yml'); + assert.equal(called(jobs.e2e), '_e2e.yml'); + assert.deepEqual(needsOf(jobs.e2e), ['test']); + assert.equal(jobs.e2e?.with?.deploy, true); + const publish = jobs['publish-deploy']; + assert.equal(called(publish), '_publish-deploy.yml'); + assert.deepEqual(needsOf(publish).sort(), ['e2e', 'test']); + for (const output of ['apps', 'deploys', 'environment']) + assert.equal(publish?.with?.[output], `\${{ needs.e2e.outputs.${output} }}`, output); + // Run on the default `success()`: an e2e job whose matrix was empty, every large job skipped by its `if`, ends + // in success, so publish runs and tags; a large job that failed or was cancelled fails or cancels it, and + // publish is skipped (on_push runs of the workflows this replaced show the first; `needs` documents the second). + assert.equal(publish?.if, undefined); + // A newer push cancels test and e2e of the older one, never a publish or a deploy. + for (const name of ['test', 'e2e']) assert.equal(jobs[name]?.concurrency?.['cancel-in-progress'], true, name); + assert.notEqual(publish?.concurrency?.['cancel-in-progress'], true); + } +}); + +test('a package repo’s on_pr is test and the changeset guard, its on_push test then publish', async () => { + const pr = await jobsOf({ publishes_packages: true }, 'on_pr'); + assert.equal(called(pr.test), '_check.yml'); + assert.equal(pr.test?.with?.tasks, 'test'); + assert.ok('changeset-status' in pr); + const push = await jobsOf({ publishes_packages: true }, 'on_push'); + assert.deepEqual(Object.keys(push), ['test', 'publish']); + assert.equal(called(push.test), '_check.yml'); + assert.equal(called(push.publish), '_publish-package.yml'); + assert.deepEqual(needsOf(push.publish), ['test']); +}); + +test('no workflow template and no reusable workflow names verify, as a phase or a verb', async () => { + for (const answers of [{}, { publishes_packages: true }, { ci_strategy: 'hybrid', display_versions: true }]) { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + assert.doesNotMatch(textOf(result, path), /verify/i, path); + } + for (const name of readdirSync(WORKFLOWS)) + assert.doesNotMatch(readFileSync(join(WORKFLOWS, name), 'utf8'), /verify/i, name); +}); + +/** The steps of a job that start a cache server, by the cache they ask for. */ +const caches = (job: Job | undefined): unknown[] => + (job?.steps ?? []).filter((s) => s.uses?.endsWith('/.github/actions/turbo-cache')).map((s) => s.with?.cache); + +/** The command lines of a job's steps, joined. */ +const runs = (job: Job | undefined): string => (job?.steps ?? []).map((s) => s.run ?? '').join('\n'); + +test('_check.yml runs the repo’s test on a medium runner with the shared cache', () => { + const workflow = reusable('_check.yml'); + assert.equal(workflow.on.workflow_call.inputs.tasks?.default, 'test'); + assert.equal(workflow.on.workflow_call.inputs.size?.default, 'medium'); + assert.deepEqual(Object.keys(workflow.jobs), ['check']); + assert.deepEqual(caches(workflow.jobs.check), ['shared']); +}); + +test('_e2e.yml plans, then per app builds the app and runs its suites on a large runner with the trusted cache alone', () => { + const { jobs } = reusable('_e2e.yml'); + assert.deepEqual(Object.keys(jobs), ['plan', 'e2e', 'cleanup']); + assert.match(runs(jobs.plan), /plx-ci plan/); + const e2e = jobs.e2e; + assert.deepEqual(needsOf(e2e), ['plan']); + assert.equal(e2e?.['runs-on'], '${{ matrix.runner }}'); + assert.deepEqual(caches(e2e), ['trusted']); + const lines = runs(e2e); + const build = lines.search(/mise run build "\$APP"/); + const suites = lines.search(/mise run e2e "\$APP"/); + assert.ok(build >= 0 && suites > build, 'build, then e2e'); + // Nothing before the build reads the shared cache: no check and no test in this job. + assert.doesNotMatch(lines, /mise run (check|test)|turbo run/); + // The key reaches the build alone. + const keyed = (e2e?.steps ?? []).filter((s) => s.run && JSON.stringify(s.env ?? {}).includes('SERVER_ACTIONS')); + assert.deepEqual( + keyed.map((s) => s.run), + ['mise run build "$APP"'], + ); + // The suites' browsers are installed only for an app that has a suite. + const browser = (e2e?.steps ?? []).find((s) => /playwright install/.test(s.run ?? '')); + assert.equal(browser?.if, "${{ join(matrix.suites, '') != '' }}"); + // In each suite's directory: two suites may pin two Playwrights, whose browsers differ. + assert.equal(browser?.env?.SUITES, "${{ join(matrix.suites, ' ') }}"); + assert.match(browser?.run ?? '', /for suite in \$SUITES; do/); + assert.deepEqual(needsOf(jobs.cleanup).sort(), ['e2e', 'plan']); +}); + +// What no machine here can show, since only a runner evaluates `if`, names an artifact and stores it: the shape of the +// step that keeps a failed suite's results. newborns/pipeline.test.ts shows what the step's path finds after a suite +// failed in a newborn, for an app with one suite and one with two. +test('_e2e.yml keeps the results of a failed suite: one upload per app and attempt, only after its E2E step failed, for a few days', () => { + const steps = reusable('_e2e.yml').jobs.e2e?.steps ?? []; + const suiteAt = steps.findIndex((s) => s.run === 'mise run e2e "$APP"'); + const uploads = steps.filter((s) => s.uses?.startsWith('actions/upload-artifact@')); + assert.equal(uploads.length, 1); + const [upload] = uploads; + // The last step, after the suites; pinned by its major, as the job's other actions of GitHub's own are. + assert.ok(suiteAt >= 0 && steps.at(-1) === upload, 'the upload follows the E2E step and ends the job'); + // v6 and later run on Node 24 and need Actions Runner 2.327.1, which the environment image passes; the major chosen. + assert.equal(upload?.uses, 'actions/upload-artifact@v7'); + // Only where the E2E step ran and failed: failure() lifts the default success(), and the step's conclusion is + // `failure` only where it failed, `skipped` where an earlier step failed, `success` on a green run. + const suite = steps[suiteAt]; + assert.equal(suite?.id, 'e2e'); + assert.equal(upload?.if, "${{ failure() && steps.e2e.conclusion == 'failure' }}"); + // The failure stays the job's: neither step continues on error. + for (const step of [suite, upload]) assert.equal(step?.['continue-on-error'], undefined, step?.name); + // Each suite's test-results/ under the suite's directory name: after the wildcard the artifact keeps the path, so + // two suites of one app never meet; the app and the attempt name the artifact, so two apps of a run, or a re-run of + // the job, never do. Hidden files stay out (Playwright's .last-run.json). + assert.equal(upload?.with?.path, 'e2e/*/test-results/'); + assert.equal(upload?.with?.name, 'e2e-${{ matrix.app }}-attempt-${{ github.run_attempt }}'); + assert.equal(upload?.with?.['include-hidden-files'], undefined); + // A suite that failed before Playwright wrote anything (no build output, no browser) uploads nothing, and says nothing. + assert.equal(upload?.with?.['if-no-files-found'], 'ignore'); + assert.equal(upload?.with?.['retention-days'], 5); +}); + +test("the suite's generated config writes its results to test-results/ beside it and no report directory, which the upload would miss", async () => { + const config = textOf(await renderBundled(['e2e-playwright'], { app: '@acme/web' }), 'playwright.config.ts'); + // Playwright's own default for outputDir: test-results beside the package.json; the list reporter writes no file. + assert.doesNotMatch(config, /outputDir/); + assert.match(config, /reporter: 'list'/); +}); + +test("_e2e.yml's header says in one line what a failed suite uploads", () => { + const header = readFileSync(join(WORKFLOWS, '_e2e.yml'), 'utf8').split('\non:')[0] ?? ''; + const lines = header.split('\n').filter((line) => /test-results/.test(line)); + assert.equal(lines.length, 1, header); + // One sentence: as generated, the error, the spec's source and the page's text; with the repo's own settings, more. + const sentence = /^# Uploaded[^.]*\.(?:\n|$)/m.exec(header.replace(/\n# (?=[^\n])/g, ' '))?.[0] ?? ''; + for (const what of ['test-results/', 'page', 'traces', 'screenshots', 'videos', 'read the repository']) + assert.ok(sentence.includes(what), `${what}: ${sentence}`); +}); + +test('_publish-deploy.yml publishes on a small runner with the trusted cache, deploys after it, and reads no candidate registry', () => { + const { jobs } = reusable('_publish-deploy.yml'); + assert.deepEqual(Object.keys(jobs), ['publish', 'display-versions', 'deploy', 'tag-display-version']); + const publish = jobs.publish; + assert.match(publish?.['runs-on'] ?? '', /'ci-small'/); + assert.deepEqual(caches(publish), ['trusted']); + // The trusted cache exactly where publish builds from the output, whose restore reads it; the plan's context is publish's. + const step = (publish?.steps ?? []).find((s) => s.uses?.endsWith('/.github/actions/turbo-cache')); + assert.equal(step?.if, "${{ matrix.build && matrix.context == 'output' }}"); + assert.match(runs(publish), /plx-ci publish "\$APP" "\$HASH" "\$GITHUB_SHA" --context "\$CONTEXT"/); + const publishStep = (publish?.steps ?? []).find((s) => /plx-ci publish/.test(s.run ?? '')); + assert.equal(publishStep?.env?.CONTEXT, '${{ matrix.context }}'); + assert.ok(needsOf(jobs.deploy).includes('publish')); + for (const name of ['_e2e.yml', '_publish-deploy.yml']) { + const text = readFileSync(join(WORKFLOWS, name), 'utf8'); + assert.doesNotMatch( + text, + /plx-ci (registry|test|build)\b|bucket-registry|CI_REGISTRY|test-|--cache-from/, + name, + ); + } +}); + +test('_e2e.yml: the plan asks the trusted cache, the large jobs are the apps with work, publish gets every app', () => { + const workflow = reusable('_e2e.yml') as ReturnType & { + on: { workflow_call: { outputs: Record } }; + }; + const { plan, e2e, cleanup } = workflow.jobs; + // The trusted cache, before the plan, and nothing else of a cache. + assert.deepEqual(caches(plan), ['trusted']); + const steps = plan?.steps ?? []; + const cacheAt = steps.findIndex((s) => s.uses?.endsWith('/.github/actions/turbo-cache')); + const planAt = steps.findIndex((s) => /plx-ci plan/.test(s.run ?? '')); + assert.ok(cacheAt >= 0 && planAt > cacheAt, 'the cache step precedes the plan'); + // § 5.3: the plan job builds, checks, tests and installs nothing that could bring an output into its tree; a trial of + // unreleased tooling installs tooling's own packages into .plx-ci, no package of the repo's. + const own = { ...plan, steps: steps.filter((s) => !(s.if ?? '').includes("inputs.tooling-ref != ''")) }; + assert.doesNotMatch(runs(own), /mise run|pnpm (install|i\b)|turbo run/); + // The large jobs: the plan's matrix, skipped as a job where it is empty, since an empty matrix is no job. + assert.equal(e2e?.if, "${{ needs.plan.outputs.matrix != '[]' }}"); + assert.equal( + (e2e as { strategy?: { matrix?: { include?: string } } }).strategy?.matrix?.include, + '${{ fromJSON(needs.plan.outputs.matrix) }}', + ); + assert.match(cleanup?.if ?? '', /needs\.plan\.outputs\.matrix == '\[\]'/); + const instances = steps.find((s) => /hybrid create-instances/.test(s.run ?? '')); + assert.equal(instances?.env?.MATRIX, '${{ steps.plan.outputs.matrix }}'); + // Publish fans out over every app, the ones without a large job among them. + assert.equal(workflow.on.workflow_call.outputs.apps?.value, '${{ jobs.plan.outputs.apps }}'); + const publish = reusable('_publish-deploy.yml').jobs.publish; + assert.match(publish?.if ?? '', /inputs\.apps != '\[\]'/); +}); + +// The callers a template renders against the reusable workflows of this repo: actionlint checks this repo's +// own workflows and never a rendered file, and the test setup has no place that lints rendered files, so the +// YAML of both sides is read here. + +interface Declared { + required?: boolean; + default?: unknown; +} +interface Callable { + on: { workflow_call: { inputs?: Record; secrets?: Record } }; +} + +/** What a caller owes and may pass a reusable workflow: its declared inputs and secrets, and the names it requires. */ +function contractOf(name: string): { + inputs: string[]; + secrets: string[]; + required: string[]; + requiredSecrets: string[]; +} { + const { inputs = {}, secrets = {} } = (parse(readFileSync(join(WORKFLOWS, name), 'utf8')) as Callable).on + .workflow_call; + const owed = (declared: Record) => + Object.entries(declared) + .filter(([, d]) => d.required === true && d.default === undefined) + .map(([key]) => key); + return { + inputs: Object.keys(inputs), + secrets: Object.keys(secrets), + required: owed(inputs), + requiredSecrets: owed(secrets), + }; +} + +test('every caller a template renders passes what the reusable workflow declares, and everything it requires', async () => { + const templates = [ + ['repo-turbo', CHOICES['repo-turbo']], + ['repo-operations', CHOICES['repo-operations']], + ] as const; + let callers = 0; + for (const [repo, choices] of templates) { + const alone = [await readTree(join(templatesRoot(), repo))]; + const beside = [...alone, await readTree(join(templatesRoot(), 'updates'))]; + for (const { answers, result } of distinct(choices, (a: Answers) => renderTrees(beside, a))) { + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) { + const jobs = (parse(textOf(result, path)) as { jobs: Record }).jobs; + for (const [name, job] of Object.entries(jobs)) { + const workflow = /^plexus-ms\/tooling\/\.github\/workflows\/([^@]+)@/.exec(job.uses ?? '')?.[1]; + if (!workflow) continue; + callers++; + const where = `${repo} ${JSON.stringify(answers)}: ${path} job ${name} calls ${workflow}`; + const contract = contractOf(workflow); + const passed = Object.keys(job.with ?? {}); + assert.deepEqual( + passed.filter((key) => !contract.inputs.includes(key)), + [], + `${where} with an input it does not declare`, + ); + assert.deepEqual( + contract.required.filter((key) => !passed.includes(key)), + [], + `${where} without an input it requires`, + ); + if (typeof job.secrets === 'object' && job.secrets !== null) { + const given = Object.keys(job.secrets); + assert.deepEqual( + given.filter((key) => !contract.secrets.includes(key)), + [], + `${where} with a secret it does not declare`, + ); + assert.deepEqual( + contract.requiredSecrets.filter((key) => !given.includes(key)), + [], + `${where} without a secret it requires`, + ); + } else if (job.secrets !== 'inherit') + assert.deepEqual(contract.requiredSecrets, [], `${where} without a secret it requires`); + } + } + } + } + assert.ok(callers > 20, `${callers} callers read`); +}); diff --git a/packages/lib/src/pull.ts b/packages/lib/src/pull.ts index e193d539..c1f4ba24 100644 --- a/packages/lib/src/pull.ts +++ b/packages/lib/src/pull.ts @@ -9,7 +9,10 @@ // when the lockfile did not refresh, that `pnpm install` is to be run after // resolving. Where the forge refuses a draft, the same pull request is // opened as an ordinary one, and the run says so; it needs a hand all the -// same. One that needs none is ready for review. +// same. One that needs none is ready for review. Below what needs a hand, the +// body names what needs none but a reviewer should know, since nothing on the +// branch shows it: the edited files the version drops, kept, and the answers +// `update` removed from the markers, a line per marker and key. // // The branch is never moved by any run, and plx never pushes to it again: it // is the human's from the moment it is on origin. A later run, scheduled or @@ -366,16 +369,24 @@ const siteIn = (dir: string): string => (dir === '.' ? 'the root' : dir); const KEPT = (version: string) => `Kept although ${version} drops them, since they were edited here`; +const REMOVED = (version: string) => `Removed from the markers, since no template asks or reads them at ${version}`; + +/** The marker of the site at `dir`, relative to the repo. */ +const markerAt = (dir: string): string => (dir === '.' ? MARKER_FILE : `${dir}/${MARKER_FILE}`); + /** * The message of the commit by which a repo takes the version: its subject, * then for each site the paths left conflicted with their markers and the * files the version drops that were edited here, kept without markers, one - * block each. A later run reads the second kind back (`keptIn`), since no - * marker shows them; the first it finds by the detector. + * block each, and one block of the answers removed from the markers, a line + * per marker and key. A later run reads the second and the third kind back + * (`keptIn`, `removedIn`), since nothing on the branch shows them; the first + * it finds by the detector. */ export function commitMessage( version: string, sites: readonly { dir: string; conflicts?: readonly string[]; kept?: readonly string[] }[], + removed: Readonly> = {}, ): string { const block = (head: string, paths: readonly string[] | undefined) => paths && paths.length > 0 ? [`${head}:\n${paths.map((p) => `- ${p}`).join('\n')}`] : []; @@ -385,9 +396,33 @@ export function commitMessage( ...block(`Conflicted, committed with their markers, at ${siteIn(s.dir)}`, s.conflicts), ...block(`${KEPT(version)}, at ${siteIn(s.dir)}`, s.kept), ]), + ...block( + REMOVED(version), + Object.entries(removed).flatMap(([dir, keys]) => keys.map((key) => `${markerAt(dir)}: ${key}`)), + ), ].join('\n\n'); } +/** The answers a commit message of `commitMessage` names removed, by the directory of the marker. */ +function removedIn(message: string): Record { + const removed: Record = {}; + let open = false; + for (const line of message.split('\n')) { + if (/^Removed from the markers, since no template asks or reads them at \S+:$/.test(line)) open = true; + else if (!open) continue; + else { + const named = /^- (.+): (\S+)$/.exec(line); + if (!named?.[1] || !named[2]) { + open = false; + continue; + } + const dir = named[1] === MARKER_FILE ? '.' : named[1].slice(0, -`/${MARKER_FILE}`.length); + removed[dir] = [...(removed[dir] ?? []), named[2]]; + } + } + return removed; +} + /** The kept files a commit message of `commitMessage` names, by site. */ export function keptIn(message: string): Record { const kept: Record = {}; @@ -420,6 +455,8 @@ export interface PullState { conflicts?: Readonly>; /** By site, the edited files the version drops, kept without markers: no hand needed, but a reviewer is told. */ kept?: Readonly>; + /** By the directory of the marker, the answers removed from it: no hand needed, but a reviewer is told. */ + removed?: Readonly>; /** The root marker names the version, and the `plx` pin does not. */ pin?: PinGap; /** The opening run: the lockfile refresh failed. A later run: run `pnpm install` and commit the lockfile. */ @@ -486,6 +523,9 @@ export function pullBody(p: PullState): string { ? `Ready for review: no tracked file holds a conflict marker, the root marker names ${p.version}, and the root \`${MISE_FILE}\` pins plx at it.${settled.length ? `\n\n${settled.join('\n')}` : ''}` : 'Nothing needs a hand: every site merged clean.'; const kept = Object.entries(p.kept ?? {}).filter(([, paths]) => paths.length > 0); + const removed = Object.entries(p.removed ?? {}).flatMap(([dir, keys]) => + keys.map((key) => `- ${code(key)} from ${code(markerAt(dir))}.`), + ); return [ head, ...(kept.length > 0 @@ -495,6 +535,7 @@ export function pullBody(p: PullState): string { .join('\n')}`, ] : []), + ...(removed.length > 0 ? [`${REMOVED(p.version)}:\n${removed.join('\n')}`] : []), `Plexus ${p.version} (§ 1.5 PLX): the templates at ${p.sites.map(site).join(', ')}, the version in the root marker, the lockfile where manifests moved, and the workflow refs.`, p.note, ].join('\n\n'); @@ -517,6 +558,8 @@ interface AtTip { pin?: PinGap; /** By site, the edited files the version drops, as plx's commit on the branch names them. */ kept: Record; + /** By the directory of the marker, the answers plx's commit removed that the tip's marker does not hold again. */ + removed: Record; /** No marker, the root marker names the version, and the pin does too. */ ready: boolean; /** Whether the body asks for `pnpm install` and the lockfile. */ @@ -526,8 +569,9 @@ interface AtTip { /** * The version branch's tip, read by hash: the detector over its tracked * files, its sites, every marker it holds that lists at least one template, - * whether its root marker names the version and its `plx` pin too, and the - * kept files plx's commit names (`comparedAt`) that the tip still holds. The lockfile is asked for + * whether its root marker names the version and its `plx` pin too, the kept + * files plx's commit names (`comparedAt`) that the tip still holds, and the + * answers it names removed that the tip's markers do not hold again. The lockfile is asked for * where the tip holds one and the pull request is not ready, or holds commits * beyond the one plx made (somebody resolved by hand), as the forge counts * them. @@ -559,7 +603,16 @@ async function readTip(ctx: Context, consumer: Consumer, version: string, tip: s .map(([dir, paths]) => [dir, paths.filter((p) => files.has(p))] as const) .filter(([, paths]) => paths.length > 0), ); - return { tip, sites, marked, behind, ...(pin ? { pin } : {}), kept, ready, lockfile }; + // An answer somebody has since put back on the branch is no longer removed. + const removed = Object.fromEntries( + Object.entries(removedIn(compared.message)) + .map(([dir, keys]) => { + const answers = held.find((s) => s.dir === dir)?.config?.answers ?? {}; + return [dir, keys.filter((key) => !Object.hasOwn(answers, key))] as const; + }) + .filter(([, keys]) => keys.length > 0), + ); + return { tip, sites, marked, behind, ...(pin ? { pin } : {}), kept, removed, ready, lockfile }; } /** What a later run found at the tip, as the run names it. */ @@ -613,6 +666,7 @@ export async function revisit( behind, ...(pin ? { pin } : {}), kept: at.kept, + removed: at.removed, lockfile: at.lockfile, checked: true, note: REVISITED, @@ -698,6 +752,7 @@ export async function openLate( behind, ...gap, kept: at.kept, + removed: at.removed, lockfile: at.lockfile, checked: true, note: OPENED_LATE, diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index 796f2248..70172077 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { generatedFrom, pathsOf, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ const toolsOf = (mise: string): string[] => @@ -43,17 +43,28 @@ test('an infrastructure layer adds its playbook', async () => { assert.match(textOf(result, 'inventory/hosts.yml'), /^proxmox:$/m); }); -test('runners of the tenant’s own add the CI playbook and its housekeeping', async () => { - for (const ci_strategy of ['on-prem', 'hybrid']) { - const result = await render({ ci_strategy }); - assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), [...COMMON, '.github/workflows/housekeeping.yml', 'ci.yml'].sort(), ci_strategy); - } +test('runners of the tenant’s own add the CI playbook, and a hybrid strategy its instance sweep', async () => { + const onPrem = await render({ ci_strategy: 'on-prem' }); + assert.deepEqual(onPrem.errors, []); + assert.deepEqual(pathsOf(onPrem), [...COMMON, 'ci.yml'].sort()); + const hybrid = await render({ ci_strategy: 'hybrid' }); + assert.deepEqual(hybrid.errors, []); + assert.deepEqual(pathsOf(hybrid), [...COMMON, '.github/workflows/housekeeping.yml', 'ci.yml'].sort()); }); -test('a registry of its own adds the housekeeping alone', async () => { - const result = await render({ ci_registry: 'own' }); - assert.deepEqual(pathsOf(result), [...COMMON, '.github/workflows/housekeeping.yml'].sort()); +test('the housekeeping mount sweeps instances and holds nothing of the registry pair or its question', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid'] as const) { + const result = await render({ ci_strategy, alerts_email: 'ops@acme.example' }); + for (const path of pathsOf(result)) + assert.doesNotMatch( + textOf(result, path), + /ci_registry|CI_REGISTRY|plx-ci registry|registry rotate|bucket-registry|:500[01]\b|registry buckets/, + `${path} ${ci_strategy}`, + ); + } + const text = textOf(await render({ ci_strategy: 'hybrid' }), '.github/workflows/housekeeping.yml'); + assert.doesNotMatch(text, /registry:/); + assert.match(text, /alerts-email: /); }); test('the answers are the questions’ defaults, and the org follows the tenant', async () => { @@ -62,12 +73,10 @@ test('the answers are the questions’ defaults, and the org follows the tenant' github_org: 'acme', infrastructure: false, ci_strategy: 'github', - ci_registry: 'ghcr', ci_overlay: 'none', }); const hybrid = await render({ ci_strategy: 'hybrid', github_org: 'acme-gh', alerts_email: 'ops@acme.example' }); assert.equal(hybrid.answers.github_org, 'acme-gh'); - assert.equal(hybrid.answers.ci_registry, 'own'); assert.equal(hybrid.answers.alerts_email, 'ops@acme.example'); }); @@ -82,7 +91,7 @@ test('the tenant is required, and the error carries its help', async () => { }); test('only a choice of the question is an answer', async () => { - for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }, { ci_registry: 'docker' }]) { + for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }]) { assert.equal((await render(answers)).errors.length, 1); } }); @@ -138,3 +147,54 @@ test('a generated file says its template lives in tooling', async () => { path, ); }); + +// --- the five verbs and the hooks (as repo-turbo has them) -------------------------------- + +const SHAPES = [{}, { infrastructure: true, ci_strategy: 'hybrid' }, { ci_strategy: 'on-prem', ci_overlay: 'netbird' }]; + +test('a repo has the five verbs as root tasks, each taking an optional name, and no verify', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + const tasks = tasksOf(mise); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) { + assert.ok(tasks.includes(verb), `${verb} ${JSON.stringify(answers)}`); + assert.match(taskOf(mise, verb), /^usage = .*\[name\]/m, verb); + } + assert.ok(!tasks.includes('verify'), 'no verify task'); + } +}); + +test('no rendered file mentions verify', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of pathsOf(result)) assert.doesNotMatch(textOf(result, path), /verify/i, path); + } +}); + +test('dev, build and e2e are no-ops that pass; test runs check first and then has nothing to run', async () => { + const mise = textOf(await render(), 'mise.toml'); + for (const verb of ['dev', 'build', 'e2e']) assert.match(runOf(mise, verb), /^run = 'echo "\w+: nothing/, verb); + assert.match(runOf(mise, 'test'), /^run = \[\s*'mise run check',\s*'echo "test: nothing/); + assert.doesNotMatch(runOf(mise, 'e2e'), /mise run/, 'e2e runs alone'); +}); + +test('pre-commit runs lint; pre-push runs test, which runs check first', async () => { + const hk = textOf(await render(), 'hk.pkl'); + const hook = (name: string) => new RegExp(`\\["${name}"\\] \\{([\\s\\S]*?)\\n \\}`).exec(hk)?.[1] ?? ''; + assert.match(hook('pre-commit'), /fix = "mise :lint --write \{\{ files \}\}"/); + assert.doesNotMatch(hook('pre-commit'), /mise :(check|test)/); + assert.match(hook('pre-push'), /mise :test/); + assert.doesNotMatch(hook('pre-push'), /mise :check/); +}); + +test('the workflows call test, which runs check first, and only tasks the repo has', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + const tasks = tasksOf(textOf(result, 'mise.toml')); + for (const path of ['.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml']) { + const asked = [...textOf(result, path).matchAll(/^ +tasks: (.+)$/gm)].map((m) => m[1]); + assert.deepEqual(asked, ['test'], path); + assert.ok(tasks.includes('test')); + } + } +}); diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 0e509598..925e57b7 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -1,6 +1,9 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { test } from 'node:test'; -import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { templatesRoot } from './templatesRoot.ts'; +import { generatedFrom, pathsOf, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ const toolsOf = (mise: string): string[] => @@ -23,6 +26,7 @@ const COMMON = [ 'packages/.gitkeep', 'pnpm-workspace.yaml', 'turbo.json', + 'turbow', ]; test('an app repo is rendered with its apps directory and its commit workflows', async () => { @@ -30,13 +34,7 @@ test('an app repo is rendered with its apps directory and its commit workflows', assert.deepEqual(result.errors, []); assert.deepEqual( pathsOf(result), - [ - ...COMMON, - '.dockerignore', - '.github/workflows/housekeeping.yml', - '.github/workflows/on_commit.yml', - 'apps/.gitkeep', - ].sort(), + [...COMMON, '.dockerignore', '.github/workflows/on_commit.yml', 'apps/.gitkeep'].sort(), ); }); @@ -46,14 +44,19 @@ test('a package repo has changesets instead of apps and the commit workflows', a assert.deepEqual(pathsOf(result), [...COMMON, '.changeset/config.json'].sort()); }); -test('the housekeeping workflow follows the registry, which follows the strategy', async () => { - const github = await render({ ci_strategy: 'github' }); - assert.equal(github.answers.ci_registry, 'ghcr'); - assert.ok(github.files.has('.github/workflows/housekeeping.yml')); - const hybrid = await render({ ci_strategy: 'hybrid', alerts_email: 'ops@acme.example' }); - assert.equal(hybrid.answers.ci_registry, 'own'); - assert.equal(hybrid.answers.alerts_email, 'ops@acme.example'); - assert.ok(!hybrid.files.has('.github/workflows/housekeeping.yml')); +test('no repo, in any shape, holds a housekeeping workflow or anything of the registry pair and its question', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid']) + for (const publishes_packages of [false, true]) { + const result = await render({ ci_strategy, publishes_packages }); + const shape = `${ci_strategy} ${publishes_packages}`; + assert.ok(!result.files.has('.github/workflows/housekeeping.yml'), shape); + for (const path of pathsOf(result)) + assert.doesNotMatch( + textOf(result, path), + /ci_registry|CI_REGISTRY|plx-ci registry|registry rotate|bucket-registry|:500[01]\b|test-|--cache-(from|to)/, + `${path} ${shape}`, + ); + } }); test('the answers of a plain app repo are the questions’ defaults', async () => { @@ -63,16 +66,15 @@ test('the answers of a plain app repo are the questions’ defaults', async () = publishes_packages: false, private_packages_scope: '', ci_strategy: 'github', - ci_registry: 'ghcr', ci_overlay: 'none', display_versions: false, + postgres: '', }); }); -test('a package repo is asked where it publishes and nothing about CI registries', async () => { +test('a package repo is asked where it publishes', async () => { const result = await render({ publishes_packages: true }); assert.equal(result.answers.package_registry, 'npm'); - assert.ok(!('ci_registry' in result.answers)); assert.ok(!('display_versions' in result.answers)); const github = await render({ publishes_packages: true, package_registry: 'github' }); assert.match(textOf(github, 'PLEXUS.md'), /the forge's package registry, private to the tenant,/); @@ -111,7 +113,7 @@ test('the major of a display version is 1 or higher', async () => { }); test('only a choice of the question is an answer', async () => { - for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }, { ci_registry: 'docker' }]) { + for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }]) { assert.equal((await render(answers)).errors.length, 1); } }); @@ -170,3 +172,189 @@ test('a generated file says its template lives in tooling', async () => { test('no turbo input names an answers file', async () => { assert.doesNotMatch(textOf(await render(), 'turbo.json'), /answers/); }); + +// The five verbs, the task graph and the hooks (§ 1 and § 6 of the decisions, PLX-Repo). + +/** The tasks of a rendered `turbo.json`. */ +const turboOf = (result: Awaited>) => + // Turbo reads comments in turbo.json, on lines of their own here. + JSON.parse(textOf(result, 'turbo.json').replace(/^\s*\/\/.*$/gm, '')).tasks as Record< + string, + { dependsOn?: string[]; inputs?: string[]; env?: string[]; passThroughEnv?: string[]; cache?: boolean } + >; + +const SHAPES = [{}, { publishes_packages: true }]; + +test('a repo has the five verbs as root tasks, each taking an optional name, and no verify', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + const tasks = tasksOf(mise); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) { + assert.ok(tasks.includes(verb), `${verb} ${JSON.stringify(answers)}`); + assert.match(taskOf(mise, verb), /^usage = .*\[name\]/m, verb); + } + assert.ok(!tasks.includes('verify'), 'no verify task'); + } +}); + +test('no rendered file mentions verify', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of pathsOf(result)) assert.doesNotMatch(textOf(result, path), /verify/i, path); + } +}); + +test('check is lint, then plx doctor, then the check of Turbo', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'check'); + const at = (needle: RegExp) => run.search(needle); + assert.ok(at(/mise run lint/) >= 0 && at(/plx doctor/) > at(/mise run lint/), 'doctor after lint'); + assert.ok(at(/turbow \w+ run check/) > at(/plx doctor/), 'turbo after doctor'); + assert.doesNotMatch(run, /turbow \w+ run (test|build|e2e)/); + } +}); + +test('test runs check, then the test of Turbo, in a run of its own', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'test'); + assert.ok( + run.search(/mise run check/) >= 0 && run.search(/turbow \w+ run test/) > run.search(/mise run check/), + run, + ); + assert.doesNotMatch(run, /turbow \w+ run (check|build|e2e)/); + } +}); + +test('e2e runs the e2e of Turbo alone: it neither tests nor checks', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'e2e'); + assert.match(run, /turbow \w+ run e2e/); + assert.doesNotMatch(run, /mise run (test|check)|turbow \w+ run (check|test|build)/); + } +}); + +test('the dependsOn of the graph hold data dependencies only', async () => { + for (const answers of SHAPES) { + const tasks = turboOf(await render(answers)); + for (const task of ['build', 'check', 'test', 'e2e']) assert.deepEqual(tasks[task]?.dependsOn, ['^build'], task); + assert.equal(tasks.dev?.cache, false); + assert.equal(tasks.dev?.dependsOn, undefined); + } +}); + +test('test files are no input of build, and are an input of check and test', async () => { + const tasks = turboOf(await render()); + assert.deepEqual( + tasks.build?.inputs?.filter((input) => input.startsWith('!') && /test|spec|tests|vitest/.test(input)), + ['!**/*.{test,spec}.*', '!**/{__tests__,__snapshots__}/**', '!tests/**', '!{vitest,playwright,jest}*.config.*'], + ); + for (const task of ['check', 'test', 'e2e']) + assert.ok(!tasks[task]?.inputs?.some((input) => /test|spec|vitest/.test(input)), task); +}); + +test('the platform is mise’s, in the env of no task of the root and in the global env of no one', async () => { + const result = await render(); + assert.match(textOf(result, 'mise.toml'), /^PLX_PLATFORM = "\{\{ ?os\(\) ?\}\}-\{\{ ?arch\(\) ?\}\}"$/m); + assert.doesNotMatch(textOf(result, 'turbo.json'), /PLX_PLATFORM|globalEnv|globalPassThroughEnv/); +}); + +test('no PostgreSQL is asked for unanswered: no pin, no variable, nothing declared by test and e2e', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + assert.doesNotMatch(textOf(result, 'mise.toml'), /conda|postgres/i); + assert.doesNotMatch(textOf(result, 'turbo.json'), /POSTGRES/); + const tasks = turboOf(result); + for (const task of ['test', 'e2e']) assert.equal(tasks[task]?.env, undefined, task); + } +}); + +test('answered, the version is pinned, its major is a variable of mise, and test and e2e declare it', async () => { + for (const [postgres, major] of [ + ['18.6', '18'], + ['17.12', '17'], + ] as const) + for (const answers of SHAPES) { + const result = await render({ ...answers, postgres }); + assert.deepEqual(result.errors, []); + const mise = textOf(result, 'mise.toml'); + assert.equal(toolsOf(mise).at(-1), '"conda:postgresql"'); + assert.match(mise, new RegExp(`^"conda:postgresql" = "${postgres.replace('.', '\\.')}"$`, 'm')); + assert.match(mise, new RegExp(`^PLX_POSTGRES_MAJOR = "${major}"$`, 'm')); + const tasks = turboOf(result); + for (const task of ['test', 'e2e']) assert.deepEqual(tasks[task]?.env, ['PLX_POSTGRES_MAJOR'], task); + for (const task of ['build', 'check', 'dev']) assert.equal(tasks[task]?.env, undefined, task); + } +}); + +test('the major is derived from the answer and asked of no one', async () => { + const result = await render({ postgres: '18.6' }); + assert.equal(result.answers.postgres, '18.6'); + assert.deepEqual( + Object.keys(result.answers).filter((key) => /postgres/i.test(key)), + ['postgres'], + ); + const questions = readFileSync(join(templatesRoot(), 'repo-turbo', 'template.yml'), 'utf8'); + assert.doesNotMatch(questions, /postgres_major/i); +}); + +test('an answer is an exact version, major and minor, or empty', async () => { + for (const postgres of ['', '18.6', '17.12', '9.6', '18.0', '10.10']) + assert.deepEqual((await render({ postgres })).errors, [], postgres); + for (const postgres of [ + '18', + '18.6.1', + 'v18.6', + '18.x', + '18.', + '.6', + ' 18.6', + '18.6\n', + 'latest', + '18-6', + '018.6', + '18.06', + '00.6', + '18.00', + '٣.٤', + '18.6', + ]) { + const { errors } = await render({ postgres }); + assert.equal(errors.length, 1, JSON.stringify(postgres)); + assert.equal(errors[0]?.question, 'postgres', JSON.stringify(postgres)); + assert.match(errors[0]?.message ?? '', /An exact version, major and minor, as in 18\.6, or empty/); + } +}); + +test('no passthrough variable changes what is tested', async () => { + const tasks = turboOf(await render({ postgres: '18.6' })); + for (const task of ['test', 'e2e']) + for (const name of tasks[task]?.passThroughEnv ?? []) + assert.doesNotMatch(name, /DATABASE|URL|E2E_|POSTGRES/, `${task} passes ${name} through`); +}); + +test('pre-commit fixes lint on the staged files, then checks; pre-push tests', async () => { + const hk = textOf(await render(), 'hk.pkl'); + const hook = (name: string) => new RegExp(`\\["${name}"\\] \\{([\\s\\S]*?)\\n \\}`).exec(hk)?.[1] ?? ''; + const commit = hook('pre-commit'); + assert.match(commit, /fix = "mise :lint --write \{\{ files \}\}"/); + assert.ok(commit.indexOf('["check"]') > commit.indexOf('["lint"]'), 'check follows lint'); + assert.match(commit, /\["check"\] \{[^}]*mise :check/); + assert.match( + commit, + /\["check"\] \{\s*depends = "lint"/, + 'check waits for the fixing lint, which hk would run beside it', + ); + const push = hook('pre-push'); + assert.match(push, /mise :test/); + assert.doesNotMatch(push, /mise :check/); +}); + +test('a workflow asks _check.yml only for tasks the repo has', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + const tasks = tasksOf(textOf(result, 'mise.toml')); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + for (const [, asked] of textOf(result, path).matchAll(/^ +tasks: (.+)$/gm)) + for (const task of (asked ?? '').split(' ')) assert.ok(tasks.includes(task), `${path} asks for ${task}`); + } +}); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts new file mode 100644 index 00000000..079e4e76 --- /dev/null +++ b/packages/lib/src/repoTurboCache.test.ts @@ -0,0 +1,378 @@ +// The two remote caches of a repo-turbo repo (Decisions § 5): the verbs reach +// Turbo through `turbow`, which the template renders beside `mise.toml`, and +// which picks the cache server for each one. Here `turbow` is run as the tasks +// run it, in a git checkout with an origin, with a stub `turbo` first on PATH +// that prints every TURBO_ variable and argument it was handed, and with a +// health endpoint on a free loopback port standing in for a cache server; the +// newborn test (newborns/) runs it against a real server and an S3 stand-in. +// A job of the forge is GITHUB_ACTIONS=true; CI alone is any machine's. +import assert from 'node:assert/strict'; +import { execFile, execFileSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { parse } from 'yaml'; +import { pathsOf, renderBundled, runOf, textOf } from './testing/bundled.ts'; + +const SHAPES = [{}, { publishes_packages: true }]; +const render = (answers: Record = {}) => renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + +let scratch = ''; +let turbow = ''; +let server: Server; +let answering = ''; +let silent = ''; + +/** A loopback port nothing listens on: taken from the system, then given back. */ +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +before(async () => { + scratch = mkdtempSync(join(tmpdir(), 'plx-turbow-')); + turbow = textOf(await render(), 'turbow'); + // The stub prints what turbow hands to Turbo, every TURBO_ variable and each argument on a line, and exits + // with STUB_EXIT. + mkdirSync(join(scratch, 'bin')); + writeFileSync( + join(scratch, 'bin', 'turbo'), + [ + '#!/bin/sh', + 'echo turbo-ran', + "env | grep '^TURBO_' | sed 's/^/turbo-env /'", + 'for a in "$@"; do echo "turbo-arg $a"; done', + 'exit "$STUB_EXIT"', + '', + ].join('\n'), + ); + chmodSync(join(scratch, 'bin', 'turbo'), 0o755); + server = createServer((req, res) => { + res.statusCode = req.url === '/management/health' ? 200 : 404; + res.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + answering = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + silent = `http://127.0.0.1:${await freePort()}`; +}); + +after(async () => { + await new Promise((resolve) => server.close(() => resolve())); + rmSync(scratch, { recursive: true, force: true }); +}); + +let checkouts = 0; +/** A checkout with `turbow` at its root, and `origin` at `remote` when one is given. */ +function checkout(remote?: string): string { + const dir = join(scratch, `checkout-${checkouts++}`); + mkdirSync(dir); + writeFileSync(join(dir, 'turbow'), turbow); + chmodSync(join(dir, 'turbow'), 0o755); + execFileSync('git', ['init', '-q'], { cwd: dir }); + if (remote) execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: dir }); + return dir; +} + +interface Ran { + status: number | null; + /** What the stub turbo was handed, or undefined when turbow never started it. */ + turbo?: { env: Record; args: string[] }; + /** The lines turbow wrote itself. */ + said: string[]; +} + +const ARGS = ['run', 'check', '--filter={./apps/web}...']; + +/** + * `./turbow run check --filter=…` in `dir`, as a task runs it, with + * nothing of the caller's CI, Turbo or cache variables but `env`: a test run + * in a job of the forge must see what one on a laptop sees. + */ +async function turbowIn(dir: string, cache: string, env: Record = {}, args = ARGS): Promise { + const base = Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => name !== 'CI' && name !== 'GITHUB_ACTIONS' && !/^(TURBO_|PLX_TURBO_)/.test(name), + ), + ); + // Not spawnSync: the stand-in server answers from this process, whose loop must keep turning meanwhile. + const ran = await new Promise<{ status: number | null; output: string }>((resolve) => { + execFile( + './turbow', + [cache, ...args], + { cwd: dir, env: { ...base, STUB_EXIT: '0', PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env } }, + (error, stdout, stderr) => + resolve({ + status: error ? (typeof error.code === 'number' ? error.code : 1) : 0, + output: `${stdout}${stderr}`, + }), + ); + }); + const lines = ran.output.split('\n').filter(Boolean); + const ours = (line: string) => /^turbo-(ran|env|arg)\b/.test(line); + const turbo = lines.includes('turbo-ran') + ? { + env: Object.fromEntries( + lines + .filter((line) => line.startsWith('turbo-env ')) + .map((line) => line.slice('turbo-env '.length)) + .map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)]), + ), + args: lines.filter((line) => line.startsWith('turbo-arg ')).map((line) => line.slice('turbo-arg '.length)), + } + : undefined; + return { status: ran.status, turbo, said: lines.filter((line) => !ours(line)) }; +} + +const REMOTE = 'git@github.com:acme/web.git'; +/** What Turbo gets where it runs without a remote cache: no server, no team, no token, and the local cache alone. */ +const UNCACHED = { TURBO_API: '', TURBO_TEAM: '', TURBO_TOKEN: '', TURBO_CACHE: 'local:rw' }; +/** What a caller's shell or a machine may hold that would send artifacts elsewhere, or otherwise, than turbow says. */ +const STRAY = { + TURBO_API: 'https://example.invalid', + TURBO_TEAM: 'someone', + TURBO_TEAMID: 'team_someone', + TURBO_TOKEN: 'secret', + TURBO_CACHE: 'remote:r', + TURBO_REMOTE_CACHE_SIGNATURE_KEY: 'a-key', + TURBO_REMOTE_CACHE_READ_ONLY: 'true', + TURBO_PREFLIGHT: 'true', + TURBO_REMOTE_ONLY: 'true', +}; +/** A job of the forge, which sets both. */ +const JOB = { GITHUB_ACTIONS: 'true', CI: 'true' }; + +test('turbow is rendered in every repo, executable, beside mise.toml', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + assert.equal(result.tree.get('turbow')?.mode, 0o100755, JSON.stringify(answers)); + assert.match(textOf(result, 'turbow'), /^#!\/bin\/sh\n/); + } +}); + +test('check and test reach Turbo through the shared cache, build and e2e through the trusted one, dev through none', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + for (const [verb, cache] of [ + ['check', 'shared'], + ['test', 'shared'], + ['build', 'trusted'], + ['e2e', 'trusted'], + ] as const) { + const run = runOf(mise, verb); + assert.match(run, new RegExp(`^\\./turbow ${cache} run ${verb}\\b`, 'm'), `${verb} ${JSON.stringify(answers)}`); + assert.doesNotMatch(run, /^turbo /m, `${verb} calls no turbo but through turbow`); + } + assert.doesNotMatch(runOf(mise, 'dev'), /turbow/, 'dev, whose task is never cached, asks for no cache'); + } +}); + +test('outside a job the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', async () => { + assert.match(turbow, /\$\{PLX_TURBO_SHARED:-http:\/\/127\.0\.0\.1:8585\}/); +}); + +test('outside a job, CI set or not, with the shared server answering, every verb uses it, as the repo’s owner-repo, and nothing else reaches Turbo', async () => { + const dir = checkout(REMOTE); + for (const ci of [{}, { CI: 'true' }]) + for (const cache of ['shared', 'trusted']) { + const ran = await turbowIn(dir, cache, { ...STRAY, ...ci, PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, { + TURBO_API: answering, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'local', + TURBO_CACHE: 'local:rw,remote:rw', + }); + assert.deepEqual(ran.turbo?.args, ARGS); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', new RegExp(`shared remote cache at ${answering.replaceAll('.', '\\.')}`)); + } +}); + +test('outside a job, with no server answering, every verb runs without a remote cache, tells Turbo so, and says so in one line', async () => { + const dir = checkout(REMOTE); + for (const shared of [silent, 'none']) + for (const cache of ['shared', 'trusted']) { + const ran = await turbowIn(dir, cache, { ...STRAY, PLX_TURBO_SHARED: shared }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, UNCACHED); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + } +}); + +test('in a job, build and e2e reach the trusted server the job started, with the remote cache alone, and check and test the shared one', async () => { + const dir = checkout('https://github.com/acme/web'); + const job = { + ...STRAY, + ...JOB, + PLX_TURBO_SHARED: silent, + PLX_TURBO_SHARED_TOKEN: 'shared-job-token', + PLX_TURBO_TRUSTED: answering, + PLX_TURBO_TRUSTED_TOKEN: 'trusted-job-token', + }; + const trusted = await turbowIn(dir, 'trusted', job); + assert.equal(trusted.status, 0, trusted.said.join('\n')); + // The local cache may hold what a shared run restored in this checkout; a trusted run never reads it. + assert.deepEqual(trusted.turbo?.env, { + TURBO_API: answering, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'trusted-job-token', + TURBO_CACHE: 'remote:rw', + }); + const shared = await turbowIn(dir, 'shared', job); + assert.deepEqual(shared.turbo?.env, { + TURBO_API: silent, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'shared-job-token', + TURBO_CACHE: 'local:rw,remote:rw', + }); + // A job with the trusted server alone, as the e2e job is: check and test find no shared server there. + const alone = await turbowIn(dir, 'shared', { ...JOB, PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 't' }); + assert.equal(alone.status, 0, alone.said.join('\n')); + assert.deepEqual(alone.turbo?.env, UNCACHED); + assert.match(alone.said.join('\n'), /without a remote cache/); +}); + +test('TURBO_FORCE reaches Turbo as it was given, which forces whatever TURBO_CACHE says, in every case', async () => { + const dir = checkout(REMOTE); + for (const force of ['true', '1']) + for (const [cache, env, setting] of [ + ['shared', { PLX_TURBO_SHARED: 'none' }, 'local:rw'], + ['shared', { PLX_TURBO_SHARED: answering }, 'local:rw,remote:rw'], + ['trusted', { ...JOB, PLX_TURBO_TRUSTED: answering }, 'remote:rw'], + ] as const) { + const ran = await turbowIn(dir, cache, { ...env, TURBO_FORCE: force }); + assert.equal(ran.turbo?.env.TURBO_FORCE, force, `${force} ${cache} ${setting}`); + assert.equal(ran.turbo?.env.TURBO_CACHE, setting, `${force} ${cache}`); + } +}); + +test('in a job without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { + const dir = checkout(REMOTE); + for (const env of [{ PLX_TURBO_SHARED: answering, PLX_TURBO_SHARED_TOKEN: 't' }, {}]) { + const ran = await turbowIn(dir, 'trusted', { ...JOB, ...env }); + assert.notEqual(ran.status, 0); + assert.equal(ran.turbo, undefined, 'Turbo never ran'); + assert.match(ran.said.join('\n'), /trusted cache server/); + assert.match(ran.said.join('\n'), /PLX_TURBO_TRUSTED/); + } +}); + +test('CI alone is no job: build and e2e on a machine with CI=true use the shared server, and fail for want of none', async () => { + const dir = checkout(REMOTE); + for (const ci of ['true', '1', 'yes']) { + const ran = await turbowIn(dir, 'trusted', { CI: ci, PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.equal(ran.turbo?.env.TURBO_API, answering, ci); + } +}); + +test('in a job where the tenant has no bucket, every verb runs without a remote cache and says so in one line', async () => { + const dir = checkout(REMOTE); + for (const cache of ['shared', 'trusted']) { + const ran = await turbowIn(dir, cache, { ...JOB, PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, UNCACHED); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + } +}); + +test('turbow exits with Turbo’s status and hands it every argument as it was given', async () => { + const dir = checkout(REMOTE); + const failed = await turbowIn(dir, 'shared', { PLX_TURBO_SHARED: answering, STUB_EXIT: '3' }); + assert.equal(failed.status, 3); + const args = ['run', 'check', '--filter=a b', '', '--summarize=two spaces']; + assert.deepEqual((await turbowIn(dir, 'shared', { PLX_TURBO_SHARED: 'none' }, args)).turbo?.args, args); +}); + +test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', async () => { + for (const remote of [ + 'git@github.com:acme/web.git', + 'git@github.com:Acme/Web', + 'https://github.com/acme/web', + 'https://github.com/acme/web.git', + 'https://github.com/acme/web/', + 'ssh://git@github.com/acme/web.git', + 'HTTPS://GITHUB.COM/ACME/WEB.GIT', + 'ssh://git@github.com:2222/acme/web', + 'https://user:token@github.com/acme/web.git', + ]) { + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + assert.equal(ran.turbo?.env.TURBO_TEAM, 'acme-web', remote); + } +}); + +test('the team holds only [a-z0-9._-], every other character a dash, and a nested group keeps its last two names', async () => { + for (const [remote, team] of [ + ['https://git.example.com/Group/Sub%20Group/re po.git', 'sub-20group-re-po'], + ['https://git.example.com/o/r#x?y.git', 'o-r-x-y'], + ['https://git.example.com/ä/ü.git', 'o-r'], + ['https://git.example.com/group/sub/repo.git', 'sub-repo'], + ['git@git.example.com:acme/web.v2_x.git', 'acme-web.v2_x'], + ] as const) { + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + if (team === 'o-r') assert.match(ran.turbo?.env.TURBO_TEAM ?? '', /^-+--+$/, remote); + else assert.equal(ran.turbo?.env.TURBO_TEAM, team, remote); + } +}); + +test('a checkout without origin, or whose origin names no owner, has no team, and runs without a remote cache', async () => { + for (const [remote, why] of [ + [undefined, /origin/], + ['git@git.example.com:repo.git', /owner/], + ['https://git.example.com/repo.git', /owner/], + ] as const) { + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, UNCACHED, String(remote)); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + assert.match(ran.said[0] ?? '', why); + } +}); + +// Where a job gets its cache server: the step turbo-cache of this repo, which _check.yml starts for every repo. + +/** The job `name` of a rendered workflow, as text, up to the next job. */ +const jobOf = (workflow: string, name: string): string => + new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [\\w-]+:\\n|(?![\\s\\S]))`, 'm').exec(workflow)?.[1] ?? ''; + +test('no workflow of a repo asks for the cache', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid']) + for (const answers of SHAPES) { + const result = await render({ ...answers, ci_strategy }); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + assert.doesNotMatch(textOf(result, path), /turbo-cache/, path); + } +}); + +test('a package repo’s test job hands the vault’s token to _check.yml, as an app repo’s does', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of ['.github/workflows/on_pr.yml', '.github/workflows/on_push.yml']) { + const check = jobOf(textOf(result, path), 'test'); + assert.match(check, /_check\.yml@/, path); + assert.match(check, /op-service-account-token: \$\{\{ secrets\.OP_SERVICE_ACCOUNT_TOKEN \}\}/, path); + } + } +}); + +test('_check.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { + const workflow = parse( + readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_check.yml'), 'utf8'), + ); + assert.ok(!('turbo-cache' in workflow.on.workflow_call.inputs), 'no input switches the cache'); + const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.check.steps; + const cache = steps.filter((step) => step.uses?.includes('turbo-cache')); + assert.equal(cache.length, 1); + assert.equal(cache[0]?.uses, '$/.github/actions/turbo-cache'); + assert.equal(cache[0]?.with?.cache, 'shared'); + assert.equal(cache[0]?.if, undefined, 'started for every repo'); +}); diff --git a/packages/lib/src/requirements.test.ts b/packages/lib/src/requirements.test.ts index ae2338ed..a6bee800 100644 --- a/packages/lib/src/requirements.test.ts +++ b/packages/lib/src/requirements.test.ts @@ -13,7 +13,7 @@ import { requirementName, scanPage, } from './requirements.ts'; -import { bundledIndex } from './standardIndex.ts'; +import { bundledIndex, renderStandardIndex, STANDARD_INDEX_FILE } from './standardIndex.ts'; import { fakeIo, type Tree } from './testing/fakeIo.ts'; // Citations, names and identifiers are put together at run time: this repo's @@ -404,6 +404,27 @@ test('checkRepo resolves against a compendium checkout when given one', async () assert.equal(lintCitations(`${name('App', 'Port')}`, 'notes.txt', new Set(bundledIndex().citable)).length, 1); }); +test('a requirement name the compendium has dropped fails where a file still cites it, never in the index that named it', async () => { + const gone = name('App', 'Gone'); + // The index of the version before, as ship wrote it, named a requirement the compendium being cut no longer has. + const previous = renderStandardIndex({ + version: '0.1.0', + citable: [cite('1', 'PLX-App'), name('App', 'Port'), gone], + }); + const repo = (notes: string): Tree => { + const dirs = STANDARD_INDEX_FILE.split('/'); + const file = dirs.pop() ?? ''; + const index = dirs.reduceRight((inner, dir) => ({ [dir]: inner }), { [file]: previous }); + return { ...compendium(), r: { ...index, 'notes.txt': notes } }; + }; + const check = async (notes: string) => + (await checkRepo(new Context({}, checkout(repo(notes), 'r')), '/r', { compendium: '/c' })).defects; + assert.deepEqual(await check(`${name('App', 'Port')}\n`), []); + assert.deepEqual(await check(`${name('App', 'Port')}\n${gone}\n`), [ + `✗ notes.txt: line 2: ${gone} names no requirement line`, + ]); +}); + test('checkCommitMessage reads the comment character from git', async () => { const message = `fix: x\n\n; Please enter the commit message for your changes.\n; On branch ${id('XYZ', 13)}-topic\n`; const io = (char: string | undefined) => diff --git a/packages/lib/src/requirements.ts b/packages/lib/src/requirements.ts index 27d69c7f..be4b2430 100644 --- a/packages/lib/src/requirements.ts +++ b/packages/lib/src/requirements.ts @@ -39,6 +39,10 @@ // the index this plx carries (standardIndex.ts), written by `plx-dev ship` // from the compendium at the version it cuts: a tenant repo, which has no // compendium, checks its citations against the version of plx it pins. +// Two files the lints never read: the baseline, which records violations, and +// in tooling that index, which is what citations are checked against and +// cites nothing. Until ship rewrites it, the index is the previous version's, +// and names what the compendium being cut may have dropped. // // plx requirements # lint; exit 1 on any defect // plx requirements --write-baseline # record today's violations @@ -59,7 +63,7 @@ import { renderViolation, type Violation, } from './lints.ts'; -import { bundledIndex, type StandardIndex } from './standardIndex.ts'; +import { bundledIndex, STANDARD_INDEX_FILE, type StandardIndex } from './standardIndex.ts'; export type PageMode = 'map' | 'module'; @@ -390,7 +394,7 @@ export async function lintRepo(ctx: Context, dir: string, options: RepoOptions = const citable: Citable = new Set(index.citable); for (const file of tracked) { - if (file === BASELINE_FILE) continue; + if (file === BASELINE_FILE || file === STANDARD_INDEX_FILE) continue; const text = await ctx.readFile(join(dir, file)).catch(() => undefined); if (text === undefined || text.includes('\0')) continue; // deleted in the worktree, a submodule, or binary if (kind === 'compendium' && /\.mdx?$/.test(file)) result.violations.push(...lintDateOrVersion(text, file)); diff --git a/packages/lib/src/siteTemplates.ts b/packages/lib/src/siteTemplates.ts index 52969318..a226d33e 100644 --- a/packages/lib/src/siteTemplates.ts +++ b/packages/lib/src/siteTemplates.ts @@ -40,8 +40,17 @@ // // Each site is rendered once for both, and the root a second time over the // union of templates only where that differs from its own. +// +// The keys of the first kind are also what `plx update` judges by (update.ts): +// an answer that the templates of the version a repo is on own or read, and +// those of the version it takes do not, is one this check would report once +// the repo is on that version, and the update removes it (`strayKeys`), unless +// a template of that version the markers do not list owns or reads it. +import { readdir } from 'node:fs/promises'; import { join } from 'node:path'; import type { render, Tree } from '@plexus-ms/cli-template'; +import { readTemplate } from './bundled.ts'; +import { engine } from './engine.ts'; import { MARKER_FILE } from './marker.ts'; import { type MarkerSite, siteAnswers } from './sites.ts'; @@ -55,16 +64,52 @@ export interface Bundled { readonly render: typeof render; } +/** + * The templates `names` below `root`, every one there by default, each read + * as `plx new` reads it (bundled.ts); rejects naming one it cannot read. + */ +export async function bundledAt(root: string, names?: readonly string[]): Promise { + const all = async () => + (await readdir(root, { withFileTypes: true })) + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort(); + const trees = await Promise.all( + (names ?? (await all())).map(async (name) => [name, (await readTemplate(root, name)).tree] as const), + ); + return { trees: new Map(trees), render: (await engine()).render }; +} + +/** A key of a marker that no template of the marker's scope owns or reads; `dir` is the marker's site. */ +export interface StrayKey { + dir: string; + key: string; +} + /** The findings of the markers among `sites` against `bundled`. */ export function templateFindings( sites: readonly MarkerSite[], bundled: Bundled, rootAnswers?: Record, ): string[] { - const { keys, answers } = judge(sites, bundled, rootAnswers); + const { stray, answers } = judge(sites, bundled, rootAnswers); + const where = (dir: string) => (dir === '.' ? 'a template that a marker of the repo lists' : 'a template it lists'); + const keys = stray.map( + ({ dir, key }) => + `${join(dir, MARKER_FILE)}: \`${key}\` is neither reserved nor a question or read of ${where(dir)}`, + ); return [...unknownNames(sites, bundled), ...keys, ...answers]; } +/** + * The keys of the markers among `sites` that no template of their scope in + * `bundled` owns or reads, the sites in their order and each site's keys in + * the engine's: the findings of the first kind, as data. + */ +export function strayKeys(sites: readonly MarkerSite[], bundled: Bundled): StrayKey[] { + return judge(sites, bundled, undefined).stray; +} + function unknownNames(sites: readonly MarkerSite[], bundled: Bundled): string[] { const held = [...bundled.trees.keys()].sort().map((name) => `\`${name}\``); return sites.flatMap(({ dir, config }) => @@ -82,12 +127,12 @@ function judge( sites: readonly MarkerSite[], bundled: Bundled, rootAnswers: Record | undefined, -): { keys: string[]; answers: string[] } { +): { stray: StrayKey[]; answers: string[] } { const listed = (site: MarkerSite) => site.config?.templates ?? []; const trees = (names: Iterable) => [...names].flatMap((name) => bundled.trees.get(name) ?? []); const rootConfig = sites.find((s) => s.dir === '.')?.config; const everywhere = [...new Set(sites.flatMap(listed))]; - const keys: string[] = []; + const stray: StrayKey[] = []; const answers = new Set(); for (const site of sites) { const { dir, config } = site; @@ -106,12 +151,9 @@ function judge( } const scope = root ? everywhere : mine; const { unused } = own && scope.length === mine.length ? own : bundled.render(trees(scope), given); - const where = root ? 'a template that a marker of the repo lists' : 'a template it lists'; - for (const key of unused) - if (Object.hasOwn(config.answers, key)) - keys.push(`${join(dir, MARKER_FILE)}: \`${key}\` is neither reserved nor a question or read of ${where}`); + for (const key of unused) if (Object.hasOwn(config.answers, key)) stray.push({ dir, key }); } - return { keys, answers: [...answers] }; + return { stray, answers: [...answers] }; } /** diff --git a/packages/lib/src/sync.ts b/packages/lib/src/sync.ts index e7324ef7..c42ce820 100644 --- a/packages/lib/src/sync.ts +++ b/packages/lib/src/sync.ts @@ -41,6 +41,9 @@ // one splice with its defaults, read when the plan is made: a write of its own // before or after would be lost to the other. It is written whether or not the // root renders anything or is merged, since every site of the repo moves to it. +// The answers a caller names for removal (`update`, never `apply`: those no +// template asks any more, update.ts) are taken out in the same splice +// (`removeMarkerKeys`), which leaves every other byte as it was. // // Performing a plan writes the merges, each site's in turn, then the markers. // A conflicted path is left in the file between the engine's markers, or kept @@ -62,7 +65,7 @@ import { loadTemplate, readTemplate } from './bundled.ts'; import type { Context } from './context.ts'; import { type Plan, write } from './effects.ts'; import { engine } from './engine.ts'; -import { MARKER_FILE, setMarkerKeys } from './marker.ts'; +import { MARKER_FILE, removeMarkerKeys, setMarkerKeys } from './marker.ts'; /** Templates, by name below a root, and the answers to render them with. */ export interface Source { @@ -111,6 +114,8 @@ export interface SyncOptions { siblings?: readonly { dir: string; templates: readonly string[]; answers: Answers }[]; /** The version to write into the root marker, which must be among the sites; none: the version is left as it is. */ version?: string; + /** The answers to take out of the markers, by site directory, each among the sites; none: every key stays. */ + remove?: Readonly>; } /** What planning decided for one site. */ @@ -242,13 +247,16 @@ export async function planSync( const dropped: Record = {}; if (options.version !== undefined && !rootEntry) throw new Error('the version goes into the root marker, and the root is not among the sites'); + const strays = Object.keys(options.remove ?? {}).filter((dir) => !rendered.some((r) => r.site.dir === dir)); + if (strays.length > 0) throw new Error(`answers to remove from ${strays.join(', ')}, which is among no site`); for (const entry of rendered) { const { dir, contextOnly } = entry.site; const defaults = contextOnly ? {} : defaultsOf(entry); const keys = { ...defaults, ...(dir === '.' && options.version !== undefined ? { version: options.version } : {}) }; - if (Object.keys(keys).length > 0) { + const removed = options.remove?.[dir] ?? []; + if (Object.keys(keys).length > 0 || removed.length > 0) { const path = join(repo, dir, MARKER_FILE); - markers.push(write(path, setMarkerKeys(await ctx.readFile(path), keys))); + markers.push(write(path, removeMarkerKeys(setMarkerKeys(await ctx.readFile(path), keys), removed))); } if (contextOnly) continue; const plan = await planMerge(join(repo, dir), entry.old, entry.new); diff --git a/packages/lib/src/take.ts b/packages/lib/src/take.ts index 64379fc1..312b7574 100644 --- a/packages/lib/src/take.ts +++ b/packages/lib/src/take.ts @@ -2,8 +2,9 @@ // branch the version lands on (consumers.ts): its sites brought to the // version by the caller's step, the lockfile refreshed where manifests moved, // the hand-owned workflows pinned to the version; then one commit, pushed as -// `plexus/`, whose message names each site's conflicted paths and -// the edited files the version drops, and a pull request against the branch. A conflict is +// `plexus/`, whose message names each site's conflicted paths, the +// edited files the version drops and the answers the step removed from the +// markers, and a pull request against the branch. A conflict is // committed with its markers and reported, and the pull request is opened all // the same, as a draft where the forge offers one, whose body opens with what // needs a hand (pull.ts): that is where it gets resolved. Nothing here aborts @@ -58,11 +59,22 @@ export interface SiteResult { kept?: string[]; } +/** The answers removed from the markers, by the directory of the marker (`.` for the root), each marker's in order. */ +export type Removed = Readonly>; + +/** What the sites' step came to: every site, and the answers it removed from the markers, where it removed any. */ +export interface SitesTaken { + sites: SiteResult[]; + removed?: Removed; +} + /** What one consumer's taking of the version came to, as data: the caller folds it into a summary. */ export interface Taken { rel: string; /** Every site, in the order they were brought to the version. */ sites: SiteResult[]; + /** The answers the sites' step removed from the markers, where it removed any. */ + removed?: Removed; /** The lockfile refresh, where manifests moved; undefined when nothing needed one. */ lockfile?: 'refreshed' | 'failed'; /** Tracked files of the scratch checkout that hold a conflict marker once the sites are updated. */ @@ -90,7 +102,7 @@ export const needsHand = (t: Taken): boolean => * files and markers changed in place, and what became of each. A step that * throws stops the taking before anything is committed. */ -export type SitesStep = (ctx: Context, consumer: Consumer, dir: string) => Promise; +export type SitesStep = (ctx: Context, consumer: Consumer, dir: string) => Promise; /** How a consumer takes the version. */ export interface Take { @@ -112,10 +124,15 @@ export interface Take { */ export async function takeVersion(ctx: Context, consumer: Consumer, dir: string, take: Take): Promise { const base = (await ctx.read('git', ['rev-parse', 'HEAD'], { cwd: dir })).trim(); - const sites = await take.sites(ctx, consumer, dir); + const { sites, removed } = await take.sites(ctx, consumer, dir); const lockfile = await refreshLockfile(ctx, consumer, dir, base); await bumpConsumerRefs(ctx, consumer, dir, take.version); - const taken: Taken = { rel: consumer.rel, sites, ...(lockfile ? { lockfile } : {}) }; + const taken: Taken = { + rel: consumer.rel, + sites, + ...(removed && Object.keys(removed).length > 0 ? { removed } : {}), + ...(lockfile ? { lockfile } : {}), + }; return { ...taken, ...(await openPull(ctx, consumer, dir, base, take, taken)) }; } @@ -206,7 +223,9 @@ async function openPull( run('git', ['add', '-A'], { cwd: dir }), // One commit on the branch, any scratch ones folded in: a later run tells it from a human's by the count. run('git', ['reset', '--quiet', '--soft', base], { cwd: dir }), - run('git', ['commit', '--quiet', '--no-verify', '-m', commitMessage(version, taken.sites)], { cwd: dir }), + run('git', ['commit', '--quiet', '--no-verify', '-m', commitMessage(version, taken.sites, taken.removed)], { + cwd: dir, + }), // An empty expected value: the branch must not exist on origin yet. run( 'git', @@ -241,6 +260,7 @@ async function openPull( ...gap, conflicts: Object.fromEntries(taken.sites.map((s) => [s.dir, s.conflicts ?? []])), kept: Object.fromEntries(taken.sites.map((s) => [s.dir, s.kept ?? []])), + ...(taken.removed ? { removed: taken.removed } : {}), note: `Opened by ${take.opener}${take.why ? `: ${take.why}` : ''}.`, }; if (marked.length > 0) ctx.say(` ${consumer.rel}: conflict markers in ${marked.join(', ')}`); diff --git a/packages/lib/src/testing/before.ts b/packages/lib/src/testing/before.ts index 126e7ca5..ed49ceff 100644 --- a/packages/lib/src/testing/before.ts +++ b/packages/lib/src/testing/before.ts @@ -1,8 +1,8 @@ // The two repo templates as Plexus 0.132.0 bundled them, the last version // before the files of PLX-Updates moved into a template of their own, -// `updates`: the reference of the tests that the move changes no file a repo -// holds (updatesMove.test.ts here, and the update through it in -// @plexus-ms/dev's ship.integration.test.ts). Not shipped (excluded in +// `updates`: the reference of the test that the update through the move +// changes no file a repo holds but the ones it concerns (@plexus-ms/dev's +// ship.integration.test.ts). Not shipped (excluded in // tsconfig). // // The archive holds `templates/repo-turbo` and `templates/repo-operations` of diff --git a/packages/lib/src/testing/bundled.ts b/packages/lib/src/testing/bundled.ts index aa6499cf..a387d953 100644 --- a/packages/lib/src/testing/bundled.ts +++ b/packages/lib/src/testing/bundled.ts @@ -28,3 +28,16 @@ export function generatedFrom(result: RenderResult): [path: string, line: string if (line.includes('Generated from')) found.push([path, line]); return found; } + +/** The body of the task `name` in a rendered `mise.toml`, up to the next table. */ +export const taskOf = (mise: string, name: string): string => + new RegExp(`^\\[tasks\\.${name}\\]\\n([\\s\\S]*?)(?=^\\[[a-z]|(?![\\s\\S]))`, 'm').exec(mise)?.[1] ?? ''; + +/** What a task runs: its body from `run =` on, which leaves out its description. */ +export const runOf = (mise: string, name: string): string => { + const body = taskOf(mise, name); + return body.slice(body.indexOf('run =')); +}; + +/** The names of a rendered `mise.toml`'s tasks. */ +export const tasksOf = (mise: string): string[] => [...mise.matchAll(/^\[tasks\.([\w-]+)\]/gm)].map((m) => m[1] ?? ''); diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 73d0123b..5af6546c 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -8,7 +8,9 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Repo/Marker`. -`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build` and `verify` exist as root mise tasks, and of `PLX-Repo/SubVerbs` that `lint`, `check`, `test` and `verify` do, not what they run, in which order, or whether they pass. +`plx doctor` checks of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook, written literally in its `hooks` block, not what either runs. + +`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass. `plx doctor` checks `PLX-App/Marker`. diff --git a/packages/lib/src/testing/shapes.ts b/packages/lib/src/testing/shapes.ts index 2dd8d264..26787c8c 100644 --- a/packages/lib/src/testing/shapes.ts +++ b/packages/lib/src/testing/shapes.ts @@ -16,20 +16,19 @@ export const CHOICES: Readonly package_registry: ['npm', 'github'], private_packages_scope: ['', '@acme'], ci_strategy: ['github', 'on-prem', 'hybrid'], - ci_registry: ['ghcr', 'own'], ci_overlay: ['none', 'netbird'], alerts_email: ['', 'ops@acme.example'], display_versions: [false, true], major: [1, 3], pr_reviewers: ['', 'alice', 'alice, bob'], update_max_age: [7, 0], + postgres: ['', '18.6'], }, 'repo-operations': { tenant: ['acme'], github_org: ['acme', 'acme-gh'], infrastructure: [false, true], ci_strategy: ['github', 'on-prem', 'hybrid'], - ci_registry: ['ghcr', 'own'], ci_overlay: ['none', 'netbird'], alerts_email: ['', 'ops@acme.example'], pr_reviewers: ['', 'alice', 'alice, bob'], diff --git a/packages/lib/src/turboCacheStep.test.ts b/packages/lib/src/turboCacheStep.test.ts new file mode 100644 index 00000000..4927e6a2 --- /dev/null +++ b/packages/lib/src/turboCacheStep.test.ts @@ -0,0 +1,129 @@ +// The step turbo-cache of this repo (.github/actions/turbo-cache), as a job +// runs it: its script's phases with GITHUB_OUTPUT and GITHUB_ENV as files of +// their own, and the wiring of its action.yml, which no machine but a runner +// of the forge runs. The newborn test (newborns/turbo-cache.test.ts) runs the +// phases around a real server. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { parse } from 'yaml'; + +const STEP = join(import.meta.dirname, '..', '..', '..', '.github', 'actions', 'turbo-cache'); +const CACHES = [ + { cache: 'shared', variable: 'PLX_TURBO_SHARED', item: 'bucket-turbo', bucket: 'acme-ci-turbo' }, + { cache: 'trusted', variable: 'PLX_TURBO_TRUSTED', item: 'bucket-turbo-trusted', bucket: 'acme-ci-turbo-trusted' }, +]; + +let scratch = ''; +before(() => { + scratch = mkdtempSync(join(tmpdir(), 'plx-turbo-cache-step-')); +}); +after(() => rmSync(scratch, { recursive: true, force: true })); + +/** `KEY=value` lines of a runner's file. */ +const pairs = (text: string): Record => + Object.fromEntries( + text + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), + ); + +let runs = 0; +/** One phase of the script, with nothing of the vault's credentials but `env`. */ +function phase(name: string, env: Record) { + const n = runs++; + const output = join(scratch, `output-${n}`); + const githubEnv = join(scratch, `env-${n}`); + writeFileSync(output, ''); + writeFileSync(githubEnv, ''); + const base = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(OP_|GITHUB_|PLX_)/.test(key))); + const ran = spawnSync('bash', [join(STEP, 'turbo-cache.sh'), name], { + encoding: 'utf8', + env: { ...base, GITHUB_OUTPUT: output, GITHUB_ENV: githubEnv, ...env }, + }); + assert.equal(ran.status, 0, ran.stderr); + return { + stdout: ran.stdout, + outputs: pairs(readFileSync(output, 'utf8')), + env: pairs(readFileSync(githubEnv, 'utf8')), + }; +} + +const plan = (cache: string) => + phase('plan', { CACHE: cache, OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); +const announce = (cache: string, keys: string, server = keys === 'success' ? 'success' : 'skipped') => + phase('announce', { CACHE: cache, KEYS: keys, SERVER: server, VAULT: 'acme-ci', PORT: '8585', TOKEN: 'job-token' }); + +test('plan names the vault item and the bucket of each cache', () => { + for (const { cache, item, bucket } of CACHES) { + const planned = plan(cache).outputs; + assert.equal(planned.item, item, cache); + assert.equal(planned.bucket, bucket, cache); + assert.equal(planned.vault, 'acme-ci'); + } +}); + +test('plan masks the job’s token before anything prints it, and announce never prints it', () => { + const planned = plan('trusted'); + const token = planned.outputs.token ?? ''; + assert.match(token, /^[0-9a-f]{64}$/); + const lines = planned.stdout.split('\n'); + assert.equal(lines[0], `::add-mask::${token}`); + assert.ok(!lines.slice(1).join('\n').includes(token), 'the token is printed once, in the mask command'); + const told = phase('announce', { CACHE: 'trusted', KEYS: 'success', SERVER: 'success', PORT: '8585', TOKEN: token }); + assert.ok(!told.stdout.includes(token)); +}); + +test('announce tells turbow of the cache it was asked for, and never of the other', () => { + for (const { cache, variable } of CACHES) { + assert.deepEqual(announce(cache, 'success').env, { + [variable]: 'http://127.0.0.1:8585', + [`${variable}_TOKEN`]: 'job-token', + }); + for (const [keys, server] of [ + ['skipped', 'skipped'], + ['failure', 'skipped'], + ['success', 'failure'], + ]) + assert.deepEqual(announce(cache, keys, server).env, { [variable]: 'none' }, `${cache} ${keys} ${server}`); + } +}); + +test('a job without the remote cache it asked for gets one warning on the run, naming the cause; a job with its server none', () => { + for (const { cache, item } of CACHES) { + const warnings = (stdout: string) => stdout.split('\n').filter((line) => line.startsWith('::warning ')); + for (const [keys, server, cause] of [ + ['skipped', 'skipped', /no vault/], + ['failure', 'skipped', new RegExp(`${item}\\b.*the vault acme-ci`)], + ['success', 'failure', /did not come up/], + ] as const) { + const said = warnings(announce(cache, keys, server).stdout); + assert.equal(said.length, 1, `${cache} ${keys} ${server}: ${said.join('\n')}`); + assert.match(said[0] ?? '', new RegExp(`^::warning title=Turbo runs without the ${cache} remote cache::`)); + assert.match(said[0] ?? '', cause); + } + assert.deepEqual(warnings(announce(cache, 'success').stdout), [], cache); + } +}); + +/** The steps of action.yml, by id. */ +function steps(): Record; 'continue-on-error'?: boolean; uses?: string }> { + const action = parse(readFileSync(join(STEP, 'action.yml'), 'utf8')); + return Object.fromEntries(action.runs.steps.map((step: { id?: string }) => [step.id, step])); +} + +test('the server binds loopback whatever the job’s environment holds', () => { + const server = steps().server; + assert.match(server?.uses ?? '', /^brunojppb\/turbo-cache-server@[0-9a-f]{40}$/); + assert.equal(server?.env?.HOST, '127.0.0.1'); +}); + +test('a server that does not come up fails no job: announce hears of it', () => { + const { server, announce } = steps(); + assert.equal(server?.['continue-on-error'], true); + assert.match(announce?.env?.SERVER ?? '', /^\$\{\{ steps\.server\.outcome \}\}$/); +}); diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index fa5de305..572bed4d 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -48,10 +48,34 @@ // `<<<<<<< current` and `>>>>>>> new render`, a file the version drops and // the user edited is kept without markers, named by the commit and the // pull request since nothing in the file shows it, and a born-once file -// the old render holds stays as the user left it. The defaults of questions that became -// applicable and the new `version` are spliced into the markers in one -// write each. Birth commands are never run, and neither is `mise -// install`: tools serve a developer's checkout, not a pull request. +// the old render holds stays as the user left it. The defaults of +// questions that became applicable and the new `version` are spliced +// into the markers, and the answers no template asks any more taken out +// of them, in one write each. Birth commands are never run, and neither +// is `mise install`: tools serve a developer's checkout, not a pull +// request. +// +// An answer no template asks any more is a key of a marker that a template of +// the marker's scope owns or reads at the version the repo is on, none does at +// the version it takes, and no template of that version at all does: the keys +// `plx doctor` would report of the marker once the repo is on that version, +// judged by its own rule (siteTemplates.ts) over each side's manifests, so that +// the two cannot disagree, but for a question the version moved to a template +// the markers do not list. That one the version still has, and whoever takes +// such a version adds the template, as its release notes say, and finds the +// answer where it was. Left in the marker, an answer no template asks would +// fail the pull request's own checks, and every repo would delete the same +// line by hand for every question a version removes. Only such keys are taken +// out, never a reserved key, never a key no template of the old side knew (a +// human's, which the doctor reports to that human), and nothing else of the +// marker: its entry goes, a value over several lines whole, and every other +// byte stays (`removeMarkerKeys`). The run says each key it takes out, and the +// commit and the pull request name them, a line per marker and key, so that a +// human who kept one for a reason sees it went. The manifests of both sides +// are read by the running plx, as the defaults' check reads the new side's; +// where it cannot read one, no answer is removed from any marker, the run says +// why, and the doctor reports the keys as it would have. `plx apply` removes +// nothing. // 3. The lockfile where a manifest moved, the workflow refs, one commit on // `plexus/`, and one pull request (take.ts). The `plx` pin is a // line of a template's mise.toml, and nothing writes it apart: where the @@ -109,8 +133,9 @@ import { versionBranch, } from './pull.ts'; import { findSites, type MarkerSite, siteAnswers } from './sites.ts'; -import { planSync, type Source, type Templates } from './sync.ts'; -import { type SiteResult, type Taken, takeVersion } from './take.ts'; +import { bundledAt, strayKeys } from './siteTemplates.ts'; +import { planSync, type Source, type TemplateSides } from './sync.ts'; +import { type Removed, type SitesTaken, type Taken, takeVersion } from './take.ts'; import { COMPENDIUM, compareVersions, isPlexusVersion, preflightForge, UsageError } from './version.ts'; import { type FetchVersion, templatesOf } from './versionTemplates.ts'; @@ -362,20 +387,21 @@ export async function versionOn( * The template step of a version taken (the header's steps 1 and 2), in the * worktree `dir`: every marker that lists at least one template, rendered at * `from` and at `to` and merged, the root rendered for its answers whatever it - * lists, the defaults and the version written into the markers. What became of - * each site is what the merge reported. `templates` yields the two sides; it - * is asked once the step has said which versions it takes, so that a fetch - * follows the line that names them. The maintainers' preview of an unreleased - * version (preview.ts of @plexus-ms/dev) gives the new side as the templates - * of its own checkout. + * lists, the defaults and the version written into the markers and the + * answers no template asks any more taken out. What became of each site is + * what the merge reported. `templates` yields the two sides; it is asked once + * the step has said which versions it takes, so that a fetch follows the line + * that names them. The maintainers' preview of an unreleased version + * (preview.ts of @plexus-ms/dev) gives the new side as the templates of its + * own checkout. */ export async function renderSites( ctx: Context, consumer: Consumer, dir: string, versions: { from: string; to: string }, - templates: () => Promise<{ old: Templates; new: Templates }>, -): Promise { + templates: () => Promise, +): Promise { const sites = await findSites(ctx, dir, 'HEAD'); const sourceOf = (site: MarkerSite): Source => ({ templates: site.config?.templates ?? [], @@ -393,13 +419,16 @@ export async function renderSites( .filter((s) => s.dir !== '.') .map((s) => ({ dir: s.dir, templates: s.config?.templates ?? [], answers: s.config?.answers ?? {} })); ctx.say(`→ ${consumer.rel}: the templates of ${versions.from} and ${versions.to}, merged`); - const plan = await planSync(ctx, dir, await templates(), sides, { + const both = await templates(); + const removed = await askedNoMore(ctx, sites, both, versions); + const plan = await planSync(ctx, dir, both, sides, { labels: { old: `the templates of ${versions.from}`, new: `the templates of ${versions.to}` }, siblings, version: versions.to, + remove: removed, }); await plan.perform(); - return plan.sites.map((s) => { + const results = plan.sites.map((s) => { const rel = s.dir === '.' ? consumer.rel : join(consumer.rel, s.dir); const inRepo = (path: string) => (s.dir === '.' ? path : join(s.dir, path)); const dropped = plan.dropped[s.dir] ?? []; @@ -414,8 +443,61 @@ export async function renderSites( : ` ✓ merged clean: ${rel}`, ); for (const path of kept) ctx.say(` kept although ${versions.to} drops it, since it was edited here: ${path}`); - return { rel, dir: s.dir, outcome: conflicted ? 'conflicted' : 'clean', conflicts, kept }; + return { rel, dir: s.dir, outcome: conflicted ? ('conflicted' as const) : ('clean' as const), conflicts, kept }; }); + for (const [at, keys] of Object.entries(removed)) + for (const key of keys) + ctx.say( + ` ${ctx.dryRun ? 'to be removed' : 'removed'} from ${join(at, MARKER_FILE)}, since no template asks or reads it at ${versions.to}: ${key}`, + ); + return { sites: results, ...(Object.keys(removed).length > 0 ? { removed } : {}) }; +} + +/** + * The answers no template asks any more (the header says which), by the + * directory of the marker, for the markers among `sites` and the templates of + * both sides; none where the running plx cannot read a manifest of either + * side, which the run says. + */ +async function askedNoMore( + ctx: Context, + sites: readonly MarkerSite[], + templates: TemplateSides, + versions: { from: string; to: string }, +): Promise { + const names = [...new Set(sites.flatMap((s) => s.config?.templates ?? []))].sort(); + if (names.length === 0) return {}; + const strayAt = async (root: string, version: string) => { + try { + return strayKeys(sites, await bundledAt(root, names)); + } catch (error) { + ctx.say( + ` ! no answer is removed from the markers: this plx cannot read the templates of ${version}: ${(error as Error).message}`, + ); + return undefined; + } + }; + const before = await strayAt(templates.old.root, versions.from); + const after = before && (await strayAt(templates.new.root, versions.to)); + if (!before || !after) return {}; + const known = new Set(before.map(({ dir, key }) => `${dir}\0${key}`)); + const candidates = after.filter(({ dir, key }) => !known.has(`${dir}\0${key}`)); + if (candidates.length === 0) return {}; + // A question the version moved to a template no marker lists is one it still has. + let unknown: Set; + try { + const every = await bundledAt(templates.new.root); + const probe = Object.fromEntries(candidates.map(({ key }) => [key, null])); + unknown = new Set(every.render([...every.trees.values()], probe).unused); + } catch (error) { + ctx.say( + ` ! no answer is removed from the markers: this plx cannot read the templates of ${versions.to}: ${(error as Error).message}`, + ); + return {}; + } + const removed: Record = {}; + for (const { dir, key } of candidates) if (unknown.has(key)) removed[dir] = [...(removed[dir] ?? []), key]; + return removed; } /** The repo at `path`, which must be generated from the templates, named `name` rather than from a workspace. */ diff --git a/packages/lib/src/updatesMove.test.ts b/packages/lib/src/updatesMove.test.ts deleted file mode 100644 index b940f0c6..00000000 --- a/packages/lib/src/updatesMove.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -// The move of PLX-Updates' files out of the repo template of operations and -// into `updates` changes nothing a repo holds (repo-turbo's template has -// changed since, which ended the test for it): in every answer shape, a repo -// template rendered beside `updates` gives the tree that template alone gave -// at 0.132.0, the version before the move (testing/before.ts), byte for byte -// and mode for mode, with the same policies. The one line that differs is the -// one that names the template a file is generated from, in plx-update.yml, -// which names `updates` now. -// -// What it proves holds while the templates are as the move left them, but for -// the version pins, which ship stamps: a later change to one of them makes it -// fail, and the change that does ends this test and the archive with it. -import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { after, test } from 'node:test'; -import { type Answers, readTree, render, type Tree } from '@plexus-ms/cli-template'; -import { templatesRoot } from './templatesRoot.ts'; -import { templatesBefore } from './testing/before.ts'; -import { CHOICES, distinct } from './testing/shapes.ts'; - -const scratch = mkdtempSync(join(tmpdir(), 'plx-updates-move-')); -after(() => rmSync(scratch, { recursive: true, force: true })); -const before = templatesBefore(scratch); - -/** The workflow's line naming its template, as each repo template wrote it before the move, and as updates does. */ -const header = (name: string) => - `# Generated from plexus-ms/tooling, templates/${name}: edit the template, never this file.\n`; -const WORKFLOW = '.github/workflows/plx-update.yml'; - -/** A tree with each path's policy beside its bytes and mode, the workflow's header put back as it was. */ -function comparable(tree: Tree, files: ReadonlyMap, repo: string) { - const decoder = new TextDecoder(); - return Object.fromEntries( - [...tree].map(([path, { bytes, mode }]) => { - const text = decoder.decode(bytes); - return [ - path, - { - mode, - policy: files.get(path)?.policy, - text: path === WORKFLOW ? text.replace(header('updates'), header(repo)) : text, - }, - ]; - }), - ); -} - -for (const repo of ['repo-operations'] as const) - test(`${repo} beside updates renders what ${repo} alone rendered before the move, in every answer shape`, async () => { - const old = [await readTree(join(before, repo))]; - const now = [await readTree(join(templatesRoot(), repo)), await readTree(join(templatesRoot(), 'updates'))]; - const shapes = distinct(CHOICES[repo], (answers: Answers) => render(old, answers)); - assert.ok(shapes.length > 100, `${shapes.length} shapes`); - for (const { answers, result: reference } of shapes) { - const shape = JSON.stringify(answers); - assert.deepEqual(reference.errors, [], shape); - const moved = render(now, answers); - assert.deepEqual(moved.errors, [], shape); - assert.match( - new TextDecoder().decode(moved.tree.get(WORKFLOW)?.bytes), - new RegExp(`^[^\\n]*\\n\\n${header('updates')}`), - ); - assert.deepEqual( - comparable(moved.tree, moved.files, repo), - comparable(reference.tree, reference.files, repo), - shape, - ); - assert.deepEqual(moved.answers, reference.answers, shape); - } - }); diff --git a/packages/lib/turbo.json b/packages/lib/turbo.json index 70ca5e94..0f0696d1 100644 --- a/packages/lib/turbo.json +++ b/packages/lib/turbo.json @@ -2,7 +2,7 @@ "extends": ["//"], "tasks": { "test": { - "inputs": ["$TURBO_DEFAULT$", "../../templates/**"] + "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**"] } } } diff --git a/templates/app-nextjs/files/PLEXUS.md.jinja b/templates/app-nextjs/files/PLEXUS.md.jinja index d51b9733..030f7fd8 100644 --- a/templates/app-nextjs/files/PLEXUS.md.jinja +++ b/templates/app-nextjs/files/PLEXUS.md.jinja @@ -1,5 +1,8 @@ -- `{{ name }}`, a Next.js app: `docker/Dockerfile` builds its image and `docker/compose.yaml` runs it on its host. -- Its verbs are the repo root's: `mise :dev `, `mise :build ` and `mise :verify `, `` being this directory's name. +- `{{ name }}`, a Next.js app: its `build` leaves one directory that runs as it is, `.next/standalone`, `docker/Dockerfile` copies that directory into its image, and `docker/compose.yaml` runs the image on its host. +- The `build` script completes Next's standalone output in place: after `next build` it copies the static files and `public/` into it, as Next's documentation of `output: 'standalone'` describes. +- Its verbs are the repo root's: `mise :dev `, `mise :build `, `mise :check `, `mise :test ` and `mise :e2e `, `` being this directory's name. +- The `test` script is `node --test`, which runs the files of Node's rule, `**/*.test.{cts,mts,ts}`, `**/*-test.{cts,mts,ts}`, `**/*_test.{cts,mts,ts}`, `**/test-*.{cts,mts,ts}`, `**/test.{cts,mts,ts}` and `**/test/**/*.{cts,mts,ts}` and their `.cjs`, `.mjs` and `.js` siblings, with relative imports: no `.tsx` file runs, and no `@/` import resolves. + An app with such tests names its own runner in that script. {%- if profile == 'stateful' %} -- The `migrate` and `seed` scripts in `package.json` fail until they are written: the deploy verb runs `migrate` in the image, through the compose file's `migrate` service, and `seed` loads development data and never runs on a host. +- The `migrate` and `seed` scripts in `package.json` fail until they are written: the deploy verb runs `migrate` in the image, through the compose file's `migrate` service, from what the build put in the directory, and `seed` loads development data and never runs on a host. {%- endif %} diff --git a/templates/app-nextjs/files/docker/Dockerfile b/templates/app-nextjs/files/docker/Dockerfile index 6bc8931a..80945065 100644 --- a/templates/app-nextjs/files/docker/Dockerfile +++ b/templates/app-nextjs/files/docker/Dockerfile @@ -1,39 +1,11 @@ -# syntax=docker/dockerfile:1 # Generated from plexus-ms/tooling, templates/app-nextjs. -# The image build of a Next.js standalone app in the monorepo, from its root or a pruned context (PLX-App/Dockerfile). -FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c AS builder +# The app's image, the one directory its build leaves copied in as it is (PLX-App/Dockerfile); by hand, on Linux x64 at the repo root: `mise build `, then `docker build --build-arg APP= -f apps//docker/Dockerfile apps//.next/standalone`. +FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c ARG APP -WORKDIR /repo -ENV CI=1 -ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 -RUN corepack enable -# package.json comes along so that corepack runs the pnpm its packageManager pins. -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -# The npmrc secret is the token of the tenant's private package registry, for a repo that installs -# from one (§ 5 PLX-Delivery); a build without the secret mounts nothing. -RUN --mount=type=secret,id=npmrc,target=/root/.npmrc pnpm fetch -COPY turbo.json ./ -COPY packages packages -COPY apps/${APP} apps/${APP} -# public/ is optional; an empty one lets the runner stage copy it unconditionally. -RUN mkdir -p apps/${APP}/public -RUN --mount=type=secret,id=npmrc,target=/root/.npmrc pnpm install --frozen-lockfile --prefer-offline -# pnpm, not Turbo, whose strict environment would hide BUILD_HASH and the key from `next build`; -# the filter's trailing `...` builds the app's workspace dependencies first, as `^build` would. -ARG BUILD_HASH -RUN --mount=type=secret,id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY \ - BUILD_HASH=${BUILD_HASH} pnpm --filter "{./apps/${APP}}..." run build - -FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c AS runner -ARG APP -WORKDIR /repo -ENV NODE_ENV=production -# The standalone output keeps the monorepo's layout; the static files and public/ go in beside it. -COPY --from=builder --chown=node:node /repo/apps/${APP}/.next/standalone ./ -COPY --from=builder --chown=node:node /repo/apps/${APP}/.next/static ./apps/${APP}/.next/static -COPY --from=builder --chown=node:node /repo/apps/${APP}/public ./apps/${APP}/public +COPY --chown=node:node . /repo WORKDIR /repo/apps/${APP} USER node EXPOSE 3000 +ENV NODE_ENV=production ENV HOSTNAME=0.0.0.0 ENTRYPOINT ["node", "server.js"] diff --git a/templates/app-nextjs/files/docker/compose.ci.yaml.jinja b/templates/app-nextjs/files/docker/compose.ci.yaml.jinja deleted file mode 100644 index 307f5604..00000000 --- a/templates/app-nextjs/files/docker/compose.ci.yaml.jinja +++ /dev/null @@ -1,22 +0,0 @@ -# Generated from plexus-ms/tooling, templates/app-nextjs. -# The override of compose.yaml that `plx-ci test` reads beside it, never the deploy verb (§ 1 PLX-Delivery). - -# Added to the environment the specs run in, on the runner beside the stack, to CI, PLEXUS_LOOPBACK_PORT and E2E_BASE_URL. -x-plexus-ci: - env: {} - -# Stands in for .env and .env.secret, with throwaway values. -x-ci-env: &ci-env - PUBLIC_URL: http://127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by plx-ci test} - -services: - web: - environment: *ci-env - restart: "no" -{%- if profile == "stateful" %} - # plx-ci test runs migrate once before `up`. - migrate: - environment: *ci-env - # Data services go here, published on 127.0.0.1 for the specs and kept in RAM (`volumes: !override []` - # and a tmpfs for the data directory), with the database URL in x-plexus-ci.env above. -{%- endif %} diff --git a/templates/app-nextjs/files/docker/compose.yaml.jinja b/templates/app-nextjs/files/docker/compose.yaml.jinja index 268f3ae4..7db0eaf8 100644 --- a/templates/app-nextjs/files/docker/compose.yaml.jinja +++ b/templates/app-nextjs/files/docker/compose.yaml.jinja @@ -33,7 +33,7 @@ services: migrate: image: ${PLEXUS_DEPLOYMENT_IMAGE:?rendered by the deploy verb} profiles: ["migrate"] - # npm, not pnpm: the image holds node and the standalone build and nothing else. + # npm, not pnpm: the image holds node and the directory the app's build leaves, and nothing else. entrypoint: ["npm", "run", "migrate"] environment: NODE_ENV: production diff --git a/templates/app-nextjs/files/next.config.ts b/templates/app-nextjs/files/next.config.ts index c19a6ef5..43cdee40 100644 --- a/templates/app-nextjs/files/next.config.ts +++ b/templates/app-nextjs/files/next.config.ts @@ -7,8 +7,19 @@ const root = process.env.PLX_UMBRELLA_ROOT || fileURLToPath(new URL('../../', im const nextConfig: NextConfig = { output: 'standalone', - // BUILD_HASH comes from the image build; without it Next draws a random ID, as in development. - generateBuildId: () => process.env.BUILD_HASH || null, + // The build ID is Turbo's hash of this app's build task, which carries the platform (turbo.json). + // A build started outside Turbo, or outside mise, which sets PLX_PLATFORM, throws here instead. + generateBuildId: () => { + const { TURBO_HASH, PLX_PLATFORM } = process.env; + if (!TURBO_HASH || !PLX_PLATFORM) + throw new Error( + `build through \`mise build\`, which sets TURBO_HASH and PLX_PLATFORM: TURBO_HASH=${TURBO_HASH ?? ''} PLX_PLATFORM=${PLX_PLATFORM ?? ''}`, + ); + return TURBO_HASH; + }, + // `check` is the type gate. The build's inputs need not hold every file the app's tsconfig.json + // includes, its tests among them, so a type check here could fail a miss where a hit of one hash passes. + typescript: { ignoreBuildErrors: true }, outputFileTracingRoot: root, turbopack: { root }, }; diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index 6f9ffc34..b689ea72 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -4,10 +4,10 @@ "private": true, "scripts": { "dev": "next dev", - "build": "next build", - "start": "next start", - "check": "next typegen && tsc --noEmit"{% if profile == 'stateful' %}, - "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the standalone build.' >&2; exit 1", + "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", + "check": "next typegen && tsc --noEmit", + "test": "node --test"{% if profile == 'stateful' %}, + "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the directory the build leaves, so the build puts in that directory whatever the command needs (outputFileTracingIncludes in next.config.ts, or the build script).' >&2; exit 1", "seed": "echo 'seed: not written yet. Name the command here that loads development sample data into a fresh, migrated database.' >&2; exit 1"{% endif %} }, "dependencies": { diff --git a/templates/app-nextjs/files/turbo.json b/templates/app-nextjs/files/turbo.json new file mode 100644 index 00000000..1237df92 --- /dev/null +++ b/templates/app-nextjs/files/turbo.json @@ -0,0 +1,9 @@ +{ + "extends": ["//"], + "tasks": { + "build": { + "env": ["$TURBO_EXTENDS$", "PLX_PLATFORM"], + "outputs": [".next/standalone/**"] + } + } +} diff --git a/templates/e2e-playwright/files/.gitignore.jinja b/templates/e2e-playwright/files/.gitignore.jinja new file mode 100644 index 00000000..57337032 --- /dev/null +++ b/templates/e2e-playwright/files/.gitignore.jinja @@ -0,0 +1,3 @@ +/test-results/ +/playwright-report/ +*.tsbuildinfo diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja new file mode 100644 index 00000000..b0211bab --- /dev/null +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -0,0 +1,5 @@ +- The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL and the app's `migrate` and `seed` where its `package.json` has either. +- What the app's run needs beyond that, environment for migrate, seed, the server, further processes and the specs, environment for the server alone, PostgreSQL's settings and further processes from the build output, goes in `run.ts`, which is the suite's own, like the specs; `setup.ts` is generated, and `plx update` merges it. +- It runs with `mise e2e ` at the repo's root, `` being the app's directory name, which builds the app first (the suite's own name is no name the verb takes); the suite's `e2e` script never builds, and fails without the build output. +- Its `check` type-checks the specs, `setup.ts`, `run.ts` and what they import of the app; `mise check` runs it at the repo's root, given no name. +- Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. diff --git a/templates/e2e-playwright/files/package.json.jinja b/templates/e2e-playwright/files/package.json.jinja new file mode 100644 index 00000000..f8a752e6 --- /dev/null +++ b/templates/e2e-playwright/files/package.json.jinja @@ -0,0 +1,17 @@ +{ + "name": "{{ app }}-e2e", + "private": true, + "type": "module", + "scripts": { + "check": "tsc --noEmit", + "e2e": "playwright test" + }, + "devDependencies": { + "{{ app }}": "workspace:*", + "@playwright/test": "^1.65.1", + "@plexus-ms/config": "catalog:plexus", + "@plexus-ms/test-postgres": "^0.1.0", + "@types/node": "^24", + "typescript": "catalog:" + } +} diff --git a/templates/e2e-playwright/files/playwright.config.ts b/templates/e2e-playwright/files/playwright.config.ts new file mode 100644 index 00000000..e1db170a --- /dev/null +++ b/templates/e2e-playwright/files/playwright.config.ts @@ -0,0 +1,11 @@ +// The suite's Playwright configuration: the specs in specs/, run in Chromium against the app that setup.ts starts. +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: 'specs', + globalSetup: './setup.ts', + reporter: 'list', + // Set by setup.ts once the app answers, before any worker reads this file; whatever it held before is replaced. + use: { baseURL: process.env.PLX_E2E_BASE_URL }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], +}); diff --git a/templates/e2e-playwright/files/run.ts b/templates/e2e-playwright/files/run.ts new file mode 100644 index 00000000..7c25a632 --- /dev/null +++ b/templates/e2e-playwright/files/run.ts @@ -0,0 +1,12 @@ +// This file is the repo's own, written at the suite's birth and never touched by an update: what the app's run needs +// beyond what setup.ts does, as its Needs says; setup.ts calls it once the server's port is picked, before the database. +import type { Needs, Run } from './setup.ts'; + +/** + * As generated, nothing. DATABASE_URL, PORT, HOSTNAME, PLX_E2E_BASE_URL and NODE_ENV are the setup's to give, and a + * run.ts that sets one fails the run. A variable this file reads from outside the run reaches it only where the suite's + * turbo.json names it for the e2e task, in `env` (hashed) or `passThroughEnv`, after "$TURBO_EXTENDS$". + */ +export default function needs(_run: Run): Needs { + return {}; +} diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja new file mode 100644 index 00000000..34126add --- /dev/null +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -0,0 +1,275 @@ +// Generated from plexus-ms/tooling, templates/e2e-playwright: edit the template, never this file; run.ts is the repo's. +// The global setup: starts the app's build output, never building it, after a database, migrate and seed where it has them. +import { type ChildProcess, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'; +import { cp, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chromium } from '@playwright/test'; + +/** The app this suite tests, by its package name. */ +const APP = '{{ app }}'; + +/** Environment variables, by name. */ +type Env = Record; + +/** The names the setup gives: the database, the server's port and host, the specs' address, migrate's NODE_ENV. */ +const RESERVED = ['DATABASE_URL', 'PORT', 'HOSTNAME', 'PLX_E2E_BASE_URL', 'NODE_ENV']; + +/** What run.ts is given: what is known only once the run has begun. */ +export interface Run { + /** The server's address, as in http://127.0.0.1:41234: the specs' baseURL. */ + readonly address: string; + /** A new empty directory, removed at the end of the run. */ + directory(): Promise; +} + +/** What run.ts says the app's run needs beyond the database, migrate, seed and the server. */ +export interface Needs { + /** Environment for migrate, seed, the server, every further process and the specs; none of the names RESERVED. */ + env?: Env; + /** Environment for the server alone, over `env`. */ + server?: { env?: Env }; + /** Settings of the PostgreSQL server, as in `{ max_connections: 200 }`, where the app has a database. */ + postgres?: Record; + /** Further processes, each the output's server.js beside the server on a port of its own, with `env` under its own. */ + processes?: { env?: Env }[]; +} + +export default async function setup(): Promise<() => Promise> { + const app = appDirectory(); + const output = path.join(app, '.next', 'standalone'); + if (!existsSync(output)) + throw new Error( + `${APP} has no build output at ${output}: the suite starts it and never builds it; mise e2e builds it first`, + ); + // The app needs a database when it has a migrate or a seed entry point, as the stateful profile requires of it. + const { scripts = {} } = JSON.parse(await readFile(path.join(app, 'package.json'), 'utf8')); + const entries = ['migrate', 'seed'].filter((name) => scripts[name] !== undefined); + const major = process.env.PLX_POSTGRES_MAJOR; + if (entries.length > 0 && !major) + throw new Error( + `${APP} has a ${entries.join(' and a ')} script, so its suite needs PostgreSQL, and the repo pins none: answer \`postgres\` in the repo's PLEXUS.md, an exact version as in 18.6, and run \`plx apply\` at the repo's root`, + ); + await chromium.launch().then( + (browser) => browser.close(), + (error: Error) => { + if (!/Executable doesn't exist/.test(error.message)) throw error; + throw new Error( + `Playwright's shared cache holds no Chromium: install it with \`pnpm exec playwright install chromium\` in ${process.cwd()}`, + ); + }, + ); + const stops: (() => Promise)[] = []; + const stopAll = async () => { + for (const stop of stops.reverse()) await stop(); + }; + // The further processes, which must still run when the specs end. + const further: { index: number; names: string[]; child: ChildProcess }[] = []; + const teardown = async () => { + const exited = further.filter(({ child }) => child.exitCode !== null || child.signalCode !== null); + await stopAll(); + if (exited.length > 0) + throw new Error( + exited + .map( + ({ index, names, child }) => + `further process ${index} of run.ts, with ${names.join(' and ') || 'no env of its own'}, exited with ${child.exitCode ?? child.signalCode} before the specs ended`, + ) + .join('\n'), + ); + }; + /** A new directory, removed at the end. */ + const temporary = async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); + stops.push(() => rm(dir, { recursive: true, force: true })); + return dir; + }; + /** The output's server.js, started in `dir` on `port`, ended at the end and with this process. */ + const start = (dir: string, env: NodeJS.ProcessEnv, port: number): ChildProcess => { + // It exits at the end of its stdin, which this process holds, so that it never outlives this process. + const guard = "process.stdin.on('end', () => process.exit()).resume(); require('./server.js');"; + const child = spawn(process.execPath, ['-e', guard], { + cwd: dir, + env: { ...env, PORT: String(port), HOSTNAME: '127.0.0.1' }, + stdio: ['pipe', 'inherit', 'inherit'], + }); + stops.push(() => end(child)); + return child; + }; + // Until the setup returns or throws, so that it cannot end unnoticed, and the runner with it, on a promise that never settles. + const alive = setInterval(() => {}, 60_000); + try { + // A copy, since a running server writes into its own directory. + const copy = await temporary(); + await cp(output, copy, { recursive: true, verbatimSymlinks: true }); + const server = within(copy); + const port = await freePort(); + const address = `http://127.0.0.1:${port}`; + const needs = await needed({ address, directory: temporary }); + const env: NodeJS.ProcessEnv = { ...process.env, ...needs.env }; + if (entries.length > 0) { + // From the binary the repo pins; migrate runs in the copy as the image runs it, seed in the app as developers do. + const { createDatabase, startPostgres } = await import('@plexus-ms/test-postgres'); + const postgres = await startPostgres({ major: Number(major), settings: needs.postgres }); + stops.push(postgres.stop); + env.DATABASE_URL = await createDatabase(postgres.url); + if (entries.includes('migrate')) await run(['npm', 'run', 'migrate'], server, { ...env, NODE_ENV: 'production' }); + if (entries.includes('seed')) await run(['npm', 'run', 'seed'], app, env); + } + const started = start(server, { ...env, ...needs.server?.env }, port); + await ready(`${address}/healthz`, started); + for (const [index, { env: own = {} }] of (needs.processes ?? []).entries()) + further.push({ index, names: Object.keys(own), child: start(server, { ...env, ...own }, await freePort()) }); + // The specs run in workers that inherit this process's environment. + Object.assign(process.env, needs.env); + if (env.DATABASE_URL) process.env.DATABASE_URL = env.DATABASE_URL; + process.env.PLX_E2E_BASE_URL = address; + } catch (error) { + await stopAll(); + throw error; + } finally { + clearInterval(alive); + } + return teardown; +} + +/** What run.ts says the run needs, within a minute; nothing where the suite has no run.ts. */ +async function needed(given: Run): Promise { + const file = new URL('./run.ts', import.meta.url); + if (!existsSync(file)) return {}; + // By its URL, not a literal: the suite's check then reads run.ts on its own, against the Needs it declares, and a + // suite without one passes it. + const { default: needs } = await import(file.href); + if (typeof needs !== 'function') throw new Error('run.ts exports no function by default, which setup.ts calls'); + let timer: NodeJS.Timeout | undefined; + const late = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('run.ts did not return within a minute')), 60_000); + }); + try { + return checked(await Promise.race([needs(given), late])); + } finally { + clearTimeout(timer); + } +} + +/** What run.ts returned, checked, since e2e runs without check: the first thing wrong fails the run, named. */ +function checked(needs: unknown): Needs { + const isMap = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + const fail = (what: string): never => { + throw new Error(`${what}; Needs in setup.ts says what it takes`); + }; + const only = (at: string, value: Record, names: string[]) => { + for (const name of Object.keys(value)) + if (!names.includes(name)) fail(`run.ts returned ${at}${name}, which setup.ts does not take`); + }; + const env = (at: string, value: unknown) => { + if (value === undefined) return; + if (!isMap(value)) return fail(`${at} of run.ts is no object of names and strings`); + for (const [name, text] of Object.entries(value)) { + if (typeof text !== 'string') fail(`${at}.${name} of run.ts is no string`); + if (RESERVED.includes(name)) + fail(`${at}.${name} of run.ts is the setup's to give, as are ${RESERVED.join(', ')}`); + } + }; + if (!isMap(needs)) + return fail( + `run.ts returned ${needs === null || needs === undefined ? needs : Array.isArray(needs) ? 'a list' : typeof needs}, where setup.ts takes an object`, + ); + only('', needs, ['env', 'server', 'postgres', 'processes']); + env('env', needs.env); + if (needs.server !== undefined) { + if (!isMap(needs.server)) return fail('server of run.ts is no object'); + only('server.', needs.server, ['env']); + env('server.env', needs.server.env); + } + if (needs.postgres !== undefined && !isMap(needs.postgres)) fail('postgres of run.ts is no object of settings'); + if (needs.processes !== undefined) { + if (!Array.isArray(needs.processes)) return fail('processes of run.ts is no list'); + for (const [index, further] of needs.processes.entries()) { + if (!isMap(further)) return fail(`processes[${index}] of run.ts is no object`); + only(`processes[${index}].`, further, ['env']); + env(`processes[${index}].env`, further.env); + } + } + return needs as Needs; +} + +/** + * The app's directory, through the workspace dependency and never by a relative path: found as Node finds a package, + * in node_modules from the suite up, and not through the app's exports, which need not export its package.json. + */ +function appDirectory(): string { + for (let dir = path.dirname(fileURLToPath(import.meta.url)); ; dir = path.dirname(dir)) { + const linked = path.join(dir, 'node_modules', APP); + if (existsSync(path.join(linked, 'package.json'))) return realpathSync(linked); + if (path.dirname(dir) === dir) + throw new Error(`${APP} is not installed beside its suite: run pnpm install at the repo's root`); + } +} + +/** + * The app's directory in the output, as the app's build recorded it: `relativeAppDir` of the one + * `.next/required-server-files.json` the output holds outside `node_modules`. + */ +function within(output: string): string { + const records: string[] = []; + const look = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) + if (entry.isDirectory() && entry.name !== 'node_modules') { + const at = path.join(dir, entry.name); + if (entry.name === '.next' && existsSync(path.join(at, 'required-server-files.json'))) records.push(at); + else look(at); + } + }; + look(output); + if (records.length !== 1) + throw new Error( + `the build output of ${APP} holds ${records.length} .next/required-server-files.json, where its build writes one: build it again`, + ); + const record = path.join(records[0] as string, 'required-server-files.json'); + const server = path.join(output, JSON.parse(readFileSync(record, 'utf8')).relativeAppDir); + if (!existsSync(path.join(server, 'server.js'))) + throw new Error(`the build output of ${APP} holds no server.js where ${record} places the app: build it again`); + return server; +} + +async function run([command, ...args]: string[], cwd: string, env: NodeJS.ProcessEnv): Promise { + const child = spawn(command as string, args, { cwd, env, stdio: 'inherit' }); + const [code, signal] = await once(child, 'exit'); + if (code !== 0) throw new Error(`${[command, ...args].join(' ')} in ${cwd} failed with ${signal ?? code}`); +} + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer().once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const { port } = probe.address() as { port: number }; + probe.close(() => resolve(port)); + }); + }); +} + +async function ready(url: string, server: ChildProcess): Promise { + for (const until = Date.now() + 60_000; Date.now() < until; ) { + if (server.exitCode !== null) throw new Error(`the server exited with ${server.exitCode} before ${url} answered`); + const answered = await fetch(url).then( + (response) => response.ok, + () => false, + ); + if (answered) return; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error(`${url} did not answer within a minute`); +} + +async function end(server: ChildProcess): Promise { + if (server.exitCode !== null || server.signalCode !== null) return; + const exited = once(server, 'exit'); + server.kill(); + await exited; +} diff --git a/templates/e2e-playwright/files/specs/home.spec.ts.jinja b/templates/e2e-playwright/files/specs/home.spec.ts.jinja new file mode 100644 index 00000000..c25e12c0 --- /dev/null +++ b/templates/e2e-playwright/files/specs/home.spec.ts.jinja @@ -0,0 +1,6 @@ +import { expect, test } from '@playwright/test'; + +test('the home page shows the name of the app', async ({ page }) => { + await page.goto('/'); + await expect(page.getByRole('heading', { level: 1 })).toHaveText('{{ app }}'); +}); diff --git a/templates/e2e-playwright/files/tsconfig.json.jinja b/templates/e2e-playwright/files/tsconfig.json.jinja new file mode 100644 index 00000000..6ec6f37d --- /dev/null +++ b/templates/e2e-playwright/files/tsconfig.json.jinja @@ -0,0 +1,18 @@ +{ + // The suite's check reads the app's code as the app's own check does: it extends the app's own tsconfig.json, its + // aliases, target, lib and jsx included, through the suite's workspace link to the app, and sets only the suite's own. + "extends": "./node_modules/{{ app }}/tsconfig.json", + "compilerOptions": { + "noEmit": true, + // No build info: tsc reused it across a change of the app's target alone, and the check is Turbo's to cache. + "incremental": false, + // The app's editor plugins are the app's. + "plugins": [], + // run.ts imports setup.ts by its .ts name, which Playwright resolves; the setup runs in node. plx update merges + // this file, so a line a repo adds stays. + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/templates/e2e-playwright/files/turbo.json b/templates/e2e-playwright/files/turbo.json new file mode 100644 index 00000000..9e659286 --- /dev/null +++ b/templates/e2e-playwright/files/turbo.json @@ -0,0 +1,9 @@ +{ + // check follows the checks of the suite's dependencies, whose hashes carry the app's source it reads, and builds no + // app; neither does test (the root's ^build would build it). e2e keeps the root's ^build. + "extends": ["//"], + "tasks": { + "check": { "dependsOn": ["^check"] }, + "test": { "dependsOn": [] } + } +} diff --git a/templates/e2e-playwright/template.yml b/templates/e2e-playwright/template.yml new file mode 100644 index 00000000..660b576a --- /dev/null +++ b/templates/e2e-playwright/template.yml @@ -0,0 +1,15 @@ +# files/.gitignore.jinja is a .gitignore: npm leaves a file of that name out of a package, so the +# template carries it with the suffix, which renders it to the same bytes. +name: e2e-playwright + +questions: + app: + type: str + help: "The app this suite tests, by its package name as its package.json gives it (as in @acme/shop): the suite lists it as a workspace dependency and starts its build output" + +policies: + # The marker, the spec and run.ts are rendered at birth only: the spec and run.ts, where the app says what + # its run needs, are the author's from then on, and the marker's frontmatter is plx's. setup.ts is merged. + PLEXUS.md.jinja: born-once + run.ts: born-once + specs/home.spec.ts.jinja: born-once diff --git a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja index 82629355..1154bdca 100644 --- a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja @@ -21,5 +21,5 @@ jobs: with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small - tasks: verify + tasks: test {% endraw %} \ No newline at end of file diff --git a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja index c81fe622..0c29e5c8 100644 --- a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja @@ -20,5 +20,5 @@ jobs: with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small - tasks: verify + tasks: test {% endraw %} \ No newline at end of file diff --git a/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja similarity index 84% rename from templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja rename to templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja index 288c7e2a..cdf27be9 100644 --- a/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja @@ -1,7 +1,7 @@ {% raw %}name: housekeeping # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# The daily housekeeping of the tenant's CI: its throwaway instances, its registry buckets (§ 8 PLX-Delivery). +# The daily housekeeping of the tenant's CI: its throwaway instances (§ 8 PLX-Delivery). on: schedule: @@ -15,14 +15,12 @@ on: permissions: contents: read - packages: write jobs: housekeeping: uses: plexus-ms/tooling/.github/workflows/_housekeeping.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ 'own' if ci_registry == 'own' else 'none' }}{% raw %} dry-run: ${{ inputs.dry_run || false }} alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}' secrets: diff --git a/templates/repo-operations/files/PLEXUS.md.jinja b/templates/repo-operations/files/PLEXUS.md.jinja index 26603b2e..94da9aee 100644 --- a/templates/repo-operations/files/PLEXUS.md.jinja +++ b/templates/repo-operations/files/PLEXUS.md.jinja @@ -1,3 +1,3 @@ - The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory they run on, and the third-party apps under `apps/`, each with a marker of its own. -- `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}{% if ci_strategy != 'github' %}, `mise :ci` the runner host{% endif %}; `mise :verify` checks the repo. +- `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}{% if ci_strategy != 'github' %}, `mise :ci` the runner host{% endif %}; `mise :check` checks the repo and `mise :test` runs check first. - The Plexus version the repo is on is the `version` of this marker, and its `plx` pin in `mise.toml` follows it, the collections in `requirements.yml` pinned to the same. diff --git a/templates/repo-operations/files/hk.pkl b/templates/repo-operations/files/hk.pkl index 1c360dc8..aad65538 100644 --- a/templates/repo-operations/files/hk.pkl +++ b/templates/repo-operations/files/hk.pkl @@ -13,8 +13,8 @@ hooks { } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index cd0b2244..bc709659 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -16,7 +16,7 @@ ansible = { version = "latest", uvx = true } # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true } -{%- if ci_strategy == 'hybrid' or ci_registry == 'own' %} +{%- if ci_strategy == 'hybrid' %} "npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } {%- endif %} @@ -46,10 +46,12 @@ run = './ansible-playbookw ci.yml' {% endif -%} [tasks.dev] description = "No-op: an operations repo has no development environment to start" +usage = 'arg "[name]" hide=#true' run = 'echo "dev: nothing to start in an operations repo"' [tasks.build] description = "No-op: an operations repo produces no artifact; third-party apps pin published images" +usage = 'arg "[name]" hide=#true' run = 'echo "build: nothing to build in an operations repo"' [tasks.lint] @@ -73,7 +75,8 @@ exit "$status" [tasks.check] depends = ["collections"] -description = "Static checks: lint, the contracts' checks (plx doctor), then playbook syntax against the pinned collections" +description = "Run every static check, executing no test: lint, the contracts' checks (plx doctor), then playbook syntax against the pinned collections" +usage = 'arg "[name]" hide=#true' run = [ 'mise run lint', 'plx doctor', @@ -87,12 +90,17 @@ run = [ ] [tasks.test] -description = "No-op: an operations repo has no tests that gate a deploy" -run = 'echo "test: nothing to test in an operations repo"' +description = "Run check, then every test that lives beside the code: an operations repo has none that gate a deploy" +usage = 'arg "[name]" hide=#true' +run = [ + 'mise run check', + 'echo "test: nothing to test in an operations repo"', +] -[tasks.verify] -description = "Perform all steps that verify code quality" -run = ['mise run check', 'mise run test'] +[tasks.e2e] +description = "No-op: an operations repo has no end-to-end suites; it neither checks nor tests" +usage = 'arg "[name]" hide=#true' +run = 'echo "e2e: nothing to run in an operations repo"' [tasks.collections] description = "Install the pinned plexus.* collections" diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 47b3c4b6..2a70de45 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -26,14 +26,6 @@ questions: - on-prem - hybrid - ci_registry: - type: str - help: "Where the app repos' runs keep the images they build and test (§ 8 PLX-Delivery): ghcr, the forge's registry, nothing to mount here; own, a registry on the tenant's object storage, whose monthly buckets this repo rotates" - choices: - - ghcr - - own - default: "{{ 'ghcr' if ci_strategy == 'github' else 'own' }}" - ci_overlay: type: str help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the inventory names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" diff --git a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja index 517cea35..b1f2f510 100644 --- a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja @@ -1,7 +1,7 @@ {% if publishes_packages %}{% raw %}name: on_pr # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# A package repo's pull-request mount, check and the changeset guard (§ 5 PLX-Delivery). +# A package repo's pull-request mount, the test job and the changeset guard (§ 5 PLX-Delivery). on: pull_request: @@ -15,12 +15,14 @@ concurrency: cancel-in-progress: true jobs: - check: + test: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - tasks: verify{% endraw %}{% if private_packages_scope %} + tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} + secrets: + op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} changeset-status: {% endraw %}{% if 'updates' in _templates %}{% raw %} # `changeset version` consumed the release branch's changesets, and the bot's branches get theirs from the @@ -55,7 +57,7 @@ jobs: {% endraw %}{% endif %}{% else %}{% raw %}name: on_pr # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's pull-request mount, check then verify (§ 2 PLX-Delivery). +# An app repo's pull-request mount, the test job, then the e2e job per app; it publishes and deploys nothing (§ 2 PLX-Delivery). on: pull_request: @@ -63,7 +65,7 @@ on: permissions: contents: read - packages: write + packages: read actions: read concurrency: @@ -71,21 +73,19 @@ concurrency: cancel-in-progress: true jobs: - check: + test: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - verify: - needs: check - uses: plexus-ms/tooling/.github/workflows/_verify.yml@0.133.0 + e2e: + needs: test + uses: plexus-ms/tooling/.github/workflows/_e2e.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}'{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 0f9cc504..d927952f 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -1,7 +1,7 @@ {% if publishes_packages %}{% raw %}name: on_push # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# A package repo's trunk mount, check then publish; started by hand on a branch, snapshot versions of it (§ 5 PLX-Delivery). +# A package repo's trunk mount, the test job then publish; started by hand on a branch, snapshot versions of it (§ 5 PLX-Delivery). on: push: @@ -26,15 +26,17 @@ permissions: {%- endif %}{% raw %} jobs: - check: + test: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - tasks: verify{% endraw %}{% if private_packages_scope %} + tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} + secrets: + op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} publish: - needs: check + needs: test uses: plexus-ms/tooling/.github/workflows/_publish-package.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} @@ -43,7 +45,7 @@ jobs: {% endraw %}{% else %}{% raw %}name: on_push # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's environment-branch mount, check, verify, release (§§ 2 and 3 PLX-Delivery). +# An app repo's environment-branch mount: the test job, the e2e job per app, then publish and deploy into the branch's environment (§§ 2 and 3 PLX-Delivery). on: # No paths filter: a branch created at a known commit pushes no files and would start nothing. @@ -57,53 +59,53 @@ permissions: actions: read jobs: - check: + # A newer push cancels the test and e2e jobs of an older one, never its publish or deploy. + test: concurrency: - group: on_push-verify-${{ github.ref }} + group: on_push-test-${{ github.ref }} cancel-in-progress: true uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - verify: - needs: check + e2e: + needs: test concurrency: - group: on_push-verify-${{ github.ref }} + group: on_push-test-${{ github.ref }} cancel-in-progress: true - uses: plexus-ms/tooling/.github/workflows/_verify.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_e2e.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} deploy: true alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}'{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - release: - needs: verify{% endraw %}{% if display_versions %}{% raw %} + # Only after the test job and every e2e job of the run: that is what makes a published image a tested one. + publish-deploy: + needs: [test, e2e]{% endraw %}{% if display_versions %}{% raw %} # Display versions (PLX-Releases): serialized per branch and never cancelled, so that two pushes to main # never take the same number, and allowed to write the tag and the GitHub Release of the version it cuts. concurrency: - group: on_push-release-${{ github.ref }} + group: on_push-publish-${{ github.ref }} cancel-in-progress: false permissions: contents: write packages: write actions: read{% endraw %}{% endif %}{% raw %} - uses: plexus-ms/tooling/.github/workflows/_release.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_publish-deploy.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} overlay: {% endraw %}{{ ci_overlay }}{% raw %} - apps: ${{ needs.verify.outputs.apps }} - deploys: ${{ needs.verify.outputs.deploys }} - environment: ${{ needs.verify.outputs.environment }}{% endraw %}{% if display_versions %} - display-versions: true{% endif %}{% raw %} + apps: ${{ needs.e2e.outputs.apps }} + deploys: ${{ needs.e2e.outputs.deploys }} + environment: ${{ needs.e2e.outputs.environment }}{% endraw %}{% if display_versions %} + display-versions: true{% endif %}{% if private_packages_scope %} + private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} {% endraw %}{% endif %} \ No newline at end of file diff --git a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja index 7493980a..50c831c0 100644 --- a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja @@ -1,7 +1,7 @@ {% raw %}name: on_commit # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's mount for a push to any other branch, check alone (§ 2 PLX-Delivery). +# An app repo's mount for a push to any other branch, the test job alone (§ 2 PLX-Delivery). on: push: @@ -17,11 +17,10 @@ concurrency: cancel-in-progress: true jobs: - check: + test: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} diff --git a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja deleted file mode 100644 index f911e7d4..00000000 --- a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja +++ /dev/null @@ -1,28 +0,0 @@ -{% raw %}name: housekeeping - -# Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# The retention of the candidates this repo leaves in the forge's registry (§ 8 PLX-Delivery). - -on: - schedule: - - cron: '41 4 * * *' - workflow_dispatch: - inputs: - dry_run: - description: Only list what would be deleted - type: boolean - default: false - -permissions: - contents: read - # Mounted here, not in the operations repo: only this repo's own token may delete versions of its packages. - packages: write - -jobs: - housekeeping: - uses: plexus-ms/tooling/.github/workflows/_housekeeping.yml@0.133.0 - with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: ghcr - dry-run: ${{ inputs.dry_run || false }} -{% endraw %} \ No newline at end of file diff --git a/templates/repo-turbo/files/PLEXUS.md.jinja b/templates/repo-turbo/files/PLEXUS.md.jinja index 37900d56..1124f865 100644 --- a/templates/repo-turbo/files/PLEXUS.md.jinja +++ b/templates/repo-turbo/files/PLEXUS.md.jinja @@ -3,7 +3,7 @@ {% else -%} - An app repo of `{{ tenant }}`: its apps under `apps/`, each with a marker of its own, and the workspace packages they share under `packages/`. {% endif -%} -- The verbs answer at the root, `mise :dev`, `mise :build` and `mise :verify`, and hand over to Turborepo, which runs each project's `package.json` scripts in the order of the workspace graph. +- The verbs answer at the root, `mise :dev`, `mise :build`, `mise :check`, `mise :test` and `mise :e2e`, and hand over to Turborepo, which runs each project's `package.json` scripts in the order of the workspace graph. {% if not publishes_packages and display_versions -%} - Display versions (PLX-Releases): a production release that changes an app cuts the version tag `.` with a GitHub Release, and the apps show their display version. `major` above is the major the next version takes; raise it in the pull request that warrants it, and the minor counts up by itself. diff --git a/templates/repo-turbo/files/hk.pkl b/templates/repo-turbo/files/hk.pkl index 6ec23d47..8f7c3682 100644 --- a/templates/repo-turbo/files/hk.pkl +++ b/templates/repo-turbo/files/hk.pkl @@ -10,12 +10,16 @@ hooks { check = "mise :lint {{ files }}" fix = "mise :lint --write {{ files }}" } + ["check"] { + depends = "lint" + check = "mise :check" + } } } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index bccbdf4f..9899a6ab 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -41,6 +41,10 @@ hk = "latest" {%- if not publishes_packages %} "npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } {%- endif %} +{%- if postgres %} +# The database of test and e2e: a real server from a binary, never a container or an emulation. +"conda:postgresql" = "{{ postgres }}" +{%- endif %} [settings] # Not a version source: it lets config_roots match a project without a mise config of its own, @@ -53,6 +57,12 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{% raw %}{{config_root}}{% endraw %}/node_modules/.bin"] +# Turbo hashes these where a turbo.json declares them: the platform on an app's build only, and never in the +# root's env or globalEnv, which would move the hash of every task; the major in the root's env of test and e2e. +PLX_PLATFORM = "{% raw %}{{ os() }}-{{ arch() }}{% endraw %}" +{%- if postgres %} +PLX_POSTGRES_MAJOR = "{{ postgres.split('.')[0] }}" +{%- endif %} {% if not publishes_packages -%} [tasks.promote] @@ -85,22 +95,45 @@ description = "Build the production artifacts, an app after the workspace packag {{ name_arg("build") }} run = ''' {{ scoped("build") }} -turbo run build ${dir:+--filter="{./$dir}..."} +./turbow trusted run build ${dir:+--filter="{./$dir}..."} ''' -[tasks.verify] -description = "Perform all steps that verify code quality" -{{ name_arg("verify") }} -run = [ - 'mise run check ${usage_name:+"$usage_name"}', - 'mise run test ${usage_name:+"$usage_name"}', -] +[tasks.check] +depends = ["install"] +description = "Run every static check, executing no test: lint (Biome) and the contracts' checks (plx doctor), repo-wide, then each project's check script" +{{ name_arg("check") }} +run = ''' +{{ scoped("check") }} +mise run lint +plx doctor +./turbow shared run check ${dir:+--filter="{./$dir}..."} +''' + +[tasks.test] +depends = ["install"] +description = "Run check, then every test that lives beside the code; no built app is needed" +{{ name_arg("test") }} +run = ''' +{{ scoped("test") }} +mise run check ${usage_name:+"$usage_name"} +./turbow shared run test ${dir:+--filter="{./$dir}..."} +''' + +[tasks.e2e] +depends = ["install"] +description = "Run the end-to-end suites, after the workspace packages they depend on are built; it neither checks nor tests" +{{ name_arg("e2e") }} +# A name selects the project and the projects that depend on it, since a suite is a package that depends on its app. +run = ''' +{{ scoped("e2e") }} +./turbow trusted run e2e ${dir:+--filter="...{./$dir}"} +''' [tasks.install] description = "Install and wire up project dependencies" hide = true run = "pnpm install" -sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] +sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", "e2e/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] outputs = ["node_modules/.pnpm/lock.yaml"] [tasks.lint] @@ -112,23 +145,3 @@ arg "" var=#true default="." help="Files or directories to lint (defaults ''' # usage shell-quotes var-arg values, so re-parse them via eval instead of bare expansion. run = 'eval "set -- $usage_paths"; biome check ${usage_write:+--write} --no-errors-on-unmatched "$@"' - -[tasks.check] -depends = ["install"] -description = "Run static checks on the codebase: lint and the contracts' checks (plx doctor), repo-wide, then each project's check script" -{{ name_arg("check") }} -run = ''' -{{ scoped("check") }} -mise run lint -plx doctor -turbo run check ${dir:+--filter="{./$dir}..."} -''' - -[tasks.test] -depends = ["install"] -description = "Run tests on the codebase" -{{ name_arg("test") }} -run = ''' -{{ scoped("test") }} -turbo run test ${dir:+--filter="{./$dir}..."} -''' diff --git a/templates/repo-turbo/files/pnpm-workspace.yaml.jinja b/templates/repo-turbo/files/pnpm-workspace.yaml.jinja index 0c11733a..f31060af 100644 --- a/templates/repo-turbo/files/pnpm-workspace.yaml.jinja +++ b/templates/repo-turbo/files/pnpm-workspace.yaml.jinja @@ -1,6 +1,7 @@ packages: {%- if not publishes_packages %} - "apps/*" + - "e2e/*" {%- endif %} - "packages/*" catalog: diff --git a/templates/repo-turbo/files/turbo.json.jinja b/templates/repo-turbo/files/turbo.json.jinja index b4ccd60e..d6472752 100644 --- a/templates/repo-turbo/files/turbo.json.jinja +++ b/templates/repo-turbo/files/turbo.json.jinja @@ -3,7 +3,16 @@ "tasks": { "build": { "dependsOn": ["^build"], - "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**", "!docker/compose*.yaml"], + "inputs": [ + "$TURBO_DEFAULT$", + "!**/{README,AGENTS,PLEXUS}.md", + "!docs/**", + "!docker/compose*.yaml", + "!**/*.{test,spec}.*", + "!**/{__tests__,__snapshots__}/**", + "!tests/**", + "!{vitest,playwright,jest}*.config.*" + ], "outputs": [{% if not publishes_packages %}".next/**", "!.next/cache/**", {% endif %}"dist/**"] }, "check": { @@ -11,9 +20,21 @@ "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**", "!docker/compose*.yaml"] }, "test": { - "dependsOn": ["build"], + "dependsOn": ["^build"], + "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], + {%- if postgres %} + "env": ["PLX_POSTGRES_MAJOR"], + {%- endif %} + // CI is passed through, never hashed: a pass on a developer's machine counts in CI, so no test may change what it tests by CI. + "passThroughEnv": ["CI"] + }, + "e2e": { + "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], - "passThroughEnv": ["CI", "DATABASE_URL", "E2E_*", "PLAYWRIGHT_*", "PW_TEST_*"] + {%- if postgres %} + "env": ["PLX_POSTGRES_MAJOR"], + {%- endif %} + "passThroughEnv": ["CI", "PLAYWRIGHT_BROWSERS_PATH"] }, "dev": { "cache": false, diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow new file mode 100755 index 00000000..110baee7 --- /dev/null +++ b/templates/repo-turbo/files/turbow @@ -0,0 +1,86 @@ +#!/bin/sh +# Generated from plexus-ms/tooling, templates/repo-turbo. +# Turbo with the remote cache its verb may use, as the tasks call it: ./turbow . +set -eu + +cache=${1:-} +case $cache in + shared | trusted) shift ;; + *) + echo "usage: ./turbow " >&2 + exit 2 + ;; +esac + +# Where and how artifacts go is turbow's alone: no remote-cache setting of the caller's shell reaches Turbo, and no +# artifact is signed. +unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_CACHE TURBO_REMOTE_CACHE_SIGNATURE_KEY \ + TURBO_REMOTE_CACHE_READ_ONLY TURBO_PREFLIGHT TURBO_REMOTE_ONLY + +reason= +# Outside a job of the forge no machine holds the trusted keys: every verb uses the shared server, by default this +# machine's own, run without a token. In a job (GITHUB_ACTIONS=true, which the forge's runner sets and CI alone does not) +# a verb uses only the server its job started (.github/actions/turbo-cache of plexus-ms/tooling), with the job's token, +# and build and e2e never use the shared one. A server named none is a tenant without the bucket. +if [ "${GITHUB_ACTIONS:-}" != true ]; then + from=shared server=${PLX_TURBO_SHARED:-http://127.0.0.1:8585} token=${PLX_TURBO_SHARED_TOKEN:-local} + if [ "$server" != none ] && ! node -e ' + fetch(process.argv[1], { signal: AbortSignal.timeout(2000) }).then( + (answer) => process.exit(answer.ok ? 0 : 1), + () => process.exit(1), + );' "$server/management/health"; then + reason="nothing answers at $server" + fi +elif [ "$cache" = trusted ]; then + if [ -z "${PLX_TURBO_TRUSTED:-}" ]; then + echo "turbow: in a job of the forge, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one" >&2 + exit 1 + fi + from=trusted server=$PLX_TURBO_TRUSTED token=${PLX_TURBO_TRUSTED_TOKEN:-local} +else + from=shared server=${PLX_TURBO_SHARED:-} token=${PLX_TURBO_SHARED_TOKEN:-local} + [ -n "$server" ] || reason="this job started no shared cache server (PLX_TURBO_SHARED is unset)" +fi +if [ "$server" = none ]; then + reason="the tenant has no $from bucket" +fi + +# The team keeps the repos of a tenant apart in a bucket: owner-repo, the last two names of the path of origin's URL +# (a nested group keeps its last two), in lower case, without .git, every character but [a-z0-9._-] a dash. +if [ -z "$reason" ]; then + if url=$(git remote get-url origin 2>/dev/null); then + path=$(printf '%s' "$url" | LC_ALL=C tr '[:upper:]' '[:lower:]') + case $path in + *://*) + path=${path#*://} + path=${path#*/} + ;; + *) case ${path%%/*} in *:*) path=${path#*:} ;; esac ;; + esac + path=${path%/} + path=${path%.git} + case $path in + */*) + rest=${path%/*} + team=$(printf '%s-%s' "${rest##*/}" "${path##*/}" | LC_ALL=C sed 's/[^a-z0-9._-]/-/g') + ;; + *) reason="origin's URL names no owner to name the team with ($url)" ;; + esac + else + reason="the checkout has no origin to name its team" + fi +fi + +if [ -n "$reason" ]; then + echo "turbow: without a remote cache: $reason" >&2 + # Told to Turbo too: a login and a linked repo would otherwise send the artifacts there. + export TURBO_API='' TURBO_TEAM='' TURBO_TOKEN='' TURBO_CACHE=local:rw +elif [ "$from" = trusted ]; then + echo "turbow: the trusted remote cache at $server, team $team" >&2 + # Never the local cache, which a shared run of this checkout may have filled from the shared bucket. + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE=remote:rw +else + echo "turbow: the shared remote cache at $server, team $team" >&2 + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE=local:rw,remote:rw +fi +exec turbo "$@" diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index f33158db..59438d7f 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -32,22 +32,13 @@ questions: ci_strategy: type: str - help: "Where the CI jobs run (§ 8 PLX-Delivery): github, the forge's runners; on-prem, container slots on runner hosts of the tenant's own for every job; hybrid, slots for the small and medium jobs and a throwaway cloud instance for each build and test" + help: "Where the CI jobs run (§ 8 PLX-Delivery): github, the forge's runners; on-prem, container slots on runner hosts of the tenant's own for every job; hybrid, slots for the small and medium jobs and a throwaway cloud instance for each app's e2e job" default: github choices: - github - on-prem - hybrid - ci_registry: - type: str - help: "Where the images a run builds and tests live before they are published (§ 8 PLX-Delivery): ghcr, the forge's registry; own, a registry on the tenant's object storage, which also holds Turbo's remote cache" - choices: - - ghcr - - own - default: "{{ 'ghcr' if ci_strategy == 'github' else 'own' }}" - when: "{{ not publishes_packages }}" - ci_overlay: type: str help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the inventory names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" @@ -76,6 +67,18 @@ questions: validator: "{% if major < 1 %}A major, 1 or higher{% endif %}" when: "{{ display_versions and not publishes_packages }}" + postgres: + type: str + help: "The PostgreSQL the repo's tests run against, as an exact version with major and minor, as in 18.6 (empty: none): mise installs that binary from conda-forge, and its major is an input of test and e2e" + default: "" + # An exact version as string tests, since the engine has no regex: two parts of ASCII digits, none with a leading zero + # but a lone 0. + validator: >- + {% if postgres %}{% set parts = postgres.split('.') %}{% set bad %}{% if parts | length != 2 %}x{% endif %}{% for + part in parts %}{% if part == '' or (part | length > 1 and part[0] == '0') %}x{% endif %}{% for c in part %}{% if c + not in '0123456789' %}x{% endif %}{% endfor %}{% endfor %}{% endset %}{% if bad %}An exact version, major and + minor, as in 18.6, or empty{% endif %}{% endif %} + policies: # The marker is born once: its body is the repo's own prose, which an update would conflict with, and # its frontmatter is plx's. diff --git a/tests/runner-image-base.sh b/tests/runner-image-base.sh new file mode 100755 index 00000000..72d3ca59 --- /dev/null +++ b/tests/runner-image-base.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Fails when the environment image is not built on the runtime base of the +# app-nextjs template, digest and all: a build in CI has to run in the image +# that ships (actions_runners' files/ci-runner/Dockerfile). +set -euo pipefail +cd "$(dirname "$0")/.." + +env_image=ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +runtime=templates/app-nextjs/files/docker/Dockerfile + +# The environment image's one base, and the app's last stage, the one that ships. +ours=$(awk '/^FROM / { print $2; exit }' "$env_image") +theirs=$(awk '/^FROM / { base = $2 } END { print base }' "$runtime") +if [ "$ours" != "$theirs" ]; then + echo "✗ $env_image is built on $ours, the runtime base of $runtime is $theirs" >&2 + exit 1 +fi diff --git a/tests/runner-slot-buildkit.sh b/tests/runner-slot-buildkit.sh new file mode 100755 index 00000000..8bf85755 --- /dev/null +++ b/tests/runner-slot-buildkit.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Fails unless every slot's container is told where the host's BuildKit +# service listens (actions_runners), from the one variable the service's +# configuration takes its port from: the role writes BUILDKIT_HOST from +# actions_runners_buildkit_port into slot.env, and files/ci-runner-slot hands +# it to the container, whatever its size; a publish job reads it there, and +# builds through the runner's Docker where it is unset. Runs the slot script +# with its paths moved into a directory of its own and docker replaced by a +# stub that prints the arguments, as runner-slot-mounts.sh does. +set -euo pipefail +cd "$(dirname "$0")/.." + +role=ansible/ci/roles/actions_runners +slot=$role/files/ci-runner-slot +failed=0 +port='{{ actions_runners_buildkit_port }}' +if ! grep -qxF " BUILDKIT_HOST=tcp://127.0.0.1:$port" "$role/tasks/main.yml"; then + echo "✗ the role writes no BUILDKIT_HOST=tcp://127.0.0.1:$port into slot.env" >&2 + failed=1 +fi +if ! grep -qF "address = [\"tcp://127.0.0.1:$port\"]" "$role/tasks/buildkit.yml"; then + echo "✗ the BuildKit service listens elsewhere than tcp://127.0.0.1:$port" >&2 + failed=1 +fi + +dir=$(mktemp -d) +trap 'rm -rf "$dir"' EXIT +mkdir "$dir/etc" "$dir/run" +sed -e "s|/etc/ci-runner/|$dir/etc/|g" -e "s|/run/ci-runner/|$dir/run/|g" \ + -e "s|/usr/bin/docker|$dir/docker|g" "$slot" >"$dir/ci-runner-slot" +printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >"$dir/docker" +chmod +x "$dir/docker" +printf 'IMAGE=image\nCACHE_DIR=/cache-dir\nBUILDKIT_HOST=tcp://127.0.0.1:4321\n' >"$dir/etc/slot.env" +for size in small medium large; do + printf 'MEMORY=1g\n' >"$dir/etc/size-$size.env" + : >"$dir/run/$size-1.env" + args=$(sh "$dir/ci-runner-slot" "$size-1") + if ! printf '%s\n' "$args" | grep -qx 'BUILDKIT_HOST=tcp://127.0.0.1:4321'; then + echo "✗ a $size slot is not given BUILDKIT_HOST" >&2 + failed=1 + fi +done +exit "$failed" diff --git a/tests/runner-slot-mounts.sh b/tests/runner-slot-mounts.sh new file mode 100755 index 00000000..974aa6dd --- /dev/null +++ b/tests/runner-slot-mounts.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Fails when a slot's container mounts other than its size allows +# (actions_runners' files/ci-runner-slot): a small slot, whose jobs hold the +# deploy and publish secrets, mounts nothing of the host's cache, the pnpm +# store included; a medium or large slot mounts the pnpm store and the +# directories of executables those sizes share. Runs the script itself, its +# paths moved into a directory of its own and docker replaced by a stub that +# prints the arguments. +set -euo pipefail +cd "$(dirname "$0")/.." + +slot=ansible/ci/roles/actions_runners/files/ci-runner-slot +dir=$(mktemp -d) +trap 'rm -rf "$dir"' EXIT +mkdir "$dir/etc" "$dir/run" +sed -e "s|/etc/ci-runner/|$dir/etc/|g" -e "s|/run/ci-runner/|$dir/run/|g" \ + -e "s|/usr/bin/docker|$dir/docker|g" "$slot" >"$dir/ci-runner-slot" +printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >"$dir/docker" +chmod +x "$dir/docker" +printf 'IMAGE=image\nCACHE_DIR=/cache-dir\n' >"$dir/etc/slot.env" + +home=/home/runner +shared="/cache-dir/corepack:$home/.cache/node/corepack +/cache-dir/mise/cache:$home/.cache/mise +/cache-dir/mise/data:$home/.local/share/mise +/cache-dir/mise/state:$home/.local/state/mise +/cache-dir/ms-playwright:$home/.cache/ms-playwright +/cache-dir/pnpm-store:/cache/pnpm-store" + +failed=0 +for size in small medium large; do + printf 'MEMORY=1g\n' >"$dir/etc/size-$size.env" + : >"$dir/run/$size-1.env" + args=$(sh "$dir/ci-runner-slot" "$size-1") + mounts=$(printf '%s\n' "$args" | awk 'prev ~ /^(-v|--volume|--mount)$/ { print } { prev = $0 }' | sort) + if printf '%s\n' "$args" | grep -qE '^--(volume|mount)='; then + echo "✗ a $size slot mounts with a flag this check does not read:" >&2 + printf '%s\n' "$args" | grep -E '^--(volume|mount)=' >&2 + failed=1 + continue + fi + if [ "$size" = small ]; then + if [ -n "$mounts" ] || printf '%s\n' "$args" | grep -q -e /cache-dir -e pnpm_config_store_dir; then + echo "✗ a small slot mounts or names the host's cache:" >&2 + printf '%s\n' "$args" | grep -e /cache-dir -e pnpm_config_store_dir >&2 || true + failed=1 + fi + else + if [ "$mounts" != "$shared" ] || ! printf '%s\n' "$args" | grep -qx pnpm_config_store_dir=/cache/pnpm-store; then + echo "✗ a $size slot mounts other than the shared caches:" >&2 + printf '%s\n' "$mounts" >&2 + failed=1 + fi + fi +done +exit "$failed"