Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
ci(contract): link a release train from branches with a contract stack (#750)
Ron97a7228f7c80
diff --git a/.github/contract-stacks/l12.json b/.github/contract-stacks/l12.jsonnew file mode 100644index 00000000..60c0005f--- /dev/null+++ b/.github/contract-stacks/l12.json@@ -0,0 +1,16 @@+{+ "description": "Laravel 12 release train. Each package is linked from its release branch, or from its Laravel 12 branch until that PR merges there (customer-portal), so release PRs can be tested before anything is tagged. Delete this stack after the release ships.",+ "fleetbase-ref": "feat/laravel-12",+ "build-from-source": true,+ "overlays": [+ { "repository": "fleetbase/core-api", "ref": "release/v2.0.0", "package": "fleetbase/core-api" },+ { "repository": "fleetbase/fleetops", "ref": "release/v0.7.0", "package": "fleetbase/fleetops-api" },+ { "repository": "fleetbase/storefront", "ref": "release/v0.5.0", "package": "fleetbase/storefront-api" },+ { "repository": "fleetbase/ledger", "ref": "release/v0.1.0", "package": "fleetbase/ledger-api" },+ { "repository": "fleetbase/customer-portal", "ref": "chore/laravel-12", "package": "fleetbase/customer-portal-api" },+ { "repository": "fleetbase/registry-bridge", "ref": "release/v0.2.0", "package": "fleetbase/registry-bridge" },+ { "repository": "fleetbase/ai", "ref": "release/v0.1.0", "package": "fleetbase/ai" },+ { "repository": "fleetbase/valhalla", "ref": "release/v0.1.0", "package": "fleetbase/valhalla-api" },+ { "repository": "fleetbase/vroom", "ref": "release/v0.1.0", "package": "fleetbase/vroom-api" }+ ]+}diff --git a/.github/workflows/api-contract.yml b/.github/workflows/api-contract.ymlindex 338434d6..fadab778 100644--- a/.github/workflows/api-contract.yml+++ b/.github/workflows/api-contract.yml@@ -16,6 +16,12 @@ name: API Contract (Postman)# overlay-package: fleetbase/storefront-api# secrets: inherit#+# To test a release train before anything is tagged, a caller adds `stack: <name>`+# (a file in .github/contract-stacks/). The stack sets the fleetbase ref, builds the+# image from it, and links every listed package from its branch, with the caller's+# own entry replaced by the commit under test. `extra-overlays` adds packages the+# stack doesn't list.+## Requires org-level secrets POSTMAN_API_KEY and _GITHUB_AUTH_TOKEN (inherited).on:@@ -74,6 +80,29 @@ on:type: stringrequired: falsedefault: main+ stack:+ description: >-+ Name of a file in .github/contract-stacks/ (without .json) listing packages to+ link from branches before the run, for testing a release train before anything+ is tagged. The stack also sets fleetbase-ref and build-from-source. The calling+ repository's own entry is replaced by the commit under test. Leave empty for the+ usual single-package overlay.+ type: string+ required: false+ default: ''+ stack-ref:+ description: Ref of fleetbase/fleetbase to read the stack file from.+ type: string+ required: false+ default: main+ extra-overlays:+ description: >-+ More packages to link from branches, one a line: `owner/repo@ref composer/package [path]`.+ Added to the stack's list. Every linked package goes in as a Composer path+ repository, and the whole app is re-resolved against them.+ type: string+ required: false+ default: ''permissions:contents: read@@ -103,29 +132,164 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 45steps:+ # Resolved before anything else, because a stack sets which fleetbase ref to boot.+ # Read through the API rather than a checkout, which would be wiped by the+ # workspace checkout below.+ - name: Resolve contract stack+ id: stack+ env:+ GH_TOKEN: ${{ secrets._GITHUB_AUTH_TOKEN || github.token }}+ STACK: ${{ inputs.stack }}+ STACK_REF: ${{ inputs.stack-ref }}+ EXTRA_OVERLAYS: ${{ inputs.extra-overlays }}+ CALLER: ${{ github.repository }}+ run: |+ set -euo pipefail+ if [[ -z "$STACK" && -z "$EXTRA_OVERLAYS" ]]; then+ echo "enabled=false" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ resolver="$RUNNER_TEMP/resolve-contract-stack.py"+ gh api -H 'Accept: application/vnd.github.raw' \+ "repos/fleetbase/fleetbase/contents/scripts/ci/resolve-contract-stack.py?ref=${STACK_REF}" > "$resolver"+ stack_file=""+ if [[ -n "$STACK" ]]; then+ if [[ ! "$STACK" =~ ^[a-z0-9_-]+$ ]]; then+ echo "::error::Invalid stack name."; exit 1+ fi+ stack_file="$RUNNER_TEMP/stack.json"+ gh api -H 'Accept: application/vnd.github.raw' \+ "repos/fleetbase/fleetbase/contents/.github/contract-stacks/${STACK}.json?ref=${STACK_REF}" > "$stack_file"+ fi+ python3 "$resolver" "$stack_file" "$CALLER" "$EXTRA_OVERLAYS" > "$RUNNER_TEMP/stack.out"+ cat "$RUNNER_TEMP/stack.out" >> "$GITHUB_OUTPUT"+ echo "enabled=true" >> "$GITHUB_OUTPUT"+ {+ echo "### Contract stack \`${STACK:-extra overlays}\` from fleetbase/fleetbase@${STACK_REF}"+ echo '```'+ cat "$RUNNER_TEMP/stack.out"+ echo '```'+ } >> "$GITHUB_STEP_SUMMARY"+- name: Checkout fleetbase/fleetbaseuses: actions/checkout@v4with:repository: fleetbase/fleetbase- ref: ${{ inputs.fleetbase-ref }}+ ref: ${{ steps.stack.outputs.fleetbase_ref || inputs.fleetbase-ref }}submodules: recursivetoken: ${{ secrets._GITHUB_AUTH_TOKEN }}- name: Set up Docker Buildxuses: docker/setup-buildx-action@v3+ # A stack is resolved into the root lock BEFORE the image is built, so the image is a+ # fresh install of the whole train. The Dockerfile installs from the lock before it+ # copies the app, and Composer refuses a lock that no longer satisfies composer.json,+ # so linking packages into a running container afterwards cannot move the framework.+ - name: Checkout calling repository for the stack+ if: ${{ steps.stack.outputs.enabled == 'true' && inputs.overlay-package != '' }}+ uses: actions/checkout@v4+ with:+ repository: ${{ github.repository }}+ ref: ${{ github.sha }}+ token: ${{ secrets._GITHUB_AUTH_TOKEN }}+ path: .overlay++ - name: Set up PHP for the stack+ if: ${{ steps.stack.outputs.enabled == 'true' }}+ uses: shivammathur/setup-php@v2+ with:+ php-version: '8.2'+ tools: composer:v2+ coverage: none++ - name: Resolve the stack into the root lock+ if: ${{ steps.stack.outputs.enabled == 'true' }}+ env:+ CALLER_PACKAGE: ${{ inputs.overlay-package }}+ CALLER_PATH: ${{ inputs.overlay-path }}+ OVERLAYS: ${{ steps.stack.outputs.overlays }}+ GIT_TOKEN: ${{ secrets._GITHUB_AUTH_TOKEN || github.token }}+ COMPOSER_AUTH: '{"github-oauth":{"github.com":"${{ secrets._GITHUB_AUTH_TOKEN }}"}}'+ run: |+ set -euo pipefail+ packages="api/.contract-packages"+ rm -rf "$packages"; mkdir -p "$packages"+ : > "$RUNNER_TEMP/linked.txt"+ n=0++ link() {+ local src="$1" pkg="$2" from="$3" version+ if [[ ! -f "$src/composer.json" ]]; then+ echo "::error::No composer.json at ${src} for ${pkg}."; exit 1+ fi+ version="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); assert d["name"] == sys.argv[2], "package name mismatch"; assert isinstance(d.get("version"), str) and d["version"], "no version in composer.json"; print(d["version"])' "$src/composer.json" "$pkg")"+ mkdir -p "${packages}/${n}"+ tar -C "$src" --exclude=.git -cf - . | tar -C "${packages}/${n}" -xf -+ echo "${n} ${pkg} ${version} ${from}" >> "$RUNNER_TEMP/linked.txt"+ n=$((n + 1))+ }++ if [[ -n "$CALLER_PACKAGE" ]]; then+ link ".overlay/${CALLER_PATH}" "$CALLER_PACKAGE" "${{ github.repository }}@${{ github.sha }}"+ fi+ while read -r repository ref package path; do+ [[ -z "${repository:-}" ]] && continue+ dir="$RUNNER_TEMP/stack/${n}"+ git clone --quiet --depth 1 --branch "$ref" "https://x-access-token:${GIT_TOKEN}@github.com/${repository}.git" "$dir"+ link "${dir}/${path}" "$package" "${repository}@${ref} ($(git -C "$dir" rev-parse --short HEAD))"+ done <<< "$OVERLAYS"++ cd api+ while read -r i pkg version _; do+ composer config "repositories.contract-stack-${i}" "{\"type\":\"path\",\"url\":\"./.contract-packages/${i}\",\"options\":{\"symlink\":false}}"+ composer require "${pkg}:${version}" --no-update --no-scripts --no-interaction+ done < "$RUNNER_TEMP/linked.txt"+ composer update --no-scripts --no-interaction --no-progress --ignore-platform-req='ext-*'+ composer show "fleetbase/*"+ composer show laravel/framework | head -4+ audit="$(composer audit --locked 2>&1 || true)"+ echo "$audit"++ {+ echo "### Packages linked from branches"+ echo+ echo "| Package | Version | Source |"+ echo "| --- | --- | --- |"+ while read -r _ pkg version from; do echo "| \`${pkg}\` | ${version} | ${from} |"; done < "$RUNNER_TEMP/linked.txt"+ echo+ echo "The root lock was re-resolved against these before the image was built."+ echo+ echo '```'+ echo "$audit"+ echo '```'+ } >> "$GITHUB_STEP_SUMMARY"++ # The image installs from the lock before it copies the app, so the linked+ # packages go in first. docker/Dockerfile is in .dockerignore, so the copy lives+ # outside the build context.+ cd ..+ anchor='COPY --chown=www-data:www-data ./api/composer.json ./api/composer.lock /fleetbase/api/'+ grep -qxF "$anchor" docker/Dockerfile || { echo "::error::Dockerfile no longer copies the lock the way this step expects."; exit 1; }+ awk -v anchor="$anchor" '$0 == anchor { print "COPY --chown=www-data:www-data ./api/.contract-packages /fleetbase/api/.contract-packages" } { print }' \+ docker/Dockerfile > "$RUNNER_TEMP/Dockerfile.contract-stack"+- name: Build API image from source- if: ${{ inputs.build-from-source }}+ if: ${{ inputs.build-from-source || steps.stack.outputs.build_from_source == 'true' }}run: |+ dockerfile=docker/Dockerfile+ if [[ "${{ steps.stack.outputs.enabled }}" == "true" ]]; then+ dockerfile="$RUNNER_TEMP/Dockerfile.contract-stack"+ fidocker build \- --file docker/Dockerfile \+ --file "$dockerfile" \--target app-release \--build-arg GITHUB_AUTH_KEY="${{ secrets._GITHUB_AUTH_TOKEN }}" \--tag fleetbase/fleetbase-api:latest \.- name: Pull published API image- if: ${{ !inputs.build-from-source }}+ if: ${{ !inputs.build-from-source && steps.stack.outputs.build_from_source != 'true' }}run: |docker pull "${{ inputs.api-image }}"# :latest is a moving target, so record the digest and build date the run@@ -255,7 +419,7 @@ jobs:# In a reusable workflow github.repository/github.sha refer to the CALLER, so this# checks out the module branch under review rather than fleetbase/fleetbase.- name: Checkout calling repository for overlay- if: ${{ inputs.overlay-package != '' }}+ if: ${{ inputs.overlay-package != '' && steps.stack.outputs.enabled != 'true' }}uses: actions/checkout@v4with:repository: ${{ github.repository }}@@ -264,7 +428,7 @@ jobs:path: .overlay- name: Install branch source and resolve its Composer dependencies- if: ${{ inputs.overlay-package != '' }}+ if: ${{ inputs.overlay-package != '' && steps.stack.outputs.enabled != 'true' }}env:OVERLAY_PACKAGE: ${{ inputs.overlay-package }}OVERLAY_PATH: ${{ inputs.overlay-path }}@@ -358,7 +522,7 @@ jobs:} >> "$GITHUB_STEP_SUMMARY"- name: Re-check API health after overlay- if: ${{ inputs.overlay-package != '' }}+ if: ${{ inputs.overlay-package != '' && steps.stack.outputs.enabled != 'true' }}run: |for _attempt in $(seq 1 20); doif curl -fsS --max-time 5 http://localhost:8000/health | grep -q '"status"'; thendiff --git a/scripts/ci/resolve-contract-stack.py b/scripts/ci/resolve-contract-stack.pynew file mode 100755index 00000000..a6fac5b4--- /dev/null+++ b/scripts/ci/resolve-contract-stack.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Turns a contract stack file and extra overlays into the list the contract workflow installs.++Usage: resolve-contract-stack.py STACK_JSON CALLER_REPOSITORY [EXTRA_OVERLAYS]++STACK_JSON may be empty, for a run with only extra overlays. EXTRA_OVERLAYS is one overlay a+line, `owner/repo@ref composer/package [path]`. The calling repository's own entry is dropped:+the workflow installs the caller from the commit under test instead.++Prints `key=value` lines for $GITHUB_OUTPUT: fleetbase_ref, build_from_source, and overlays,+a heredoc of `repository ref package path` lines.+"""+import json+import re+import sys++NAME = re.compile(r'^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$')+PACKAGE = re.compile(r'^[a-z0-9]([a-z0-9_.-]*[a-z0-9])?/[a-z0-9]([a-z0-9_.-]*[a-z0-9])?$')+REF = re.compile(r'^[A-Za-z0-9_./-]+$')+++def overlay(repository, ref, package, path='.'):+ if not NAME.match(repository) or not REF.match(ref) or not PACKAGE.match(package):+ sys.exit(f'Invalid overlay: {repository}@{ref} {package}')+ if path.startswith('/') or '..' in path.split('/'):+ sys.exit(f'Invalid overlay path: {path}')+ return {'repository': repository, 'ref': ref, 'package': package, 'path': path or '.'}+++def main():+ stack_file, caller = sys.argv[1], sys.argv[2]+ extra = sys.argv[3] if len(sys.argv) > 3 else ''++ stack = json.load(open(stack_file)) if stack_file else {}+ overlays = [overlay(o['repository'], o['ref'], o['package'], o.get('path', '.')) for o in stack.get('overlays', [])]++ for line in extra.splitlines():+ line = line.strip()+ if not line:+ continue+ parts = line.split()+ if len(parts) not in (2, 3) or '@' not in parts[0]:+ sys.exit(f'Invalid extra overlay line: {line}')+ repository, ref = parts[0].split('@', 1)+ overlays.append(overlay(repository, ref, parts[1], parts[2] if len(parts) == 3 else '.'))++ overlays = [o for o in overlays if o['repository'].lower() != caller.lower()]+ packages = [o['package'] for o in overlays]+ if len(packages) != len(set(packages)):+ sys.exit('The same package is overlaid twice.')++ print(f"fleetbase_ref={stack.get('fleetbase-ref', '')}")+ print(f"build_from_source={'true' if stack.get('build-from-source') else 'false'}")+ print('overlays<<EOF')+ for o in overlays:+ print(o['repository'], o['ref'], o['package'], o['path'])+ print('EOF')+++if __name__ == '__main__':+ main()