diff --git a/.github/actions/turbo-cache/action.yml b/.github/actions/turbo-cache/action.yml deleted file mode 100644 index 492a917a..00000000 --- a/.github/actions/turbo-cache/action.yml +++ /dev/null @@ -1,156 +0,0 @@ -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, on a port nothing listens on from 8585 to 8684. -# The slots of a runner host share its loopback, so after each start the step checks by its token that the server answering is this job's. -# Where another job's server took the port, it starts the server again on another, up to three starts in all (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. -# -# Each start is the pinned action, whose own post step, at the end of the job, stops the server whose pid that start saved. -# A start that lost its port saved the pid of its own server, which had already exited: its post step finds no process with that pid, says so, and prints the server's log, which the server created before it tried the port. -# Another process of the job could in principle hold that pid by then and get the post step's SIGTERM. -# That is accepted: a slot is a pid namespace of its own, and Linux hands out pids in turn (kernel/pid.c), coming back to one only after every other up to pid_max, far more processes than a job starts. -# A start that failed outright saved no pid, and its post step fails; since the start continues on error, the job's conclusion stays success, as seen on a runner host. -# -# A job without vault credentials, whose vault item could not be read, or without a server of its own after the starts, runs on without that remote cache. -# It 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. - # One that lost its port to another job's server still reports success, since that server answers its health check: check tells the two apart. - # Without a free port it starts nothing: the action would fall back to a default port of its own. - - name: Start the cache server - id: server - if: ${{ steps.keys.outcome == 'success' && steps.plan.outputs.port != '' }} - 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: Check that the server is this job's - id: check - if: ${{ steps.keys.outcome == 'success' }} - shell: bash - env: - CACHE: ${{ inputs.cache }} - SERVER: ${{ steps.server.outcome }} - PORT: ${{ steps.plan.outputs.port }} - TOKEN: ${{ steps.plan.outputs.token }} - run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" check' - # Composite steps cannot loop: the second and the third start are steps of their own. - - name: Start the cache server on another port - id: server2 - if: ${{ steps.check.outputs.retry == 'true' }} - continue-on-error: true - uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 - env: - HOST: 127.0.0.1 - PORT: ${{ steps.check.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: Check that the server is this job's - id: check2 - if: ${{ steps.check.outputs.retry == 'true' }} - shell: bash - env: - CACHE: ${{ inputs.cache }} - SERVER: ${{ steps.server2.outcome }} - PORT: ${{ steps.check.outputs.port }} - TOKEN: ${{ steps.plan.outputs.token }} - run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" check' - - name: Start the cache server on another port - id: server3 - if: ${{ steps.check2.outputs.retry == 'true' }} - continue-on-error: true - uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 - env: - HOST: 127.0.0.1 - PORT: ${{ steps.check2.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' - # Announce checks the last start itself. - - name: Tell turbow where the server is - id: announce - shell: bash - env: - CACHE: ${{ inputs.cache }} - KEYS: ${{ steps.keys.outcome || 'skipped' }} - VAULT: ${{ steps.plan.outputs.vault }} - PORT: ${{ steps.check2.outputs.port || steps.check.outputs.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 deleted file mode 100755 index ec51b7f5..00000000 --- a/.github/actions/turbo-cache/turbo-cache.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env bash -# The three phases of the step turbo-cache (action.yml beside this file) that -# are its own, around the vault's read and the server's starts, 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: a port nothing -# listens on, 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. -# check Whether the server that answers on PORT, after a start of the server (SERVER, the outcome of that start), is this job's. -# The slots of a runner host share its loopback, so two jobs that plan at the same instant can pick one port. -# Only one server binds it, and the other job's start still reports success, as the action's own health check is answered by the server that did. -# The server is this job's when it takes the job's token (TOKEN) and refuses a token just minted, since only this job holds its token. -# Where a server not of this job answers, check picks another port, and the step starts the server again there; a start that failed is left to announce. -# Where no port is free, it keeps PORT and says so, and announce finds the server not this job's. -# Outputs: port, the port to use; retry, `true` when it is a new one. -# 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 on PORT is this job's, as check tells it; 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), no server of this job's -# on PORT, or no PORT, as no port was free. -# In these four the job runs on. -# -# The port is one nothing listens on, from 8585 to 8684, the search starting at a random one of them, so that jobs which plan at the same instant seldom pick the same port. -# Where they do, check finds it. -# Where all of them listen, plan's port is empty, the step starts no server, and announce says that no port was free. -# The server cannot be asked for any free port instead (PORT=0): the action health-checks the port it was given. -# -# 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 - -FIRST=8585 PORTS=100 - -# A port from FIRST on that nothing listens on, the search starting at a random one; nothing where all are taken. -pick() { - local start=$((0x$(openssl rand -hex 2) % PORTS)) n port - for ((n = 0; n < PORTS; n++)); do - port=$((FIRST + (start + n) % PORTS)) - if ! (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then - echo "$port" - return - fi - done -} - -# The HTTP status the server on 127.0.0.1:$1 answers Turbo's status request with the token $2; nothing where none answers. -status() ( - exec 3<>"/dev/tcp/127.0.0.1/$1" || exit 0 - printf 'GET /v8/artifacts/status HTTP/1.0\r\nHost: 127.0.0.1:%s\r\nAuthorization: Bearer %s\r\n\r\n' "$1" "$2" >&3 - read -r -t 5 _ code _ <&3 || true - echo "${code:-}" -) 2>/dev/null - -# Whether the server on 127.0.0.1:$1 is the one holding the token $2: it takes it and refuses another. -ours() { - [ -n "${1:-}" ] && [ "$(status "$1" "$2")" = 200 ] && [ "$(status "$1" "$(openssl rand -hex 32)")" = 401 ] -} - -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=$(pick) - 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" - ;; - check) - if ours "${PORT:-}" "${TOKEN:-}" || [ "${SERVER:-}" != success ]; then - echo "port=${PORT:-}" >>"$GITHUB_OUTPUT" - exit 0 - fi - next=$(pick) - if [ -z "$next" ]; then - echo "port=$PORT" >>"$GITHUB_OUTPUT" - echo "A server not of this job answers on 127.0.0.1:$PORT, and there is no free port in $FIRST–$((FIRST + PORTS - 1)) to start this job's server again." - exit 0 - fi - { - echo "port=$next" - echo "retry=true" - } >>"$GITHUB_OUTPUT" - echo "A server not of this job answers on 127.0.0.1:$PORT; this job starts its server again on 127.0.0.1:$next." - ;; - announce) - if [ "${KEYS:-}" = success ] && ours "${PORT:-}" "${TOKEN:-}"; 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:-}:${PORT:-} in - skipped:*) cause="This job has no vault to read the item $item from." ;; - success:) cause="There is no free port in $FIRST–$((FIRST + PORTS - 1)) for this job's cache server, so none was started." ;; - success:*) cause="This job's cache server did not come up on 127.0.0.1:${PORT:-} (the steps above say 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|check|announce" >&2 - exit 2 - ;; -esac diff --git a/.github/workflows/_check.yml b/.github/workflows/_check.yml index e1c434b4..5414a1ac 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_check.yml @@ -8,13 +8,10 @@ name: _check # every commit and every pull request; a repo with other verbs to run in the # same job names them in `tasks`. # -# 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). +# Turbo's shared remote cache (§ 8 PLX-Delivery): the repo's turbow reaches +# the shared server that the runner's slot or the repo's cache host names; a +# task whose inputs did not change is replayed from any earlier job or machine +# that wrote the bucket. This job starts no cache server. on: workflow_call: @@ -65,12 +62,6 @@ jobs: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || format('ci-{0}', inputs.size) }} steps: - uses: actions/checkout@v7 - - name: Start the shared cache server - uses: $/.github/actions/turbo-cache - with: - 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, diff --git a/ansible/ci/galaxy.yml b/ansible/ci/galaxy.yml index 6053be45..6379a737 100644 --- a/ansible/ci/galaxy.yml +++ b/ansible/ci/galaxy.yml @@ -8,8 +8,8 @@ authors: - David Julian Albers description: >- The tenant's own CI capacity (§ 8 PLX-Delivery): actions_runners, the container slots of a - runner host, and the playbook plexus.ci.playbook that mounts it with the host baseline on the - inventory group ci. + runner host, turbo_cache, its two Turbo remote cache servers, and the playbook + plexus.ci.playbook that mounts it with the host baseline on the inventory group ci. license: - GPL-3.0-or-later repository: https://github.com/plexus-ms/tooling diff --git a/ansible/ci/playbooks/playbook.yml b/ansible/ci/playbooks/playbook.yml index 573a35dc..bd24e5a1 100644 --- a/ansible/ci/playbooks/playbook.yml +++ b/ansible/ci/playbooks/playbook.yml @@ -10,8 +10,9 @@ # # Tags: every play carries its layer (`host`, `ci`) and every role its own # name. The slots mint their runner configs with the tenant's CI App and read -# the registry buckets with the storage key, both from the environment the -# wrapper resolves (secrets.env). +# the registry buckets with the storage key, and the Turbo cache servers read +# their buckets with their keys, all from the environment the wrapper +# resolves (secrets.env). - name: Host baseline of the CI hosts hosts: ci become: true @@ -44,6 +45,7 @@ tags: [always] roles: - { role: plexus.ci.actions_runners, tags: [actions_runners] } + - { role: plexus.ci.turbo_cache, tags: [turbo_cache] } - name: Lock down the CI hosts hosts: ci diff --git a/ansible/ci/roles/turbo_cache/defaults/main.yml b/ansible/ci/roles/turbo_cache/defaults/main.yml new file mode 100644 index 00000000..82ace736 --- /dev/null +++ b/ansible/ci/roles/turbo_cache/defaults/main.yml @@ -0,0 +1,70 @@ +--- +# The tenant's two Turbo remote cache servers on a runner host (§ 8 +# PLX-Delivery), brunojppb/turbo-cache-server, one per bucket: the shared one +# on port 8585 against -ci-turbo, which holds check and test and which +# every machine of the tenant writes, and the trusted one on port 8586 against +# -ci-turbo-trusted, which holds build and e2e and which only CI writes. +# Every runner host runs both for its own slots, and any number of hosts serve +# the same two buckets, so every machine of the tenant sees one cache. +# +# Each server is an instance of the systemd template unit ci-turbo-cache@ +# (shared, trusted), started from two files of /etc/ci-turbo-cache, both +# root's alone: .env, its address, port, bucket and the bucket's +# keys, and -token.env, the one token it takes. systemd reads them +# before the server starts as a user of its own (DynamicUser), which owns no +# file on the host; the server logs to the journal, one JSON line per event. +# A server that exits is started again after two seconds, without a limit. +# A change to the binary or a file restarts both, which cuts off a job's +# requests in flight; Turbo then runs those tasks without the cache. +# +# By default both listen on the host's loopback alone, and the host generates +# their tokens on its first run and keeps them on every later one; nothing +# sends them off the host. With turbo_cache_overlay the host is the tenant's +# cache host, the one its repos name in the answer turbo_cache_host: both +# listen on every address of the host, with the two fixed tokens of the run's +# environment, its own slots included, and the host firewall (plexus.host +# firewall, after this role) admits the two ports on the overlay's interface +# besides loopback, and on no other. That only CI reaches the trusted port +# there is owed by a policy of the tenant's overlay, set by hand; this role +# cannot make it. +# +# What a `repo` slot is handed, and nothing else is: the file +# /etc/ci-turbo-cache/slot.env, root's alone, which holds what repo-turbo's +# turbow reads, PLX_TURBO_SHARED, PLX_TURBO_TRUSTED and their tokens; and the +# same as facts once the role has run: turbo_cache_shared_url, +# turbo_cache_trusted_url, turbo_cache_shared_token, turbo_cache_trusted_token. +# The buckets' keys are in neither: they stay with the servers, and no job, +# development machine or agent holds one. +# +# Mount it in the playbook of plexus.ci before the firewall. + +# The tenant's slug, which names the buckets -ci-turbo and +# -ci-turbo-trusted. Required. +turbo_cache_owner: "" + +# The S3 store of both buckets, and a key per bucket that reads and writes it, +# from the environment of the playbook run; written root-only to the host and +# required on every run. +turbo_cache_s3_endpoint: "{{ lookup('env', 'CI_TURBO_S3_ENDPOINT') | default('', true) }}" +turbo_cache_s3_region: "{{ lookup('env', 'CI_TURBO_S3_REGION') | default('', true) }}" +turbo_cache_shared_access_key: "{{ lookup('env', 'CI_TURBO_SHARED_ACCESS_KEY') | default('', true) }}" +turbo_cache_shared_secret_key: "{{ lookup('env', 'CI_TURBO_SHARED_SECRET_KEY') | default('', true) }}" +turbo_cache_trusted_access_key: "{{ lookup('env', 'CI_TURBO_TRUSTED_ACCESS_KEY') | default('', true) }}" +turbo_cache_trusted_secret_key: "{{ lookup('env', 'CI_TURBO_TRUSTED_SECRET_KEY') | default('', true) }}" + +# Whether this host serves both servers on its overlay as the tenant's cache +# host, with the interface the firewall admits them on (wt0 is NetBird's) and +# the two fixed tokens, from the environment of the playbook run and required +# with it. +turbo_cache_overlay: false +turbo_cache_overlay_interface: wt0 +turbo_cache_overlay_shared_token: "{{ lookup('env', 'CI_TURBO_SHARED_TOKEN') | default('', true) }}" +turbo_cache_overlay_trusted_token: "{{ lookup('env', 'CI_TURBO_TRUSTED_TOKEN') | default('', true) }}" + +# The server, a static binary from its release on GitHub for linux-amd64, by +# version and the asset's SHA-256 (its digest on the release page); the two +# move together, by hand, since no update bot can rewrite the checksum of a +# download. Installed as /usr/local/bin/turbo-cache-server. +turbo_cache_version: 5.0.4 +turbo_cache_sha256: 5759a8ce1d02e1b17e375554ccacdef73e84af7556801743ad104606fa340d0d +turbo_cache_url: https://github.com/brunojppb/turbo-cache-server/releases/download/{{ turbo_cache_version }}/decay-x86_64-unknown-linux-musl diff --git a/ansible/ci/roles/turbo_cache/handlers/main.yml b/ansible/ci/roles/turbo_cache/handlers/main.yml new file mode 100644 index 00000000..9e4bd3ab --- /dev/null +++ b/ansible/ci/roles/turbo_cache/handlers/main.yml @@ -0,0 +1,8 @@ +--- +- name: Restart the cache servers + ansible.builtin.systemd_service: + name: ci-turbo-cache@{{ item }}.service + state: restarted + daemon_reload: true + # By name, as the tasks start them: an instance holds its keys and token. + loop: "{{ turbo_cache_instances | map(attribute='name') }}" diff --git a/ansible/ci/roles/turbo_cache/tasks/main.yml b/ansible/ci/roles/turbo_cache/tasks/main.yml new file mode 100644 index 00000000..e979c0b6 --- /dev/null +++ b/ansible/ci/roles/turbo_cache/tasks/main.yml @@ -0,0 +1,162 @@ +--- +- name: Require the owner, the store and the buckets' keys + ansible.builtin.assert: + that: + - turbo_cache_owner | length > 0 + - turbo_cache_s3_endpoint | length > 0 + - turbo_cache_s3_region | length > 0 + - turbo_cache_instances | rejectattr('access_key') | list | length == 0 + - turbo_cache_instances | rejectattr('secret_key') | list | length == 0 + fail_msg: >- + turbo_cache_owner names the buckets, and the run's environment holds the + store and a key per bucket: CI_TURBO_S3_ENDPOINT, CI_TURBO_S3_REGION, + CI_TURBO_SHARED_ACCESS_KEY, CI_TURBO_SHARED_SECRET_KEY, + CI_TURBO_TRUSTED_ACCESS_KEY and CI_TURBO_TRUSTED_SECRET_KEY. + +- name: Require the fixed tokens of the cache host + when: turbo_cache_overlay + ansible.builtin.assert: + that: turbo_cache_instances | rejectattr('token') | list | length == 0 + fail_msg: >- + With turbo_cache_overlay the run's environment holds the two fixed + tokens: CI_TURBO_SHARED_TOKEN and CI_TURBO_TRUSTED_TOKEN. + +- name: Install the cache server + ansible.builtin.get_url: + url: "{{ turbo_cache_url }}" + dest: /usr/local/bin/turbo-cache-server + checksum: sha256:{{ turbo_cache_sha256 }} + owner: root + group: root + mode: "0755" + notify: Restart the cache servers + +- name: Create the configuration directory + ansible.builtin.file: + path: /etc/ci-turbo-cache + state: directory + owner: root + group: root + mode: "0700" + +# The server takes its settings from its environment alone, and a .env file +# in its working directory or above, which / has none of. Path-style requests +# work with every S3 store. OTEL_SDK_DISABLED keeps it from building exporters +# for traces and metrics that nothing receives. +- name: Write each server's settings + no_log: true + ansible.builtin.copy: + dest: /etc/ci-turbo-cache/{{ item.name }}.env + owner: root + group: root + mode: "0600" + content: | + HOST={{ item.host }} + PORT={{ item.port }} + S3_ENDPOINT={{ turbo_cache_s3_endpoint }} + S3_REGION={{ turbo_cache_s3_region }} + S3_BUCKET_NAME={{ item.bucket }} + S3_ACCESS_KEY={{ item.access_key }} + S3_SECRET_KEY={{ item.secret_key }} + S3_USE_PATH_STYLE=true + OTEL_SDK_DISABLED=true + loop: "{{ turbo_cache_instances }}" + notify: Restart the cache servers + +# A fixed token replaces what the file holds; otherwise the file is written +# once, with a token generated here, and kept. +- name: Write each server's token + no_log: true + ansible.builtin.copy: + dest: /etc/ci-turbo-cache/{{ item.name }}-token.env + owner: root + group: root + mode: "0600" + force: "{{ item.token | length > 0 }}" + content: "TURBO_TOKEN={{ item.token or lookup('ansible.builtin.password', '/dev/null', chars=['ascii_lowercase', 'digits'], length=64) }}\n" + loop: "{{ turbo_cache_instances }}" + notify: Restart the cache servers + +- name: Read the tokens + no_log: true + ansible.builtin.slurp: + src: /etc/ci-turbo-cache/{{ item }}-token.env + loop: [shared, trusted] + register: turbo_cache_token_files + +- name: Offer the servers' addresses and tokens to the slots + no_log: true + ansible.builtin.set_fact: + turbo_cache_shared_url: http://127.0.0.1:8585 + turbo_cache_trusted_url: http://127.0.0.1:8586 + turbo_cache_shared_token: "{{ (turbo_cache_token_files.results[0].content | b64decode | trim)[12:] }}" + turbo_cache_trusted_token: "{{ (turbo_cache_token_files.results[1].content | b64decode | trim)[12:] }}" + +- name: Write what a repo slot is handed + no_log: true + ansible.builtin.copy: + dest: /etc/ci-turbo-cache/slot.env + owner: root + group: root + mode: "0600" + content: | + PLX_TURBO_SHARED={{ turbo_cache_shared_url }} + PLX_TURBO_SHARED_TOKEN={{ turbo_cache_shared_token }} + PLX_TURBO_TRUSTED={{ turbo_cache_trusted_url }} + PLX_TURBO_TRUSTED_TOKEN={{ turbo_cache_trusted_token }} + +# A user of its own per server, named for the instance: under one user the +# shared server, which the overlay reaches from development machines, could +# read the trusted one's environment. No LogsDirectory=: it sets +# LOGS_DIRECTORY, which makes the server write a log file there besides stdout, +# never rotated. No order after the overlay: an address of every interface +# needs none. +- name: Install the cache server unit + ansible.builtin.copy: + dest: /etc/systemd/system/ci-turbo-cache@.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Turbo remote cache server %i of the CI runner slots + Documentation=https://github.com/brunojppb/turbo-cache-server + After=network-online.target + Wants=network-online.target + StartLimitIntervalSec=0 + + [Service] + EnvironmentFile=/etc/ci-turbo-cache/%i.env + EnvironmentFile=/etc/ci-turbo-cache/%i-token.env + ExecStart=/usr/local/bin/turbo-cache-server + WorkingDirectory=/ + DynamicUser=yes + User=ci-turbo-cache-%i + Restart=always + RestartSec=2s + + [Install] + WantedBy=multi-user.target + notify: Restart the cache servers + +- name: Admit the two ports on the overlay's interface + when: turbo_cache_overlay + ansible.builtin.include_role: + name: plexus.host.firewall + tasks_from: fragment + vars: + firewall_fragment_name: ci-turbo-cache + firewall_fragment_rules: | + add rule inet firewall input iifname "{{ turbo_cache_overlay_interface }}" tcp dport { 8585, 8586 } accept + +- name: Flush handlers + ansible.builtin.meta: flush_handlers + +# By name: Ansible prints an item it loops over at -v, whatever its label, and +# an instance holds its keys and token. +- name: Enable and start the cache servers + ansible.builtin.systemd_service: + name: ci-turbo-cache@{{ item }}.service + enabled: true + state: started + loop: "{{ turbo_cache_instances | map(attribute='name') }}" diff --git a/ansible/ci/roles/turbo_cache/vars/main.yml b/ansible/ci/roles/turbo_cache/vars/main.yml new file mode 100644 index 00000000..61d0aced --- /dev/null +++ b/ansible/ci/roles/turbo_cache/vars/main.yml @@ -0,0 +1,20 @@ +--- +# The servers, each an instance of ci-turbo-cache@: the address it binds, its +# port, bucket and keys, and the fixed token it takes, where it takes one (an +# empty one the host generates). A pair bound to the overlay's address alone, +# beside a loopback pair with generated tokens, would be two more entries. +turbo_cache_instances: + - name: shared + host: "{{ '0.0.0.0' if turbo_cache_overlay else '127.0.0.1' }}" + port: 8585 + bucket: "{{ turbo_cache_owner }}-ci-turbo" + access_key: "{{ turbo_cache_shared_access_key }}" + secret_key: "{{ turbo_cache_shared_secret_key }}" + token: "{{ turbo_cache_overlay_shared_token if turbo_cache_overlay else '' }}" + - name: trusted + host: "{{ '0.0.0.0' if turbo_cache_overlay else '127.0.0.1' }}" + port: 8586 + bucket: "{{ turbo_cache_owner }}-ci-turbo-trusted" + access_key: "{{ turbo_cache_trusted_access_key }}" + secret_key: "{{ turbo_cache_trusted_secret_key }}" + token: "{{ turbo_cache_overlay_trusted_token if turbo_cache_overlay else '' }}" diff --git a/newborns/caches.ts b/newborns/caches.ts index 2540b0b2..f67b2baa 100644 --- a/newborns/caches.ts +++ b/newborns/caches.ts @@ -1,23 +1,25 @@ -// 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. -// Or the whole step, run from its action.yml (composite.ts), with the pinned action's own code starting the server as the runner runs it. +// Turbo's remote caches for the newborn tests: 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 role plexus.ci.turbo_cache installs on a runner +// host, the release asset its defaults pin, checked against their checksum. +// `serve` starts it here with the settings the role writes into its +// environment files, from an empty environment and an empty directory, so +// that nothing reaches it but those. 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 { createHash } from 'node:crypto'; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { type CompositeRun, runComposite } from './composite.ts'; +import { parse } from 'yaml'; import { adopt, sh, tryRun } from './helpers.ts'; const WORKSPACE = join(import.meta.dirname, '..'); -const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); +/** The role's defaults, which pin the server by version and checksum. */ +const ROLE_DEFAULTS = join(WORKSPACE, 'ansible', 'ci', 'roles', 'turbo_cache', 'defaults', 'main.yml'); const RUSTFS = 'rustfs/rustfs:1.0.5'; -const KEY = 'newborn-access'; -const SECRET = 'newborn-secret-not-a-real-one'; +/** The stand-in's keys: one pair, for both buckets. */ +export const KEY = 'newborn-access'; +export const SECRET = 'newborn-secret-not-a-real-one'; /** Waits until `url` answers 200, or throws after a minute. */ async function answers(url: string): Promise { @@ -33,48 +35,43 @@ async function answers(url: string): Promise { /** The S3 stand-in and the cache servers started against it. */ export interface Caches { - /** The stand-in's address, `http://127.0.0.1:`. */ + /** The stand-in's address on this machine, `http://127.0.0.1:`. */ s3: string; + /** The stand-in's container, which a test may connect to a network of its own. */ + container: 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; - /** - * The step turbo-cache for `cache`, run from its action.yml in `dir` as a job of the owner acme runs it, with the - * vault's read stood in for by the stand-in's keys; what the job's later steps get. - */ - step(cache: 'shared' | 'trusted', dir: string): Promise; - /** Kills the servers the steps started so far. */ - stopSteps(): void; + /** A cache server for `bucket` on `port` of 127.0.0.1, with `token`; 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 pinned action's code and its server's binary for this machine, at the commit the step pins, into `dir`. */ -async function fetchAction(dir: string): Promise<{ binary: string; main: string }> { - 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 into = join(dir, 'turbo-cache-server', 'action'); - mkdirSync(into, { recursive: true }); - for (const file of [name, 'main.mjs', 'util.mjs']) { - const answer = await fetch(`https://raw.githubusercontent.com/brunojppb/turbo-cache-server/${sha}/action/${file}`); - if (!answer.ok) throw new Error(`no ${file} at ${sha}: ${answer.status}`); - writeFileSync(join(into, file), Buffer.from(await answer.arrayBuffer())); +/** The server's binary as the role installs it, the release asset its defaults pin, into `dir`. */ +async function fetchServer(dir: string): Promise { + const defaults = parse(readFileSync(ROLE_DEFAULTS, 'utf8')) as Record; + const { turbo_cache_version: version, turbo_cache_sha256: sha256, turbo_cache_url: template } = defaults; + if (!version || !sha256 || !template) throw new Error(`${ROLE_DEFAULTS} pins no server`); + // The one Jinja expression of the URL, the version. + const url = template.replace(/\{\{\s*turbo_cache_version\s*\}\}/g, version); + const binary = join(dir, 'turbo-cache-server'); + if (!existsSync(binary)) { + const answer = await fetch(url); + if (!answer.ok) throw new Error(`${url}: ${answer.status}`); + const bytes = Buffer.from(await answer.arrayBuffer()); + const got = createHash('sha256').update(bytes).digest('hex'); + if (got !== sha256) throw new Error(`${url} has the sha256 ${got}, not ${sha256}`); + writeFileSync(binary, bytes); + chmodSync(binary, 0o755); } - chmodSync(join(into, name), 0o755); - return { binary: join(into, name), main: join(into, 'main.mjs') }; + return binary; } -/** RustFS with `buckets`, and the pinned action's code with its server's binary, in `dir`. */ +/** RustFS with `buckets`, and the server's binary, in `dir`. */ export async function startCaches(dir: string, buckets: string[]): Promise { const servers: ChildProcess[] = []; - // The servers the action started: each leads a process group of its own, which the action leaves running. - const actionServers: number[] = []; // 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( @@ -95,18 +92,11 @@ export async function startCaches(dir: string, buckets: string[]): Promise { - for (const pid of actionServers.splice(0)) - try { - process.kill(-pid, 'SIGKILL'); - } catch {} - }; const stop = async () => { for (const child of servers) try { if (child.pid) process.kill(-child.pid, 'SIGKILL'); } catch {} - stopSteps(); if (container) await tryRun('docker', ['rm', '-f', container], dir); }; try { @@ -126,9 +116,10 @@ export async function startCaches(dir: string, buckets: string[]): Promise setTimeout(resolve, 500)); } for (const bucket of buckets) await call('PUT', bucket); - const { binary, main } = await fetchAction(dir); + const binary = await fetchServer(dir); return { s3, + container, call, keys: async (bucket, team = 'acme-web') => { const xml = await call('GET', `${bucket}?list-type=2&prefix=${team}/`); @@ -137,13 +128,13 @@ export async function startCaches(dir: string, buckets: string[]): Promise { const cwd = join(dir, `server-${port}`); mkdirSync(cwd); + // What the role writes into the server's environment files. const child = spawn(binary, [], { cwd, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { - PATH: '/usr/bin:/bin', - OTEL_SDK_DISABLED: 'true', + HOST: '127.0.0.1', PORT: String(port), S3_ENDPOINT: s3, S3_REGION: 'us-east-1', @@ -151,7 +142,8 @@ export async function startCaches(dir: string, buckets: string[]): Promise { - mkdirSync(at, { recursive: true }); - return runComposite(STEP, { - dir: at, - inputs: { cache, 'op-service-account-token': 'a-service-account-token' }, - github: { repository_owner: 'acme' }, - env: { OP_CONNECT_HOST: '', OP_CONNECT_TOKEN: '' }, - uses: { - // The vault's read: each output the field its pointer names, from the stand-in. - '1password/load-secrets-action': async (env) => { - const fields: Record = { - endpoint: s3, - region: 'us-east-1', - 'access-key-id': KEY, - 'secret-access-key': SECRET, - }; - const outputs = Object.fromEntries( - Object.entries(env) - .filter(([, value]) => value.startsWith('op://acme-ci/')) - .map(([name, value]) => [name, fields[value.slice(value.lastIndexOf('/') + 1)] ?? '']), - ); - return { ok: true, outputs }; - }, - // The action's own code, as the runner starts it: a state file and a temporary directory of its own. - 'brunojppb/turbo-cache-server': async (env, own) => { - mkdirSync(join(own, 'tmp'), { recursive: true }); - const state = join(own, 'state'); - writeFileSync(state, ''); - const child = spawn(process.execPath, [main], { - cwd: own, - stdio: ['ignore', 'pipe', 'pipe'], - env: { - PATH: '/usr/bin:/bin', - OTEL_SDK_DISABLED: 'true', - TMPDIR: join(own, 'tmp'), - GITHUB_STATE: state, - ...env, - }, - }); - child.stdout?.resume(); - child.stderr?.resume(); - adopt(child); - const code = await new Promise((resolve) => child.on('close', resolve)); - // The server the action reports, where it still runs: one that lost its port has exited. - const pid = Number(/DECAY_SERVER_PID=(\d+)/.exec(readFileSync(state, 'utf8'))?.[1]); - try { - if (pid) process.kill(pid, 0); - if (pid) actionServers.push(pid); - } catch {} - return { ok: code === 0, outputs: {} }; - }, - }, - }); - }, - stopSteps, stop, }; } catch (error) { diff --git a/newborns/composite.ts b/newborns/composite.ts deleted file mode 100644 index b0c40da9..00000000 --- a/newborns/composite.ts +++ /dev/null @@ -1,192 +0,0 @@ -// A composite action of this repo, run as a runner of the forge runs one, for the newborn tests. -// Its steps run in order, each `if:` and each value of `env:` evaluated in the forge's expression language as far as this repo's actions use it: string literals, ==, !=, &&, ||, parentheses, format, and the contexts inputs, github and steps. -// A `run:` step runs in the runner's shell for `shell: bash`, with GITHUB_OUTPUT and GITHUB_ENV as files of its own; a `uses:` step runs the stand-in the caller gives for that action. -// What the job's later steps would get is what the steps wrote to GITHUB_ENV. -// A step that fails without continue-on-error fails the run, and an expression or an action it does not know is refused, never guessed. -// It runs no post step, so what an action does at the end of the job, as the server's action stopping its server, is not shown here. -import { readFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { parse } from 'yaml'; -import { tryRun } from './helpers.ts'; - -/** What a step left for the steps after it. */ -export interface StepResult { - outcome: 'success' | 'failure' | 'skipped'; - outputs: Record; -} - -/** A stand-in for a `uses:` step: given the step's evaluated `env:` and a directory of its own. */ -export type Uses = (env: Record, dir: string) => Promise & { ok: boolean }>; - -/** A run of the action: the job's environment it wrote, what its run steps printed, and each step by id. */ -export interface CompositeRun { - env: Record; - said: string; - steps: Record; -} - -interface Step { - id?: string; - if?: string; - env?: Record; - run?: string; - uses?: string; - 'continue-on-error'?: boolean; -} - -type Value = string | boolean; -interface Context { - inputs: Record; - github: Record; - steps: Record; -} - -const truthy = (value: Value) => value !== '' && value !== false; - -/** One expression, without its `${{ }}`. */ -export function evaluate(source: string, context: Context): Value { - const pattern = /\s*('(?:[^']|'')*'|==|!=|&&|\|\||[(),]|[A-Za-z_][\w.-]*)\s*/y; - const tokens: string[] = []; - while (pattern.lastIndex < source.length) { - const match = pattern.exec(source); - if (!match?.[1]) throw new Error(`cannot read the expression ${source}`); - tokens.push(match[1]); - } - let at = 0; - const next = () => { - const token = tokens[at++]; - if (token === undefined) throw new Error(`the expression ${source} ends early`); - return token; - }; - const either = (): Value => { - let value = both(); - while (tokens[at] === '||') { - at++; - const right = both(); - value = truthy(value) ? value : right; - } - return value; - }; - const both = (): Value => { - let value = compared(); - while (tokens[at] === '&&') { - at++; - const right = compared(); - value = truthy(value) ? right : value; - } - return value; - }; - const compared = (): Value => { - const left = primary(); - const operator = tokens[at]; - if (operator !== '==' && operator !== '!=') return left; - at++; - return (String(left) === String(primary())) === (operator === '=='); - }; - const primary = (): Value => { - const token = next(); - if (token === '(') { - const value = either(); - if (next() !== ')') throw new Error(`unbalanced parentheses in ${source}`); - return value; - } - if (token.startsWith("'")) return token.slice(1, -1).replaceAll("''", "'"); - if (tokens[at] === '(') { - if (token !== 'format') throw new Error(`no function ${token} here`); - at++; - const args: Value[] = []; - while (tokens[at] !== ')') { - args.push(either()); - if (tokens[at] === ',') at++; - } - at++; - return String(args[0]).replace(/\{(\d+)\}/g, (_, n) => String(args[Number(n) + 1] ?? '')); - } - const [root, ...path] = token.split('.'); - if (root !== 'inputs' && root !== 'github' && root !== 'steps') throw new Error(`no context ${root} here`); - let value: unknown = context[root]; - for (const part of path) value = value && typeof value === 'object' ? (value as Record)[part] : ''; - return typeof value === 'string' || typeof value === 'boolean' ? value : ''; - }; - const value = either(); - if (at !== tokens.length) throw new Error(`cannot read the expression ${source}`); - return value; -} - -const interpolate = (text: string, context: Context) => - text.replace(/\$\{\{(.*?)\}\}/g, (_, expression: string) => String(evaluate(expression, context))); - -/** `KEY=value` lines of a runner's file. */ -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)]), - ); - -/** - * Runs the composite action in `action` (its directory) in `dir`, with - * `inputs` over the defaults of its action.yml, the `github` context, `env` - * under every run step's own, and a stand-in for each action it uses, by its - * name without the ref. - */ -export async function runComposite( - action: string, - options: { - dir: string; - inputs: Record; - github: Record; - env?: Record; - uses: Record; - }, -): Promise { - const manifest = parse(readFileSync(join(action, 'action.yml'), 'utf8')); - const inputs: Record = {}; - for (const [name, input] of Object.entries(manifest.inputs ?? {})) - inputs[name] = options.inputs[name] ?? String((input as { default?: string }).default ?? ''); - const context: Context = { inputs, github: options.github, steps: {} }; - const jobEnv: Record = {}; - let said = ''; - for (const [n, step] of (manifest.runs.steps as Step[]).entries()) { - const condition = step.if?.replace(/^\s*\$\{\{(.*)\}\}\s*$/, '$1'); - let result: StepResult; - if (condition !== undefined && !truthy(evaluate(condition, context))) { - result = { outcome: 'skipped', outputs: {} }; - } else { - const env = Object.fromEntries( - Object.entries(step.env ?? {}).map(([name, value]) => [name, interpolate(String(value), context)]), - ); - const own = join(options.dir, `step-${n}`); - let ok: boolean; - let outputs: Record; - if (step.run !== undefined) { - const output = `${own}-output`; - const githubEnv = `${own}-env`; - writeFileSync(output, ''); - writeFileSync(githubEnv, ''); - const ran = await tryRun('bash', ['--noprofile', '--norc', '-eo', 'pipefail', '-c', step.run], options.dir, { - ...options.env, - ...jobEnv, - ...env, - GITHUB_ACTION_PATH: action, - GITHUB_OUTPUT: output, - GITHUB_ENV: githubEnv, - }); - said += ran.output; - ok = ran.ok; - outputs = pairs(output); - Object.assign(jobEnv, pairs(githubEnv)); - } else { - const name = step.uses?.replace(/@.*$/, '') ?? ''; - const stand = options.uses[name]; - if (!stand) throw new Error(`no stand-in for the action ${step.uses}`); - ({ ok, outputs } = await stand(env, own)); - } - if (!ok && !step['continue-on-error']) throw new Error(`the step ${step.id ?? n} failed:\n${said}`); - result = { outcome: ok ? 'success' : 'failure', outputs }; - } - if (step.id) context.steps[step.id] = result; - } - return { env: jobEnv, said, steps: context.steps }; -} diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 0350e4fa..22d74f36 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -42,9 +42,9 @@ // handlers for SIGINT, SIGTERM and SIGHUP (below, `running`). // // 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. +// names a server (PLX_TURBO_SHARED, PLX_TURBO_TRUSTED or the answer +// turbo_cache_host, read by repo-turbo's turbow): never one the user's shell +// names, and in CI no build fails for want of a trusted token. // // Time limit. A command that outlives LIMIT is killed with everything it // started, its whole process group. @@ -136,11 +136,14 @@ const PLX = join(WORKSPACE, 'packages', 'cli', 'dist', 'plx.js'); * prints the same with a terminal and without. * NO_COLOR is not set in its place: Playwright gives each of its workers * FORCE_COLOR=1, and Node warns in every one of them that NO_COLOR is ignored. + * A newborn's verbs run outside a job of the forge, where these tests run too, + * unless a test says its command is one (GITHUB_ACTIONS=true): in a job a + * newborn's build, e2e and publish read no local cache. */ 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, 'TURBO_FORCE', 'FORCE_COLOR']) delete env[name]; + for (const name of [...local, 'TURBO_FORCE', 'FORCE_COLOR', 'GITHUB_ACTIONS']) delete env[name]; return { ...env, ...world?.env, ...extra }; } @@ -334,8 +337,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', + PLX_TURBO_SHARED: '', + PLX_TURBO_TRUSTED: '', }; world = { dir, env }; try { diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index c0fbbd71..6cf7e2c0 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -1,150 +1,353 @@ -// 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. +// A runner host's two Turbo cache servers (the role plexus.ci.turbo_cache), and +// a newborn app repo that reaches them through repo-turbo's turbow. The runner +// host is a container of Debian with systemd as its init, privileged so that +// systemd and nftables work in it, on two Docker networks of the run's own: one +// stands in for the tenant's overlay, the other for the host's LAN, where the +// S3 stand-in of caches.ts is too. The role runs there as on a runner host: by +// ansible-playbook against localhost, from the collections of this checkout, +// with the firewall after it as the playbook has it, and with the buckets' +// keys in the run's environment. // -// 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 replays nothing, and the test built nothing. -// 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. -// Jobs of one runner host share its loopback: eight that run the whole step from its action.yml at the same instant, the pinned action's own code starting each server, each get a server of their own. -// It takes the job's token and refuses every other job's. -// Needs Docker and the network, as the newborns do. +// By default both servers run as units of the template ci-turbo-cache@, on the +// host's loopback alone, each with a token the host generated; their files are +// root's alone, each server runs as a user of its own, and the file a slot is +// handed holds the two addresses and tokens and no bucket key. A second run +// changes nothing and keeps the tokens. No run prints a bucket key or a token, +// at -vvv either. With turbo_cache_overlay the servers listen on every address +// with the fixed tokens of the run's environment, and the firewall admits them +// from the overlay's interface and from no other. +// +// Then a newborn app repo whose answer turbo_cache_host names that host by its +// overlay address. `mise run check` in one clone writes the shared bucket, and +// in a second clone every task replays. In a job of the forge, `mise run build` +// writes the trusted bucket with the trusted token, and without it fails in one +// line; a build after a test in one checkout replays nothing, and the test +// built nothing. With the shared server stopped, check says so in one line and +// runs. No remote-cache setting of the caller's shell, and neither a Turbo +// login nor a linked repo, sends a request anywhere. 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 { type Caches, KEY, SECRET, 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'; +/** The fixed tokens of the host that serves the overlay, as its playbook run's environment holds them. */ +const FIXED = { shared: 'a-fixed-shared-token', trusted: 'a-fixed-trusted-token' }; +/** A Debian runner host with systemd, and what the role and the firewall run with, so that a run needs no apt. */ +const IMAGE = 'plx-newborn-runner-host:trixie'; +const DOCKERFILE = `FROM debian:trixie +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \\ + systemd systemd-sysv dbus ansible-core python3-apt nftables iproute2 ca-certificates curl \\ + && rm -rf /var/lib/apt/lists/* +CMD ["/sbin/init"] +`; +const PLAYBOOK = `- name: The cache servers of a runner host + hosts: localhost + connection: local + gather_facts: false + roles: + - plexus.ci.turbo_cache + - plexus.host.firewall +`; let here = ''; let caches: Caches | undefined; +const networks: string[] = []; +let host = ''; +/** The runner host's address on the overlay and on its LAN, and the overlay's interface there. */ +let overlayIp = ''; +let lanIp = ''; +let overlayIf = ''; +/** The S3 stand-in's address on the LAN. */ +let s3Lan = ''; -/** 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); +/** The address of `container` on `network`. */ +const ip = async (container: string, network: string) => + ( + await sh( + 'docker', + ['inspect', '-f', `{{(index .NetworkSettings.Networks "${network}").IPAddress}}`, container], + here, + ) + ).trim(); -/** 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); +/** A command on the runner host, which must pass; its output. */ +const onHost = (...command: string[]) => sh('docker', ['exec', host, ...command], here); before(async () => { here = await open('turbo-cache'); caches = await startCaches(here, [SHARED_BUCKET, TRUSTED_BUCKET]); + for (const kind of ['overlay', 'lan']) { + const name = `plx-newborn-${process.pid}-${kind}`; + await sh('docker', ['network', 'create', name], here); + networks.push(name); + } + const [overlay = '', lan = ''] = networks; + await sh('docker', ['network', 'connect', lan, caches.container], here); + s3Lan = await ip(caches.container, lan); + put(here, { 'runner-host/Dockerfile': DOCKERFILE, 'play/site.yml': PLAYBOOK }); + await sh('docker', ['build', '-q', '-t', IMAGE, join(here, 'runner-host')], here); + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--privileged', + '--cgroupns=private', + '--tmpfs', + '/run', + '--tmpfs', + '/run/lock', + '--cpus', + '4', + '--memory', + '4g', + '--pids-limit', + '2000', + '--network', + overlay, + '-v', + `${join(WORKSPACE, 'ansible')}:/collections/ansible_collections/plexus:ro`, + '-v', + `${join(here, 'play')}:/play:ro`, + IMAGE, + ], + here, + ) + ).match(/^[0-9a-f]{64}$/m); + host = started?.[0] ?? ''; + if (!host) throw new Error('docker run printed no container id'); + await sh('docker', ['network', 'connect', lan, host], here); + overlayIp = await ip(host, overlay); + lanIp = await ip(host, lan); + const addresses: { ifname: string; addr_info: { local: string }[] }[] = JSON.parse( + await onHost('ip', '-j', '-4', 'addr'), + ); + overlayIf = addresses.find((a) => a.addr_info.some((info) => info.local === overlayIp))?.ifname ?? ''; + // Up, or up with a unit of the container's that failed: either way systemd answers. + await tryRun('docker', ['exec', host, 'systemctl', 'is-system-running', '--wait'], here); }); after(async () => { + if (host) await tryRun('docker', ['rm', '-f', host], here); await caches?.stop(); + for (const network of networks) await tryRun('docker', ['network', 'rm', network], here); 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, +/** One run of the role and the firewall on the runner host, with `vars`, the run's environment `env`, and `args`. */ +async function play(vars: Record = {}, env: Record = {}, args: string[] = []) { + const environment = { + ANSIBLE_COLLECTIONS_PATH: '/collections', + ANSIBLE_NOCOLOR: '1', + CI_TURBO_S3_ENDPOINT: `http://${s3Lan}:9000`, + CI_TURBO_S3_REGION: 'us-east-1', + CI_TURBO_SHARED_ACCESS_KEY: KEY, + CI_TURBO_SHARED_SECRET_KEY: SECRET, + CI_TURBO_TRUSTED_ACCESS_KEY: KEY, + CI_TURBO_TRUSTED_SECRET_KEY: SECRET, + ...env, + }; + const output = await onHost( + 'env', + ...Object.entries(environment).map(([name, value]) => `${name}=${value}`), + 'ansible-playbook', + '-i', + 'localhost,', + '/play/site.yml', + '-e', + JSON.stringify({ turbo_cache_owner: 'acme', ...vars }), + ...args, ); - -/** 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; + const changed = Number(/localhost\s*:\s*ok=\d+\s+changed=(\d+)/.exec(output)?.[1] ?? Number.NaN); + return { output, changed }; } -/** 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') +/** The file a slot is handed, as pairs. */ +async function slotEnv(): Promise> { + const text = await onHost('cat', '/etc/ci-turbo-cache/slot.env'); + return 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 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, +/** The local addresses listening on 8585 and 8586, sorted. */ +const listeners = async () => + (await onHost('ss', '-ltnH')) + .split('\n') + .map((line) => line.trim().split(/\s+/)[3] ?? '') + .filter((address) => /:858[56]$/.test(address)) + .sort(); + +/** The status a server on the runner host answers Turbo's first request with, asked there. */ +const statusOnHost = async (port: number, token: string) => + ( + await onHost( + 'curl', + '-s', + '-o', + '/dev/null', + '-w', + '%{http_code}', + '-H', + `Authorization: Bearer ${token}`, + `http://127.0.0.1:${port}/v8/artifacts/status`, + ) + ).trim(); + +/** A bucket key per bucket, each of its own, which the S3 stand-in takes none of: the servers start with them all the same. */ +const OTHER_KEYS = { + CI_TURBO_SHARED_ACCESS_KEY: 'shared-access-not-real', + CI_TURBO_SHARED_SECRET_KEY: 'shared-secret-not-real', + CI_TURBO_TRUSTED_ACCESS_KEY: 'trusted-access-not-real', + CI_TURBO_TRUSTED_SECRET_KEY: 'trusted-secret-not-real', +}; + +/** The secrets of `named` that a playbook run's output holds, by name. */ +const leaked = (output: string, named: Record) => + Object.entries(named) + .filter(([, secret]) => output.includes(secret)) + .map(([name]) => name); + +/** Whether a run restarted the servers. */ +const restarted = (output: string) => + /RUNNING HANDLER \[plexus\.ci\.turbo_cache : Restart the cache servers\]/.test(output); + +/** The main process of each server unit. */ +const mainPids = async () => + Promise.all( + ['shared', 'trusted'].map(async (n) => + (await onHost('systemctl', 'show', '-P', 'MainPID', `ci-turbo-cache@${n}`)).trim(), + ), + ); + +describe('a runner host’s two cache servers', () => { + test('at -vvv, a first run and a run that restarts the servers print no bucket key and no token', async () => { + const first = await play({}, OTHER_KEYS, ['-vvv']); + const slot = await slotEnv(); + const generated = { shared: slot.PLX_TURBO_SHARED_TOKEN ?? '', trusted: slot.PLX_TURBO_TRUSTED_TOKEN ?? '' }; + assert.deepEqual(leaked(first.output, { ...OTHER_KEYS, ...generated }), []); + // The keys the stand-in takes: every server file changes, and the servers restart. + const again = await play({}, {}, ['-vvv']); + assert.ok(restarted(again.output), 'the servers restarted'); + assert.deepEqual(leaked(again.output, { ...OTHER_KEYS, KEY, SECRET, ...generated }), []); }); - assert.ok(ran.ok, ran.output); - return { said: ran.output, outputs: pairs(output), env: pairs(githubEnv) }; -} -describe('jobs of one runner host that start the step at the same instant', () => { - /** The status the server at `url` answers a request of Turbo's with `token`. */ - const status = async (url: string, token: string) => - (await fetch(`${url}/v8/artifacts/status`, { headers: { Authorization: `Bearer ${token}` } })).status; + test('by default both run, on loopback alone, each with a token the host generated, from files only root reads', async () => { + await play(); + assert.equal( + (await onHost('systemctl', 'is-active', 'ci-turbo-cache@shared', 'ci-turbo-cache@trusted')).trim(), + 'active\nactive', + ); + assert.equal( + (await onHost('systemctl', 'is-enabled', 'ci-turbo-cache@shared', 'ci-turbo-cache@trusted')).trim(), + 'enabled\nenabled', + ); + assert.deepEqual(await listeners(), ['127.0.0.1:8585', '127.0.0.1:8586']); + const modes = await onHost( + 'sh', + '-c', + 'stat -c "%U %a %n" /etc/ci-turbo-cache /etc/ci-turbo-cache/* /usr/local/bin/turbo-cache-server /etc/systemd/system/ci-turbo-cache@.service', + ); + assert.deepEqual(modes.trim().split('\n'), [ + 'root 700 /etc/ci-turbo-cache', + 'root 600 /etc/ci-turbo-cache/shared-token.env', + 'root 600 /etc/ci-turbo-cache/shared.env', + 'root 600 /etc/ci-turbo-cache/slot.env', + 'root 600 /etc/ci-turbo-cache/trusted-token.env', + 'root 600 /etc/ci-turbo-cache/trusted.env', + 'root 755 /usr/local/bin/turbo-cache-server', + 'root 644 /etc/systemd/system/ci-turbo-cache@.service', + ]); + const slot = await slotEnv(); + assert.deepEqual(Object.keys(slot).sort(), [ + 'PLX_TURBO_SHARED', + 'PLX_TURBO_SHARED_TOKEN', + 'PLX_TURBO_TRUSTED', + 'PLX_TURBO_TRUSTED_TOKEN', + ]); + assert.equal(slot.PLX_TURBO_SHARED, 'http://127.0.0.1:8585'); + assert.equal(slot.PLX_TURBO_TRUSTED, 'http://127.0.0.1:8586'); + const shared = slot.PLX_TURBO_SHARED_TOKEN ?? ''; + const trusted = slot.PLX_TURBO_TRUSTED_TOKEN ?? ''; + assert.match(shared, /^[a-z0-9]{64}$/); + assert.match(trusted, /^[a-z0-9]{64}$/); + assert.notEqual(shared, trusted); + // Each server takes its own token and refuses the other's. + assert.equal(await statusOnHost(8585, shared), '200'); + assert.equal(await statusOnHost(8586, trusted), '200'); + assert.equal(await statusOnHost(8585, trusted), '401'); + assert.equal(await statusOnHost(8586, shared), '401'); + // Each server runs as a user of its own, no user of the host's and root least of all, so that the shared one + // cannot read the trusted one's keys. + const users = await Promise.all( + (await mainPids()).map(async (pid) => (await onHost('stat', '-c', '%u', `/proc/${pid}`)).trim()), + ); + assert.ok(!users.includes('0'), `${users}`); + assert.notEqual(users[0], users[1]); + }); - test('each of eight gets a server of its own, which takes its token and refuses every other job’s', async () => { - const all = caches as Caches; - for (let round = 1; round <= 3; round++) { + test('a second run changes nothing: the same tokens, the servers not restarted', async () => { + const [tokens, pids] = [await slotEnv(), await mainPids()]; + const again = await play(); + assert.equal(again.changed, 0, again.output); + assert.deepEqual(await slotEnv(), tokens); + assert.deepEqual(await mainPids(), pids); + }); + + test('with turbo_cache_overlay, they listen on every address with the fixed tokens, admitted from the overlay alone', async () => { + const overlay = { turbo_cache_overlay: true, turbo_cache_overlay_interface: overlayIf }; + const tokens = { CI_TURBO_SHARED_TOKEN: FIXED.shared, CI_TURBO_TRUSTED_TOKEN: FIXED.trusted }; + // At -vvv neither the run that moves the servers onto the overlay nor one that changes their keys prints a secret. + const moved = await play(overlay, { ...tokens, ...OTHER_KEYS }, ['-vvv']); + assert.ok(restarted(moved.output), 'the servers restarted'); + assert.deepEqual(leaked(moved.output, { ...OTHER_KEYS, ...tokens }), []); + const rekeyed = await play(overlay, tokens, ['-vvv']); + assert.ok(restarted(rekeyed.output), 'the servers restarted'); + assert.deepEqual(leaked(rekeyed.output, { ...OTHER_KEYS, KEY, SECRET, ...tokens }), []); + assert.deepEqual(await listeners(), ['0.0.0.0:8585', '0.0.0.0:8586']); + const slot = await slotEnv(); + assert.equal(slot.PLX_TURBO_SHARED_TOKEN, FIXED.shared); + assert.equal(slot.PLX_TURBO_TRUSTED_TOKEN, FIXED.trusted); + assert.equal(slot.PLX_TURBO_SHARED, 'http://127.0.0.1:8585', 'the host’s own slots on loopback still'); + const status = async (address: string, port: number, token: string) => { try { - const jobs = await Promise.all( - Array.from({ length: 8 }, (_, n) => all.step('trusted', join(here, 'same-instant', `${round}-${n}`))), - ); - const servers = jobs.map(({ env }) => ({ - url: env.PLX_TURBO_TRUSTED ?? '', - token: env.PLX_TURBO_TRUSTED_TOKEN ?? '', - })); - const urls = servers.map(({ url }) => url); - for (const url of urls) assert.match(url, /^http:\/\/127\.0\.0\.1:\d+$/, `round ${round}: ${urls}`); - assert.equal(new Set(urls).size, 8, `round ${round}: every job a port of its own: ${urls}`); - for (const [n, { url, token }] of servers.entries()) { - assert.equal(await status(url, token), 200, `round ${round}, job ${n}: its own token at ${url}`); - for (const [m, other] of servers.entries()) - if (m !== n) - assert.equal(await status(url, other.token), 401, `round ${round}: job ${m}'s token at ${url}`); - } - } finally { - all.stopSteps(); + const answer = await fetch(`http://${address}:${port}/v8/artifacts/status`, { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(3000), + }); + return answer.status; + } catch { + return 0; } - } + }; + assert.equal(await status(overlayIp, 8585, FIXED.shared), 200, 'the shared server on the overlay'); + assert.equal(await status(overlayIp, 8586, FIXED.trusted), 200, 'the trusted server on the overlay'); + assert.equal(await status(lanIp, 8585, FIXED.shared), 0, 'nothing answers on the LAN'); + assert.equal(await status(lanIp, 8586, FIXED.trusted), 0, 'nothing answers on the LAN'); + const again = await play(overlay, tokens); + assert.equal(again.changed, 0, again.output); }); }); -describe('a newborn app repo with the two remote caches', () => { +describe('a newborn app repo that names the runner host as its cache host', () => { let origin = ''; let sharedUrl = ''; - let sharedLog: string[] = []; + let trustedUrl = ''; before(async () => { - origin = await born(join(here, 'web'), ['repo-turbo', 'updates'], { tenant: 'acme' }); + sharedUrl = `http://${overlayIp}:8585`; + trustedUrl = `http://${overlayIp}:8586`; + origin = await born(join(here, 'web'), ['repo-turbo', 'updates'], { tenant: 'acme', turbo_cache_host: overlayIp }); // 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}`, @@ -165,56 +368,97 @@ describe('a newborn app repo with the two remote caches', () => { 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; + /** 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 the origin, its origin at `remote`, with its tools installed: what a checkout on another machine is. */ + async function clone(name: string, remote: string): Promise { + const dir = join(here, name); + await git(here, 'clone', '-q', origin, 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; } /** 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 or an agent's: no job of the forge, though CI may be set, and the shared token. */ + const machine = () => ({ GITHUB_ACTIONS: '', CI: 'true', PLX_TURBO_SHARED_TOKEN: FIXED.shared }); + /** A job on the forge's runners that joined the overlay: both tokens. */ + const job = () => ({ GITHUB_ACTIONS: 'true', CI: 'true', ...tokens() }); + const tokens = () => ({ PLX_TURBO_SHARED_TOKEN: FIXED.shared, PLX_TURBO_TRUSTED_TOKEN: FIXED.trusted }); + const escaped = (url: string) => url.replaceAll('.', '\\.'); - /** 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('mise run check writes the shared bucket from one clone, and in a second clone every task replays', async () => { + const first = await clone('first', 'https://github.com/acme/web.git'); + const checked = await verb(first, 'check', machine()); + assert.match(checked, new RegExp(`turbow: the shared remote cache at ${escaped(sharedUrl)}, team acme-web`)); + assert.match(checked, /check-ran site/); + assert.ok((await (caches as Caches).keys(SHARED_BUCKET)).length >= 2, 'the shared bucket holds the checks'); - 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()); + const second = await clone('second', 'git@github.com:acme/web.git'); + const again = await verb(second, 'check', machine()); assert.match(again, /cache hit, replaying logs/); assert.doesNotMatch(again, /cache miss/, 'every task of the second clone is a hit'); + }); + + test('in a job of the forge, build writes the trusted bucket with the trusted token, and without it fails in one line', async () => { + const dir = await clone('trusted-job', 'https://github.com/acme/web'); + const built = await verb(dir, 'build', job()); + assert.match(built, new RegExp(`turbow: the trusted remote cache at ${escaped(trustedUrl)}, team acme-web`)); + assert.ok((await (caches as Caches).keys(TRUSTED_BUCKET)).length >= 2, 'the trusted bucket holds the builds'); + const ran = await tryRun('mise', ['run', 'build'], dir, { ...job(), PLX_TURBO_TRUSTED_TOKEN: '' }); + assert.equal(ran.ok, false); + assert.equal(ran.output.split('\n').filter((line) => line.startsWith('turbow:')).length, 1, ran.output); + assert.match(ran.output, /turbow: .*PLX_TURBO_TRUSTED_TOKEN is unset/); + assert.doesNotMatch(ran.output, /build-ran/); + }); - // 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('in a job, a build after a test in one checkout replays nothing, and the test built nothing', async () => { + // A repo of its own name, so that neither bucket holds its tasks yet. + const dir = await clone('one-checkout', 'https://github.com/acme/one-checkout'); + const tested = await verb(dir, 'test', job()); + assert.doesNotMatch(tested, /lib:build/, 'in an app repo the test waits for no build'); + const built = await verb(dir, 'build', job()); + assert.doesNotMatch(built, /cache hit/, 'nothing replayed'); + assert.match(built, missed('lib:build')); + assert.match(built, missed('site:build')); + const written = await (caches as Caches).keys(TRUSTED_BUCKET, 'acme-one-checkout'); + assert.equal(written.length, 2, 'both builds reached the trusted bucket'); }); - test('on a developer’s machine with a Turbo login and a linked repo, a verb without a server sends nothing anywhere', async () => { + test('with the shared server stopped, check says so in one line and runs every task', async () => { + const dir = await clone('stopped', 'https://github.com/acme/web'); + await onHost('systemctl', 'stop', 'ci-turbo-cache@shared'); + try { + const checked = await verb(dir, 'check', machine()); + assert.match(checked, new RegExp(`turbow: without a remote cache: nothing answers at ${escaped(sharedUrl)}`)); + assert.match(checked, /check-ran site/); + } finally { + await onHost('systemctl', 'start', 'ci-turbo-cache@shared'); + } + }); + + test('no remote-cache setting of the caller’s shell, no Turbo login and no linked repo sends a request anywhere', async () => { let hits = 0; + const urls: string[] = []; const listener = createServer((req, res) => { hits++; + urls.push(req.url ?? ''); req.resume(); res.statusCode = 404; res.end(); @@ -222,76 +466,45 @@ describe('a newborn app repo with the two remote caches', () => { 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'); + const elsewhere = `http://127.0.0.1:${port}`; + const dir = await clone('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(dir, { '.turbo/config.json': { apiUrl: elsewhere, teamId: 'team_linked', 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); + const shell = { + TURBO_CONFIG_DIR_PATH: join(here, 'turbo-login'), + TURBO_API: elsewhere, + TURBO_TEAM: 'someone', + TURBO_TOKEN: 'secret', + TURBO_LOGIN: elsewhere, + TURBO_REMOTE_ONLY: 'true', + TURBO_PREFLIGHT: 'true', + }; + // With the cache host's server, and without a token for it. + const served = await verb(dir, 'check', { ...machine(), ...shell }); + assert.match(served, new RegExp(`turbow: the shared remote cache at ${escaped(sharedUrl)}`)); + const journal = await onHost('journalctl', '-q', '-u', 'ci-turbo-cache@shared', '-o', 'cat'); + assert.match(journal, /slug=acme-web/, 'the cache host’s server was asked'); + assert.doesNotMatch(journal, /team_linked/, 'with no team of the link’s'); + for (const task of ['check', 'build']) { + const ran = await verb(dir, task, { ...machine(), ...shell, PLX_TURBO_SHARED_TOKEN: '' }); 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'); + assert.equal(hits, 0, 'no request reached the server the shell, the login or the link names'); // 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); + const alone = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'check', '--force'], dir, { + TURBO_CONFIG_DIR_PATH: join(here, 'turbo-login'), + }); assert.ok(alone.ok, alone.output); assert.ok(hits > 0, 'Turbo alone reaches the linked server'); + assert.ok( + urls.some((url) => url.includes('teamId=team_linked')), + `with the link's team: ${urls.join(' ')}`, + ); } 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 replays nothing, and the test built nothing', 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.doesNotMatch(tested, /lib:build/, 'in an app repo the test waits for no build'); - 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/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index d277e1dd..b836a676 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -2283,13 +2283,13 @@ for (const [template, answers, edits] of [ const end = snapshot(human); const expected = { ...start }; expected['PLEXUS.md'] = { - // The question repo-turbo has gained since the move is spliced into the marker, as an empty answer, and the + // The questions repo-turbo has gained since the move are spliced into the marker, as empty answers, 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-turbo' ? { postgres: '', turbo_cache_host: '' } : {}), }), template === 'repo-operations' ? ['ci_registry'] : [], ), @@ -2300,8 +2300,8 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - // 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 + // Both templates have changed since the move (their verbs, their hooks, questions more in repo-turbo), so what the + // update took in of them is no longer the repo as it was: the marker, with those questions 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))); diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 93b2661c..9080752d 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -1499,6 +1499,24 @@ test('every key of the markers is checked, each finding naming its marker', () = ]); }); +test('a repo-turbo marker passes with and without turbo_cache_host, and a URL there is a finding', async () => { + const real: Bundled = { + trees: new Map([['repo-turbo', await readTree(join(templatesRoot(), 'repo-turbo'))]]), + render, + }; + const marker = (answers: Record) => + findings(crossed([site('.', { version: '0.131.0', templates: ['repo-turbo'], answers })], { templates: real })); + assert.deepEqual(marker({ tenant: 'acme' }), []); + assert.deepEqual(marker({ tenant: 'acme', turbo_cache_host: '' }), []); + assert.deepEqual(marker({ tenant: 'acme', turbo_cache_host: 'ci-cache.example.internal' }), []); + assert.deepEqual(marker({ tenant: 'acme', turbo_cache_host: 'http://ci-cache:8585' }), [ + { + problem: + 'PLEXUS.md: `turbo_cache_host` of repo-turbo: A host name or IPv4 address, as in ci-cache.example.internal, or empty', + }, + ]); +}); + 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 = { diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 8a5ced48..1d46f25b 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -128,12 +128,12 @@ const caches = (job: Job | undefined): unknown[] => /** 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', () => { +test('_check.yml runs the repo’s test on a medium runner, and starts no cache server', () => { 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']); + assert.deepEqual(caches(workflow.jobs.check), []); }); test('_e2e.yml plans, then per app builds the app and runs its suites on a large runner with the trusted cache alone', () => { diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index ce909bb6..bf21fd76 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -70,9 +70,38 @@ test('the answers of a plain app repo are the questions’ defaults', async () = ci_service_account: true, display_versions: false, postgres: '', + turbo_cache_host: '', }); }); +test('the cache host is the one line PLX_TURBO_CACHE_HOST of mise.toml’s env, empty unless answered, in every repo', async () => { + for (const answers of [{}, { publishes_packages: true }]) { + const lines = async (host?: string) => { + const mise = textOf( + await render({ ...answers, ...(host === undefined ? {} : { turbo_cache_host: host }) }), + 'mise.toml', + ); + return (/^\[env\]\n([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(mise)?.[1] ?? '') + .split('\n') + .filter((line) => line.includes('TURBO')); + }; + assert.deepEqual(await lines(), ['PLX_TURBO_CACHE_HOST = ""'], JSON.stringify(answers)); + assert.deepEqual(await lines('ci-cache.example.internal'), ['PLX_TURBO_CACHE_HOST = "ci-cache.example.internal"']); + assert.deepEqual(await lines('100.64.0.7'), ['PLX_TURBO_CACHE_HOST = "100.64.0.7"']); + } +}); + +test('a cache host is empty or a host name or address, never a URL or a port', async () => { + for (const host of ['', 'cache', 'ci-cache.example.internal', '100.64.0.7']) + assert.deepEqual((await render({ turbo_cache_host: host })).errors, [], host); + for (const host of ['http://cache', 'cache:8585', 'Cache', 'ca che', 'cache/', 'cache"', 'cache\n']) { + const { errors } = await render({ turbo_cache_host: host }); + assert.equal(errors.length, 1, host); + assert.equal(errors[0]?.question, 'turbo_cache_host', host); + assert.match(errors[0]?.message ?? '', /A host name or IPv4 address, as in ci-cache\.example\.internal, or empty/); + } +}); + test('an app repo is asked whether its jobs are handed the service account token, a package repo is not', async () => { assert.equal((await render({ ci_service_account: false })).answers.ci_service_account, false); assert.ok(!('ci_service_account' in (await render({ publishes_packages: true })).answers)); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 079e4e76..57599bbf 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -3,12 +3,26 @@ // 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. +// stand-in for a cache server's token check on loopback: on a free port, and +// on the fixed ports 8585 and 8586 of an address of 127.0.0.0/8 that stands in +// for the cache host the repo's mise.toml names (PLX_TURBO_CACHE_HOST, which +// mise sets from it). The newborn test (newborns/) runs `turbow` against the +// real servers, as the role plexus.ci.turbo_cache runs them. 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 { + accessSync, + chmodSync, + constants, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; @@ -20,11 +34,40 @@ import { pathsOf, renderBundled, runOf, textOf } from './testing/bundled.ts'; const SHAPES = [{}, { publishes_packages: true }]; const render = (answers: Record = {}) => renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); +/** The tokens the stand-in takes; any other, or none, it refuses with 401, as the server does. */ +const SHARED_TOKEN = 'shared-token'; +const TRUSTED_TOKEN = 'trusted-token'; + let scratch = ''; let turbow = ''; -let server: Server; +const servers: Server[] = []; +/** A stand-in on a free loopback port. */ let answering = ''; +/** A loopback port nothing listens on. */ let silent = ''; +/** A server on loopback that takes every request and never answers, and one that answers every request with 500. */ +let hanging = ''; +let failing = ''; +/** The stand-in cache host: an address of 127.0.0.0/8 with a stand-in on 8585 and on 8586. */ +let host = ''; +/** A PATH of the stub turbo and of what turbow and the stub run besides, without node. */ +let noNode = ''; + +/** A stand-in that answers Turbo's status request: 200 with a token it takes, 401 otherwise. */ +async function standIn(address: string, port: number): Promise { + const server = createServer((req, res) => { + const token = (req.headers.authorization ?? '').replace(/^Bearer /, ''); + res.statusCode = + req.url !== '/v8/artifacts/status' ? 404 : [SHARED_TOKEN, TRUSTED_TOKEN].includes(token) ? 200 : 401; + res.end(); + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, address, resolve); + }); + servers.push(server); + return (server.address() as AddressInfo).port; +} /** A loopback port nothing listens on: taken from the system, then given back. */ async function freePort(): Promise { @@ -53,17 +96,58 @@ before(async () => { ].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}`; + mkdirSync(join(scratch, 'no-node')); + for (const tool of ['git', 'tr', 'sed', 'env', 'grep']) { + const found = (process.env.PATH ?? '') + .split(':') + .map((dir) => join(dir, tool)) + .find((path) => { + try { + accessSync(path, constants.X_OK); + return true; + } catch { + return false; + } + }); + if (!found) throw new Error(`no ${tool} on PATH`); + symlinkSync(found, join(scratch, 'no-node', tool)); + } + noNode = `${join(scratch, 'bin')}:${join(scratch, 'no-node')}`; + answering = `http://127.0.0.1:${await standIn('127.0.0.1', 0)}`; silent = `http://127.0.0.1:${await freePort()}`; + for (const [answer, set] of [ + [() => {}, (url: string) => (hanging = url)], + [ + (_: unknown, res: { statusCode: number; end(): void }) => { + res.statusCode = 500; + res.end(); + }, + (url: string) => (failing = url), + ], + ] as const) { + const server = createServer(answer); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + servers.push(server); + set(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); + } + // An address of its own, so that a server the machine runs on 127.0.0.1:8585 is never in the way. + for (let tries = 0; !host; tries++) { + const address = `127.85.86.${2 + Math.floor(Math.random() * 250)}`; + try { + await standIn(address, 8585); + await standIn(address, 8586); + host = address; + } catch (error) { + if (tries > 20) throw error; + } + } }); after(async () => { - await new Promise((resolve) => server.close(() => resolve())); + for (const server of servers) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } rmSync(scratch, { recursive: true, force: true }); }); @@ -100,7 +184,7 @@ async function turbowIn(dir: string, cache: string, env: Record ([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. + // Not spawnSync: the stand-ins answer from this process, whose loop must keep turning meanwhile. const ran = await new Promise<{ status: number | null; output: string }>((resolve) => { execFile( './turbow', @@ -130,22 +214,43 @@ async function turbowIn(dir: string, cache: string, env: Record } 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 Turbo gets where it runs without a remote cache: no server, no team, no token, and the local cache alone; in a + * job, a trusted verb never the local cache, which a shared run of the checkout may have filled. + */ +const uncached = (setting = 'local:rw') => ({ + TURBO_API: '', + TURBO_TEAM: '', + TURBO_TEAMID: '', + TURBO_TOKEN: '', + TURBO_CACHE: setting, +}); /** 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_LOGIN: 'https://example.invalid/login', TURBO_CACHE: 'remote:r', TURBO_REMOTE_CACHE_SIGNATURE_KEY: 'a-key', + TURBO_REMOTE_CACHE_TIMEOUT: '1', + TURBO_REMOTE_CACHE_UPLOAD_TIMEOUT: '1', 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' }; +/** Both tokens, as a `repo` slot or a job on the forge's runners holds them. */ +const TOKENS = { PLX_TURBO_SHARED_TOKEN: SHARED_TOKEN, PLX_TURBO_TRUSTED_TOKEN: TRUSTED_TOKEN }; +/** The cache host as mise sets it from the repo's mise.toml, and its two servers. */ +const HOST = () => ({ PLX_TURBO_CACHE_HOST: host }); +const hostShared = () => `http://${host}:8585`; +const hostTrusted = () => `http://${host}:8586`; +/** turbow's line where it uses a server: `the remote cache at , team `. */ +const using = (cache: string, url: string) => + new RegExp(`^turbow: the ${cache} remote cache at ${url.replaceAll('.', '\\.')}, team acme-web$`); test('turbow is rendered in every repo, executable, beside mise.toml', async () => { for (const answers of SHAPES) { @@ -155,7 +260,7 @@ test('turbow is rendered in every repo, executable, beside mise.toml', async () } }); -test('check and test reach Turbo through the shared cache, build and e2e through the trusted one, dev through none', async () => { +test('check and test reach Turbo through the shared cache, build, e2e and an app repo’s publish 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 [ @@ -163,6 +268,8 @@ test('check and test reach Turbo through the shared cache, build and e2e through ['test', 'shared'], ['build', 'trusted'], ['e2e', 'trusted'], + // A package repo publishes with changesets, by no Turbo task. + ...(answers.publishes_packages ? [] : [['publish', 'trusted'] as const]), ] as const) { const run = runOf(mise, verb); assert.match(run, new RegExp(`^\\./turbow ${cache} run ${verb}\\b`, 'm'), `${verb} ${JSON.stringify(answers)}`); @@ -172,124 +279,222 @@ test('check and test reach Turbo through the shared cache, build and e2e through } }); -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 () => { +test('outside a job, CI set or not, every verb uses the shared server of the cache host, with the shared token, 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 }); + const ran = await turbowIn(dir, cache, { ...STRAY, ...ci, ...HOST(), ...TOKENS }); assert.equal(ran.status, 0, ran.said.join('\n')); assert.deepEqual(ran.turbo?.env, { - TURBO_API: answering, + TURBO_API: hostShared(), TURBO_TEAM: 'acme-web', - TURBO_TOKEN: 'local', + TURBO_TEAMID: '', + TURBO_TOKEN: SHARED_TOKEN, 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('.', '\\.')}`)); + assert.match(ran.said[0] ?? '', using('shared', hostShared())); } }); -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 () => { +test('in a job, build, e2e and publish use the trusted server of the cache host and no local cache, 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); + const trusted = await turbowIn(dir, 'trusted', { ...STRAY, ...JOB, ...HOST(), ...TOKENS }); 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_API: hostTrusted(), TURBO_TEAM: 'acme-web', - TURBO_TOKEN: 'trusted-job-token', + TURBO_TEAMID: '', + TURBO_TOKEN: TRUSTED_TOKEN, TURBO_CACHE: 'remote:rw', }); - const shared = await turbowIn(dir, 'shared', job); + assert.match(trusted.said.join('\n'), using('trusted', hostTrusted())); + const shared = await turbowIn(dir, 'shared', { ...STRAY, ...JOB, ...HOST(), ...TOKENS }); assert.deepEqual(shared.turbo?.env, { - TURBO_API: silent, + TURBO_API: hostShared(), TURBO_TEAM: 'acme-web', - TURBO_TOKEN: 'shared-job-token', + TURBO_TEAMID: '', + TURBO_TOKEN: SHARED_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 () => { +test('a server the environment names, as a slot’s names its own host’s, comes before the cache host, in a job and outside one', 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}`); + const slot = { ...HOST(), ...TOKENS, PLX_TURBO_SHARED: answering, PLX_TURBO_TRUSTED: answering }; + for (const [where, cache, url] of [ + [{}, 'shared', answering], + [{}, 'trusted', answering], + [JOB, 'shared', answering], + [JOB, 'trusted', answering], + ] as const) { + const ran = await turbowIn(dir, cache, { ...where, ...slot }); + assert.equal(ran.turbo?.env.TURBO_API, url, `${cache} ${JSON.stringify(where)}`); + } + // Each address on its own: the other verb still goes to the cache host. + const sharedOnly = { ...HOST(), ...TOKENS, PLX_TURBO_SHARED: answering }; + assert.equal((await turbowIn(dir, 'shared', { ...JOB, ...sharedOnly })).turbo?.env.TURBO_API, answering); + assert.equal((await turbowIn(dir, 'trusted', { ...JOB, ...sharedOnly })).turbo?.env.TURBO_API, hostTrusted()); + const trustedOnly = { ...HOST(), ...TOKENS, PLX_TURBO_TRUSTED: answering }; + assert.equal((await turbowIn(dir, 'trusted', { ...JOB, ...trustedOnly })).turbo?.env.TURBO_API, answering); + assert.equal((await turbowIn(dir, 'shared', { ...JOB, ...trustedOnly })).turbo?.env.TURBO_API, hostShared()); + // Empty is no address: the cache host's. + const empty = { ...HOST(), ...TOKENS, PLX_TURBO_SHARED: '', PLX_TURBO_TRUSTED: '' }; + assert.equal((await turbowIn(dir, 'shared', empty)).turbo?.env.TURBO_API, hostShared()); + assert.equal((await turbowIn(dir, 'trusted', { ...JOB, ...empty })).turbo?.env.TURBO_API, hostTrusted()); +}); + +test('where neither the repo nor the environment names a server, every verb runs without a remote cache and says so in one line, in a job too', async () => { + const dir = checkout(REMOTE); + for (const [where, cache, setting] of [ + [{}, 'shared', 'local:rw'], + [{}, 'trusted', 'local:rw'], + [JOB, 'shared', 'local:rw'], + [JOB, 'trusted', 'remote:rw'], + ] as const) + for (const named of [{}, { PLX_TURBO_CACHE_HOST: '', PLX_TURBO_SHARED: '', PLX_TURBO_TRUSTED: '' }]) { + const ran = await turbowIn(dir, cache, { ...STRAY, ...where, ...TOKENS, ...named }); + const label = `${cache} ${JSON.stringify(where)} ${JSON.stringify(named)}`; + assert.equal(ran.status, 0, label); + assert.deepEqual(ran.turbo?.env, uncached(setting), label); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /^turbow: without a remote cache: .*turbo_cache_host/, label); + } +}); + +test('where the server does not answer, or refuses the token, the verb runs without a remote cache and says so in one line, in a job too', async () => { + const dir = checkout(REMOTE); + for (const [server, token, why] of [ + [silent, SHARED_TOKEN, `nothing answers at ${silent}`], + [answering, 'another-token', `the shared remote cache at ${answering} refuses the token`], + ] as const) + for (const where of [{}, JOB]) { + const ran = await turbowIn(dir, 'shared', { + ...STRAY, + ...where, + PLX_TURBO_SHARED: server, + PLX_TURBO_SHARED_TOKEN: token, + }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, uncached()); + assert.deepEqual(ran.said, [`turbow: without a remote cache: ${why}`]); } + const trusted = await turbowIn(dir, 'trusted', { ...JOB, PLX_TURBO_TRUSTED: silent, ...TOKENS }); + assert.equal(trusted.status, 0, trusted.said.join('\n')); + assert.deepEqual(trusted.turbo?.env, uncached('remote:rw')); + assert.deepEqual(trusted.said, [`turbow: without a remote cache: nothing answers at ${silent}`]); }); -test('in a job without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { +test('where no node is on PATH to ask the server with, the verb runs without a remote cache and says so in one line, in a job too', 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/); + for (const [cache, where, url, setting] of [ + ['shared', {}, hostShared(), 'local:rw'], + ['trusted', JOB, hostTrusted(), 'remote:rw'], + ] as const) { + const ran = await turbowIn(dir, cache, { ...where, ...HOST(), ...TOKENS, PATH: noNode }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, uncached(setting)); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match( + ran.said[0] ?? '', + new RegExp(`^turbow: without a remote cache: no node .*${url.replaceAll('.', '\\.')}`), + ); } }); -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 () => { +test('a server that takes the request and does not answer within two seconds is given up, and one that answers 500 is none to use', { + timeout: 15_000, +}, async () => { const dir = checkout(REMOTE); - for (const ci of ['true', '1', 'yes']) { - const ran = await turbowIn(dir, 'trusted', { CI: ci, PLX_TURBO_SHARED: answering }); + for (const server of [hanging, failing]) { + const started = Date.now(); + const ran = await turbowIn(dir, 'shared', { PLX_TURBO_SHARED: server, PLX_TURBO_SHARED_TOKEN: SHARED_TOKEN }); + assert.ok(Date.now() - started < 5000, `${server} given up after ${Date.now() - started} ms`); assert.equal(ran.status, 0, ran.said.join('\n')); - assert.equal(ran.turbo?.env.TURBO_API, answering, ci); + assert.deepEqual(ran.turbo?.env, uncached()); + assert.deepEqual(ran.said, [`turbow: without a remote cache: nothing answers at ${server}`]); } }); -test('in a job where the tenant has no bucket, every verb runs without a remote cache and says so in one line', async () => { +test('outside a job, a shared server without a token is no remote cache, and the line names the variable', 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' }); + const ran = await turbowIn(dir, cache, { ...HOST(), PLX_TURBO_TRUSTED_TOKEN: TRUSTED_TOKEN }); assert.equal(ran.status, 0, ran.said.join('\n')); - assert.deepEqual(ran.turbo?.env, UNCACHED); + 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/); + assert.match(ran.said[0] ?? '', /^turbow: without a remote cache: .*PLX_TURBO_SHARED_TOKEN/); + } +}); + +test('in a job, a trusted server without the trusted token fails build, e2e and publish in one line, and never falls back to the shared one', async () => { + const dir = checkout(REMOTE); + for (const named of [HOST(), { PLX_TURBO_TRUSTED: answering }]) + for (const token of [{}, { PLX_TURBO_TRUSTED_TOKEN: '' }]) { + const ran = await turbowIn(dir, 'trusted', { + ...JOB, + ...named, + ...token, + PLX_TURBO_SHARED: answering, + PLX_TURBO_SHARED_TOKEN: SHARED_TOKEN, + }); + assert.notEqual(ran.status, 0); + assert.equal(ran.turbo, undefined, 'Turbo never ran'); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /^turbow: .*trusted.*PLX_TURBO_TRUSTED_TOKEN/); + } +}); + +test('CI alone is no job: build and e2e on a machine with CI=true use the shared server, and need no trusted token', async () => { + const dir = checkout(REMOTE); + for (const ci of ['true', '1', 'yes']) { + const ran = await turbowIn(dir, 'trusted', { CI: ci, ...HOST(), PLX_TURBO_SHARED_TOKEN: SHARED_TOKEN }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.equal(ran.turbo?.env.TURBO_API, hostShared(), ci); } }); +test('GITHUB_ACTIONS other than true is no job: build and e2e use the shared server', async () => { + const dir = checkout(REMOTE); + for (const value of ['false', '1', 'yes']) { + const ran = await turbowIn(dir, 'trusted', { + GITHUB_ACTIONS: value, + ...HOST(), + PLX_TURBO_SHARED_TOKEN: SHARED_TOKEN, + }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.equal(ran.turbo?.env.TURBO_API, hostShared(), value); + } +}); + +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', {}, 'local:rw'], + ['shared', { ...HOST(), ...TOKENS }, 'local:rw,remote:rw'], + ['trusted', { ...JOB, ...HOST(), ...TOKENS }, '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('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' }); + const failed = await turbowIn(dir, 'shared', { ...HOST(), ...TOKENS, 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); + assert.deepEqual((await turbowIn(dir, 'shared', {}, args)).turbo?.args, args); +}); + +test('a first argument other than shared or trusted is refused before anything runs', async () => { + const ran = await turbowIn(checkout(REMOTE), 'build', { ...HOST(), ...TOKENS }); + assert.equal(ran.status, 2); + assert.equal(ran.turbo, undefined); + assert.match(ran.said.join('\n'), /usage: \.\/turbow /); }); test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', async () => { @@ -304,7 +509,7 @@ test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and '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 }); + const ran = await turbowIn(checkout(remote), 'shared', { ...HOST(), ...TOKENS }); assert.equal(ran.turbo?.env.TURBO_TEAM, 'acme-web', remote); } }); @@ -317,7 +522,7 @@ test('the team holds only [a-z0-9._-], every other character a dash, and a neste ['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 }); + const ran = await turbowIn(checkout(remote), 'shared', { ...HOST(), ...TOKENS }); if (team === 'o-r') assert.match(ran.turbo?.env.TURBO_TEAM ?? '', /^-+--+$/, remote); else assert.equal(ran.turbo?.env.TURBO_TEAM, team, remote); } @@ -329,16 +534,16 @@ test('a checkout without origin, or whose origin names no owner, has no team, an ['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 }); + const ran = await turbowIn(checkout(remote), 'shared', { ...HOST(), ...TOKENS }); assert.equal(ran.status, 0, ran.said.join('\n')); - assert.deepEqual(ran.turbo?.env, UNCACHED, String(remote)); + 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. +// No job starts a cache server: the servers are the runner hosts' (plexus.ci.turbo_cache). /** The job `name` of a rendered workflow, as text, up to the next job. */ const jobOf = (workflow: string, name: string): string => @@ -364,15 +569,13 @@ test('a package repo’s test job hands the vault’s token to _check.yml, as an } }); -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'), +test('_check.yml starts no cache server, and this repo has no step that would', () => { + const workflows = join(import.meta.dirname, '..', '..', '..', '.github'); + const workflow = parse(readFileSync(join(workflows, 'workflows', '_check.yml'), 'utf8')); + const steps: { uses?: string }[] = workflow.jobs.check.steps; + assert.deepEqual( + steps.filter((step) => step.uses?.includes('turbo-cache')), + [], ); - 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'); + assert.equal(existsSync(join(workflows, 'actions', 'turbo-cache')), false); }); diff --git a/packages/lib/src/turboCacheStep.test.ts b/packages/lib/src/turboCacheStep.test.ts deleted file mode 100644 index bcc32f63..00000000 --- a/packages/lib/src/turboCacheStep.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -// 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, against a stand-in for the server that answers Turbo's status -// request as the pinned server does, 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 whole step around real servers. -import assert from 'node:assert/strict'; -import { execFile } from 'node:child_process'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:http'; -import { createServer as createListener, type Server } from 'node:net'; -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' }, -]; -/** The ports the step picks from. */ -const FIRST = 8585; -const LAST = 8684; - -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`; never blocking, so a stand-in can answer it. */ -async 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 stdout = await new Promise((resolve, reject) => - execFile( - 'bash', - [join(STEP, 'turbo-cache.sh'), name], - { encoding: 'utf8', env: { ...base, GITHUB_OUTPUT: output, GITHUB_ENV: githubEnv, ...env } }, - (error, out, err) => (error ? reject(new Error(`${name}: ${error.message}\n${err}`)) : resolve(out)), - ), - ); - return { - stdout, - outputs: pairs(readFileSync(output, 'utf8')), - env: pairs(readFileSync(githubEnv, 'utf8')), - }; -} - -/** - * A stand-in for a cache server on loopback, answering Turbo's status request as the pinned server does: 200 for - * `token`, 401 for any other; with no token, as the server runs without one, 200 for every request. - */ -async function standIn(token?: string): Promise<{ port: number; close(): Promise }> { - const server = createServer((req, res) => { - const given = /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1]; - res.statusCode = req.url === '/v8/artifacts/status' && (token === undefined || given === token) ? 200 : 401; - res.end(); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address !== 'object') throw new Error('no port'); - return { - port: address.port, - close: () => new Promise((resolve) => server.close(() => resolve())), - }; -} - -/** A port on loopback nothing listens on. */ -async function nothing(): Promise { - const server = await standIn(); - await server.close(); - return server.port; -} - -const plan = (cache: string) => - phase('plan', { CACHE: cache, OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); -const check = (port: number, server: string) => - phase('check', { CACHE: 'trusted', PORT: String(port), TOKEN: 'job-token', SERVER: server }); -const announce = (cache: string, keys: string, port: number | '') => - phase('announce', { CACHE: cache, KEYS: keys, VAULT: 'acme-ci', PORT: String(port), TOKEN: 'job-token' }); - -/** Runs `body` with a stand-in holding `token`, or none, and closes it. */ -async function withServer(token: string | undefined, body: (port: number) => Promise): Promise { - const server = await standIn(token); - try { - return await body(server.port); - } finally { - await server.close(); - } -} - -/** Runs `body` while every port the step picks from listens; a port something else holds already stays as it is. */ -async function withRangeTaken(body: () => Promise): Promise { - const listeners: Server[] = []; - for (let port = FIRST; port <= LAST; port++) { - const listener = createListener(); - const listening = await new Promise((resolve) => { - listener.once('error', () => resolve(false)); - listener.listen(port, '127.0.0.1', () => resolve(true)); - }); - if (listening) listeners.push(listener); - } - try { - return await body(); - } finally { - await Promise.all(listeners.map((listener) => new Promise((resolve) => listener.close(resolve)))); - } -} - -test('plan names the vault item and the bucket of each cache', async () => { - for (const { cache, item, bucket } of CACHES) { - const planned = (await 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', async () => { - const planned = await 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'); - await withServer(token, async (port) => { - const told = await phase('announce', { CACHE: 'trusted', KEYS: 'success', PORT: String(port), TOKEN: token }); - assert.ok(told.env.PLX_TURBO_TRUSTED, told.stdout); - assert.ok(!told.stdout.includes(token)); - }); -}); - -test('plan picks a port from 8585 to 8684 that nothing listens on, a different one from job to job', async () => { - const ports = new Set(); - for (let n = 0; n < 12; n++) { - const port = Number((await plan('trusted')).outputs.port); - assert.ok(port >= FIRST && port <= LAST, String(port)); - ports.add(port); - } - assert.ok(ports.size > 1, `twelve plans, one port: ${[...ports]}`); -}); - -test('where every port of the range listens, plan names none, and announce says no port was free', async () => { - await withRangeTaken(async () => { - assert.equal((await plan('trusted')).outputs.port, ''); - const told = await announce('trusted', 'success', ''); - assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: 'none' }); - assert.match( - told.stdout, - /^::warning title=Turbo runs without the trusted remote cache::.*no free port in 8585–8684/m, - ); - }); -}); - -test('check keeps the port where the job’s own server answers', async () => { - await withServer('job-token', async (port) => { - const checked = await check(port, 'success'); - assert.deepEqual(checked.outputs, { port: String(port) }); - }); -}); - -test('check moves to another port where a server not of this job answers, with another token or none', async () => { - for (const token of ['another-job-token', undefined]) - await withServer(token, async (port) => { - const checked = await check(port, 'success'); - assert.equal(checked.outputs.retry, 'true', String(token)); - const next = Number(checked.outputs.port); - assert.ok(next >= FIRST && next <= LAST && next !== port, String(next)); - assert.match(checked.stdout, new RegExp(`127\\.0\\.0\\.1:${port}.*127\\.0\\.0\\.1:${next}`)); - }); -}); - -test('check keeps the port where another server answers and no port of the range is free, and says so', async () => { - await withServer('another-job-token', (port) => - withRangeTaken(async () => { - const checked = await check(port, 'success'); - assert.deepEqual(checked.outputs, { port: String(port) }); - assert.match(checked.stdout, /no free port in 8585–8684/); - }), - ); -}); - -test('check leaves a server that did not come up to announce', async () => { - const port = await nothing(); - assert.deepEqual((await check(port, 'failure')).outputs, { port: String(port) }); -}); - -test('announce tells turbow of the cache it was asked for, and never of the other', async () => { - for (const { cache, variable } of CACHES) { - await withServer('job-token', async (port) => { - assert.deepEqual((await announce(cache, 'success', port)).env, { - [variable]: `http://127.0.0.1:${port}`, - [`${variable}_TOKEN`]: 'job-token', - }); - for (const keys of ['skipped', 'failure']) - assert.deepEqual((await announce(cache, keys, port)).env, { [variable]: 'none' }, `${cache} ${keys}`); - }); - assert.deepEqual((await announce(cache, 'success', await nothing())).env, { [variable]: 'none' }, cache); - } -}); - -test('announce counts a server as the job’s only where it takes the job’s token and refuses another', async () => { - for (const token of ['another-job-token', undefined]) - await withServer(token, async (port) => { - const told = await announce('trusted', 'success', port); - assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: 'none' }, String(token)); - assert.match(told.stdout, new RegExp(`did not come up on 127\\.0\\.0\\.1:${port}`)); - }); -}); - -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', async () => { - const warnings = (stdout: string) => stdout.split('\n').filter((line) => line.startsWith('::warning ')); - for (const { cache, item } of CACHES) { - await withServer('another-job-token', async (port) => { - for (const [keys, cause] of [ - ['skipped', /no vault/], - ['failure', new RegExp(`${item}\\b.*the vault acme-ci`)], - ['success', /did not come up/], - ] as const) { - const said = warnings((await announce(cache, keys, port)).stdout); - assert.equal(said.length, 1, `${cache} ${keys}: ${said.join('\n')}`); - assert.match(said[0] ?? '', new RegExp(`^::warning title=Turbo runs without the ${cache} remote cache::`)); - assert.match(said[0] ?? '', cause); - } - }); - await withServer('job-token', async (port) => - assert.deepEqual(warnings((await announce(cache, 'success', port)).stdout), [], cache), - ); - } -}); - -interface Step { - id?: string; - if?: string; - env?: Record; - 'continue-on-error'?: boolean; - uses?: string; -} - -/** The steps of action.yml, in order. */ -const steps = (): Step[] => parse(readFileSync(join(STEP, 'action.yml'), 'utf8')).runs.steps; - -/** The steps that start the server. */ -const starts = () => steps().filter((step) => step.uses?.startsWith('brunojppb/turbo-cache-server@')); - -test('every start of the server is the pinned action, bound to loopback whatever the job’s environment holds', () => { - const { PORT: _, ...first } = starts()[0]?.env ?? {}; - for (const start of starts()) { - assert.match(start.uses ?? '', /^brunojppb\/turbo-cache-server@[0-9a-f]{40}$/); - assert.equal(start.uses, starts()[0]?.uses); - assert.equal(start.env?.HOST, '127.0.0.1'); - const { PORT: __, ...rest } = start.env ?? {}; - assert.deepEqual(rest, first, `${start.id}: the same server but for its port`); - } -}); - -test('a server that does not come up fails no job, and a start after the first follows a check that moved the port', () => { - const all = steps(); - const ids = all.map((step) => step.id); - assert.equal(starts().length, 3, 'three starts at most: the first, and two where another job’s server took the port'); - assert.match( - starts()[0]?.if ?? '', - /&& steps\.plan\.outputs\.port != ''/, - 'without a free port the step starts nothing', - ); - for (const [n, start] of starts().entries()) { - assert.equal(start['continue-on-error'], true, start.id); - const at = ids.indexOf(start.id); - if (n > 0) { - const moved = all[at - 1]; - assert.equal(start.if, `\${{ steps.${moved?.id}.outputs.retry == 'true' }}`, start.id); - assert.equal(start.env?.PORT, `\${{ steps.${moved?.id}.outputs.port }}`, start.id); - } - const checked = all[at + 1]; - if (checked?.id === 'announce') continue; - assert.equal(checked?.env?.SERVER, `\${{ steps.${start.id}.outcome }}`, `${checked?.id} hears of ${start.id}`); - assert.equal(checked?.env?.PORT, start.env?.PORT, `${checked?.id} checks the port ${start.id} was given`); - } - assert.equal(all.at(-1)?.id, 'announce'); - assert.equal(ids.indexOf(starts().at(-1)?.id), all.length - 2, 'announce checks the last start itself'); -}); diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index 7fbe264a..4328862b 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -57,6 +57,7 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{% raw %}{{config_root}}{% endraw %}/node_modules/.bin"] +PLX_TURBO_CACHE_HOST = "{{ turbo_cache_host }}" # 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 %}" diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow index 110baee7..66572c77 100755 --- a/templates/repo-turbo/files/turbow +++ b/templates/repo-turbo/files/turbow @@ -14,35 +14,58 @@ 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 +unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_LOGIN TURBO_CACHE TURBO_REMOTE_CACHE_SIGNATURE_KEY \ + TURBO_REMOTE_CACHE_TIMEOUT TURBO_REMOTE_CACHE_UPLOAD_TIMEOUT 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} +# Which server (§ 8 PLX-Delivery): check and test call turbow with `shared`, build, e2e and publish with `trusted`. +# In a job of the forge (GITHUB_ACTIONS=true, which the forge's runner sets and CI alone does not), a trusted verb uses +# the trusted server and never the local cache, which a shared run of this checkout may have filled, and a shared verb +# the shared server. Outside a job every verb uses the shared server: no machine but CI holds the trusted token. +# the shared server PLX_TURBO_SHARED, else http://:8585 +# the trusted server PLX_TURBO_TRUSTED, else http://:8586 +# their tokens PLX_TURBO_SHARED_TOKEN, PLX_TURBO_TRUSTED_TOKEN +# PLX_TURBO_CACHE_HOST is the answer turbo_cache_host, which mise sets from mise.toml. A slot of a runner host names its +# own host's servers in PLX_TURBO_SHARED and PLX_TURBO_TRUSTED, which come first. An empty variable names nothing. +# +# It runs without a remote cache, and says why in one line, where no server is named, where the shared token is +# missing, where no node is on PATH to ask the server with, where the server refuses the token or does not answer +# within two seconds, and where origin names no team. +# In a job, a trusted server named without the trusted token fails the verb in one line instead. +host=${PLX_TURBO_CACHE_HOST:-} +if [ "${GITHUB_ACTIONS:-}" = true ] && [ "$cache" = trusted ]; then + from=trusted server=${PLX_TURBO_TRUSTED:-${host:+http://$host:8586}} token=${PLX_TURBO_TRUSTED_TOKEN:-} + with=remote:rw without=remote:rw 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)" + from=shared server=${PLX_TURBO_SHARED:-${host:+http://$host:8585}} token=${PLX_TURBO_SHARED_TOKEN:-} + with=local:rw,remote:rw without=local:rw fi -if [ "$server" = none ]; then - reason="the tenant has no $from bucket" + +reason= +if [ -z "$server" ]; then + reason="the repo names no cache host (turbo_cache_host), and the environment no $from server" +elif [ -z "$token" ] && [ "$from" = trusted ]; then + echo "turbow: in a job of the forge, build, e2e and publish need a token for the trusted remote cache at $server, and this job has none (PLX_TURBO_TRUSTED_TOKEN is unset)" >&2 + exit 1 +elif [ -z "$token" ]; then + reason="no token for the shared remote cache at $server (PLX_TURBO_SHARED_TOKEN is unset)" +elif ! command -v node >/dev/null 2>&1; then + reason="no node on PATH to ask the $from remote cache at $server with" +else + # The request Turbo makes first, with the token: 200 is a server to use. + status=$(TOKEN=$token node -e ' + fetch(process.argv[1], { + headers: { Authorization: "Bearer " + process.env.TOKEN }, + signal: AbortSignal.timeout(2000), + }).then( + (answer) => console.log(answer.status), + () => console.log(0), + );' "$server/v8/artifacts/status") + case $status in + 200) ;; + 401) reason="the $from remote cache at $server refuses the token" ;; + *) reason="nothing answers at $server" ;; + esac 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 @@ -74,13 +97,10 @@ 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 + export TURBO_API='' TURBO_TEAM='' TURBO_TEAMID='' TURBO_TOKEN='' TURBO_CACHE="$without" 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 + echo "turbow: the $from remote cache at $server, team $team" >&2 + # No team id: a linked repo's (.turbo/config.json) would otherwise reach the server beside the team. + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TEAMID='' TURBO_TOKEN="$token" TURBO_CACHE="$with" fi exec turbo "$@" diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 5edecfb5..c7fcb57a 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -85,6 +85,16 @@ questions: not in '0123456789' %}x{% endif %}{% endfor %}{% endfor %}{% endset %}{% if bad %}An exact version, major and minor, as in 18.6, or empty{% endif %}{% endif %} + turbo_cache_host: + type: str + help: "The runner host that serves the tenant's two Turbo remote caches on its overlay (§ 8 PLX-Delivery), by name or address, as in ci-cache.example.internal; empty: none, and the verbs run without a remote cache where no slot names its own" + default: "" + # A name or an IPv4 address as string tests, since the engine has no regex; turbow adds the scheme and the ports. + validator: >- + {% if turbo_cache_host %}{% set bad %}{% for c in turbo_cache_host %}{% if c not in + 'abcdefghijklmnopqrstuvwxyz0123456789.-' %}x{% endif %}{% endfor %}{% endset %}{% if bad %}A host name or IPv4 + address, as in ci-cache.example.internal, 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/all-roles.yml b/tests/all-roles.yml index 667fd2e4..21386685 100644 --- a/tests/all-roles.yml +++ b/tests/all-roles.yml @@ -4,6 +4,7 @@ hosts: all roles: - plexus.ci.actions_runners + - plexus.ci.turbo_cache - plexus.host.alloy - plexus.host.base - plexus.host.docker