Skip to content

Modular logistics and supply chain operating system (LSOS)

release/v0.7.66 (#692)

Ronf85a4694d000
diff --git a/.github/workflows/performance.yml b/.github/workflows/performance.yml
new file mode 100644
index 00000000..94455571
--- /dev/null
+++ b/.github/workflows/performance.yml
@@ -0,0 +1,567 @@
+name: API Performance
+
+# API performance report for every release (k6).
+#
+# Boots the stack from source exactly like install-smoke.yml, mints three API keys in
+# three organizations (scripts/ci/mint-k6-keys.php), and runs tests/k6/api-release.js:
+#
+# throughput the headline: a ramping arrival rate over a weighted catalogue of the
+# public API (orders, places, contacts, drivers, vehicles, fleets, ...)
+# with a LOAD key listed in THROTTLE_UNLIMITED_API_KEYS. Reports
+# avg/p50/p90/p95/p99/max, req/s and error rate overall, for reads vs
+# writes and per endpoint, compared against the previous release.
+# noisy_neighbour secondary: a NOISY key floods create/update far past its per-key limit while a
+# VICTIM key (other org) and an anonymous console route keep working.
+# Gate: the victim and the console get ZERO 429s, the noisy key does get
+# 429s and every one carries Retry-After. This is the regression test for
+# the incident where one customer's traffic throttled the whole platform
+# because the limiter keyed on the load balancer's IP.
+#
+# The report (report.md / report.html / metrics.json / summary.json) always lands in the job
+# summary and the k6-report artifact; on a tag the report and metrics.json are attached to
+# that tag's GitHub Release, where the next release's run picks metrics.json up as its
+# comparison baseline. Latency budgets are report-only unless the repository variable
+# K6_ENFORCE_BUDGETS is "true"; error-rate and isolation thresholds fail the job, after the
+# report has been published.
+#
+# Release PRs (release/v* or dev-v* into main) run the same benchmark as a required-check
+# candidate, gated on:
+# correctness error rate and rate-limit isolation (k6 thresholds) — always enforced;
+# latency aggregate read/write p95 vs the previous release's metrics — fails only
+# when BOTH more than PERF_MAX_REGRESSION (35%) and PERF_MIN_REGRESSION_MS
+# (150 ms) slower, and a second throughput run in the same job agrees.
+# The `perf-regression-accepted` label downgrades a confirmed latency
+# regression to a warning (read at run time, so re-run the job after
+# labelling). It never overrides the correctness gate.
+
+on:
+ push:
+ tags:
+ - 'v*'
+ # Release PRs only; the job condition below filters on the head branch.
+ pull_request:
+ branches:
+ - main
+ workflow_dispatch:
+ inputs:
+ throughput_peak_rate:
+ description: Peak arrival rate for the throughput phase (req/s)
+ required: false
+ default: ''
+ throughput_duration:
+ description: Throughput phase duration (e.g. 3m30s)
+ required: false
+ default: ''
+ noisy_rate:
+ description: Noisy tenant flood rate (req/s)
+ required: false
+ default: ''
+ noisy_duration:
+ description: Noisy-neighbour phase duration (e.g. 90s)
+ required: false
+ default: ''
+ scenarios:
+ description: Comma-separated phases to run (throughput,noisy_neighbour)
+ required: false
+ default: 'throughput,noisy_neighbour'
+
+concurrency:
+ group: performance-${{ github.ref }}
+ # Never cancel a tag benchmark halfway (a second push of the same ref queues); a new push
+ # to a release PR supersedes the run for the previous commit.
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: write # attach the report to the GitHub Release
+ pull-requests: write # post the report on the release PR
+
+env:
+ K6_VERSION: '1.2.2'
+ K6_REPORT_DIR: k6-report
+ BASE_URL: http://localhost:8000
+ # Must match THROTTLE_REQUESTS_PER_MINUTE below; the noisy flood is sized against it.
+ THROTTLE_REQUESTS_PER_MINUTE: '120'
+
+jobs:
+ performance:
+ name: API performance report (k6)
+ # Pull requests: only release branches into main, and not from forks (no secrets).
+ if: >-
+ github.event_name != 'pull_request' ||
+ ((startsWith(github.head_ref, 'release/v') || startsWith(github.head_ref, 'dev-v')) &&
+ github.event.pull_request.head.repo.full_name == github.repository)
+ runs-on: ubuntu-latest
+ timeout-minutes: 90
+
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ # Same gate as install-smoke.yml: without the token the API image cannot resolve
+ # the private Fleetbase packages, so skip rather than fail on forks.
+ - name: Check composer auth availability
+ id: auth
+ run: |
+ if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
+ echo "available=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "available=false" >> "$GITHUB_OUTPUT"
+ echo "::warning::_GITHUB_AUTH_TOKEN is not set; skipping the performance run (the API image cannot be built without it)."
+ fi
+
+ # app-release is the stage the published fleetbase-api image comes from; see the
+ # comment in install-smoke.yml for why not `app`.
+ - name: Build API image from source
+ if: steps.auth.outputs.available == 'true'
+ run: |
+ docker build \
+ --file docker/Dockerfile \
+ --target app-release \
+ --build-arg GITHUB_AUTH_KEY="${{ secrets._GITHUB_AUTH_TOKEN }}" \
+ --tag fleetbase/fleetbase-api:latest \
+ .
+
+ - name: Ensure clean database volume
+ if: steps.auth.outputs.available == 'true'
+ run: |
+ sudo rm -rf docker/database/mysql
+ mkdir -p docker/database/mysql
+
+ # Written BEFORE the stack starts: Laravel parses .env once at boot and deploy.sh
+ # runs config:cache, so values added later need the explicit re-cache done below.
+ #
+ # THROTTLE_ENABLED must be the literal string true/false (see api-contract.yml).
+ # The installer-generated docker-compose.override.yml sets no THROTTLE_* keys, so
+ # these are not shadowed by container environment.
+ - name: Configure throttling and run non-interactive installer
+ if: steps.auth.outputs.available == 'true'
+ run: |
+ set -euo pipefail
+ [ -f api/.env ] || cp api/.env.example api/.env 2>/dev/null || touch api/.env
+ set_env() {
+ if grep -q "^$1=" api/.env; then
+ sed -i "s|^$1=.*|$1=$2|" api/.env
+ else
+ echo "$1=$2" >> api/.env
+ fi
+ }
+ set_env THROTTLE_ENABLED true
+ set_env THROTTLE_REQUESTS_PER_MINUTE "${THROTTLE_REQUESTS_PER_MINUTE}"
+ set_env THROTTLE_DECAY_MINUTES 1
+ # Placeholder so the key exists; the real LOAD key is filled in after minting.
+ set_env THROTTLE_UNLIMITED_API_KEYS ''
+ set_env MAIL_MAILER log
+ set_env MAIL_FROM_ADDRESS [email protected]
+ grep '^THROTTLE_' api/.env
+
+ bash scripts/docker-install.sh --non-interactive
+
+ - name: Wait for API health
+ if: steps.auth.outputs.available == 'true'
+ run: |
+ set -uo pipefail
+ for _attempt in $(seq 1 60); do
+ if curl -fsS --max-time 5 "${BASE_URL}/health" | grep -q '"status"'; then
+ echo "API is healthy"; exit 0
+ fi
+ sleep 5
+ done
+ echo "::error::API did not become healthy"; exit 1
+
+ # Same tinker+base64 technique as .github/actions/postman-contract: a <?php tag
+ # piped to tinker is a PsySH parse error, and base64 keeps the shell away from the
+ # snippet's $variables.
+ - name: Mint k6 API keys
+ id: keys
+ if: steps.auth.outputs.available == 'true'
+ run: |
+ set -euo pipefail
+ CODE="$(base64 < scripts/ci/mint-k6-keys.php | tr -d '\n')"
+ OUT="$(docker compose exec -T application php artisan tinker \
+ --execute="eval(base64_decode('${CODE}'));" 2>&1 || true)"
+
+ # Every grep below may legitimately match nothing; under `bash -e` + pipefail
+ # an unguarded non-matching grep would abort the step before the diagnostics.
+ field() { printf '%s\n' "$OUT" | grep -oE "^$1=[^[:space:]]*" | tail -1 | cut -d= -f2- || true; }
+
+ if printf '%s\n' "$OUT" | grep -q 'K6_MINT_ERROR'; then
+ echo "::error::mint-k6-keys.php aborted:"
+ printf '%s\n' "$OUT" | grep -A 2 'K6_MINT_ERROR' || true
+ exit 1
+ fi
+ LOAD="$(field K6_LOAD_KEY)"; NOISY="$(field K6_NOISY_KEY)"; VICTIM="$(field K6_VICTIM_KEY)"
+ for v in LOAD NOISY VICTIM; do
+ if [[ ! "${!v}" =~ ^flb_live_ ]]; then
+ echo "::error::Could not mint the ${v} key. Tinker output (keys redacted):"
+ printf '%s\n' "$OUT" | sed -E 's/flb_(live|test)_[A-Za-z0-9_-]+/flb_\1_***/g'
+ exit 1
+ fi
+ echo "::add-mask::${!v}"
+ done
+ {
+ echo "load_key=${LOAD}"
+ echo "noisy_key=${NOISY}"
+ echo "victim_key=${VICTIM}"
+ echo "rate_limit=$(field K6_RATE_LIMIT)"
+ } >> "$GITHUB_OUTPUT"
+ echo "Minted LOAD/NOISY/VICTIM keys; throttle enabled=$(field K6_THROTTLE_ENABLED), per-key limit=$(field K6_RATE_LIMIT)"
+ if [[ "$(field K6_THROTTLE_ENABLED)" != "true" ]]; then
+ echo "::error::Throttling is not enabled on the stack; the isolation gate would be meaningless."
+ exit 1
+ fi
+
+ # Put the LOAD key on the unlimited list now that it exists.
+ #
+ # * api/.env is a single-file bind mount. `sed -i` replaces the file (new inode),
+ # and the container would keep reading the OLD inode — so rewrite it in place
+ # with `cat tmp > api/.env`, which keeps the inode.
+ # * deploy.sh ran `config:cache`, so the running app never reads .env again:
+ # re-cache so bootstrap/cache/config.php carries the new value.
+ # * Octane workers load the cached config when they boot; octane:reload restarts
+ # them. If a probe still sees the key throttled, restart the container as the
+ # heavier fallback (the config cache lives in the container layer and survives).
+ #
+ # The probe: a throttled consumer gets X-RateLimit-Limit on every response; an
+ # unlimited key gets none. k6's setup() repeats this check and aborts if it fails.
+ - name: Exempt the LOAD key from throttling
+ if: steps.auth.outputs.available == 'true'
+ env:
+ LOAD_KEY: ${{ steps.keys.outputs.load_key }}
+ run: |
+ set -euo pipefail
+ tmp="$(mktemp)"
+ grep -v '^THROTTLE_UNLIMITED_API_KEYS=' api/.env > "$tmp" || true
+ echo "THROTTLE_UNLIMITED_API_KEYS=${LOAD_KEY}" >> "$tmp"
+ cat "$tmp" > api/.env
+ rm -f "$tmp"
+
+ docker compose exec -T application php artisan config:cache
+ docker compose exec -T application php artisan octane:reload || true
+
+ bypassed() {
+ local headers
+ headers="$(curl -sS -o /dev/null -D - --max-time 20 \
+ -H "Authorization: Bearer ${LOAD_KEY}" "${BASE_URL}/v1/orders?limit=1" 2>/dev/null || true)"
+ # Only a real 2xx without the header counts; an error page also lacks it.
+ printf '%s\n' "$headers" | grep -qE '^HTTP/[0-9.]+ 2' || return 1
+ ! printf '%s\n' "$headers" | grep -qi '^x-ratelimit-limit:'
+ }
+ wait_bypassed() {
+ for _attempt in $(seq 1 "$1"); do
+ if bypassed; then return 0; fi
+ sleep 3
+ done
+ return 1
+ }
+
+ if wait_bypassed 20; then
+ echo "LOAD key is unthrottled after config:cache + octane:reload"
+ exit 0
+ fi
+ echo "::warning::LOAD key still throttled after octane:reload; restarting the application container"
+ docker compose restart application httpd
+ if wait_bypassed 40; then
+ echo "LOAD key is unthrottled after container restart"
+ exit 0
+ fi
+ echo "::error::THROTTLE_UNLIMITED_API_KEYS did not take effect for the LOAD key"
+ docker compose exec -T application php artisan tinker \
+ --execute="echo count(config('api.throttle.unlimited_keys')) . ' unlimited key(s) configured';" || true
+ exit 1
+
+ - name: Set up k6
+ if: steps.auth.outputs.available == 'true'
+ uses: grafana/setup-k6-action@v1
+ with:
+ k6-version: ${{ env.K6_VERSION }}
+
+ # The previous release's metrics.json, for the comparison columns. The newest release
+ # other than this tag that has one wins; none (first run, or older releases without
+ # the asset) just leaves the columns out.
+ - name: Fetch previous release metrics
+ id: baseline
+ if: steps.auth.outputs.available == 'true'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ CURRENT: ${{ github.ref_name }}
+ run: |
+ set -uo pipefail
+ mkdir -p baseline
+ tags="$(gh release list --repo "$GITHUB_REPOSITORY" --limit 30 --exclude-drafts --json tagName --jq '.[].tagName' 2>/dev/null || true)"
+ for tag in $tags; do
+ [[ "$tag" == "$CURRENT" ]] && continue
+ if gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern "performance-metrics-${tag}.json" --dir baseline --clobber 2>/dev/null; then
+ echo "path=${GITHUB_WORKSPACE}/baseline/performance-metrics-${tag}.json" >> "$GITHUB_OUTPUT"
+ echo "Comparing against ${tag}"
+ exit 0
+ fi
+ done
+ echo "No previous release metrics found; the report will have no comparison columns."
+
+ # Plain `k6 run` (not run-k6-action) so the exit code and output paths are ours.
+ # k6 exits 99 when a threshold fails; that is recorded and re-raised by the last
+ # step so the report is still published first.
+ - name: Run k6
+ id: k6
+ if: steps.auth.outputs.available == 'true'
+ env:
+ K6_LOAD_KEY: ${{ steps.keys.outputs.load_key }}
+ K6_NOISY_KEY: ${{ steps.keys.outputs.noisy_key }}
+ K6_VICTIM_KEY: ${{ steps.keys.outputs.victim_key }}
+ K6_RATE_LIMIT: ${{ steps.keys.outputs.rate_limit }}
+ RELEASE_VERSION: ${{ github.head_ref || github.ref_name }}
+ GIT_SHA: ${{ github.sha }}
+ GIT_REF: ${{ github.ref }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ SCENARIOS: ${{ inputs.scenarios || 'throughput,noisy_neighbour' }}
+ THROUGHPUT_PEAK_RATE: ${{ inputs.throughput_peak_rate }}
+ THROUGHPUT_DURATION: ${{ inputs.throughput_duration }}
+ NOISY_RATE: ${{ inputs.noisy_rate }}
+ NOISY_DURATION: ${{ inputs.noisy_duration }}
+ # Latency budgets are repository variables so they can be tuned to the runner
+ # without a code change; empty means the script's defaults (800 / 1500 ms).
+ READ_P95_MS: ${{ vars.K6_READ_P95_MS }}
+ WRITE_P95_MS: ${{ vars.K6_WRITE_P95_MS }}
+ MAX_ERROR_RATE: ${{ vars.K6_MAX_ERROR_RATE }}
+ ENFORCE_BUDGETS: ${{ vars.K6_ENFORCE_BUDGETS }}
+ BASELINE_METRICS: ${{ steps.baseline.outputs.path }}
+ K6_NO_USAGE_REPORT: 'true'
+ run: |
+ set -uo pipefail
+ mkdir -p "$K6_REPORT_DIR"
+ # Empty workflow_dispatch inputs arrive as empty strings; the script treats an
+ # empty value as "use the default", so they can be passed through unconditionally.
+ #
+ # GitHub runs this as `bash -e {0}`, and `set -uo pipefail` does not turn -e off:
+ # a bare `k6 run` exiting 99 would end the step before the exit code is recorded.
+ code=0
+ k6 run --quiet tests/k6/api-release.js || code=$?
+ echo "exit_code=${code}" >> "$GITHUB_OUTPUT"
+ if [[ "$code" -ne 0 && "$code" -ne 99 ]]; then
+ echo "::error::k6 exited with ${code} (not a threshold failure — see the log above)"
+ elif [[ "$code" -eq 99 ]]; then
+ echo "::error::k6 thresholds failed — see the report in the job summary"
+ fi
+ # Never fail here: the report steps must run first. The gate step re-raises.
+ exit 0
+
+ # Latency regression gate (release PRs). gate.json is written by handleSummary; a
+ # regression is re-measured once before it counts, because one run on a shared runner
+ # can be 20–30% off on its own.
+ - name: Evaluate latency regression
+ id: gate
+ if: steps.auth.outputs.available == 'true' && github.event_name == 'pull_request'
+ run: |
+ set -uo pipefail
+ regressed=false
+ if [[ -s "${K6_REPORT_DIR}/gate.json" ]]; then
+ regressed="$(jq -r '.regressed // false' "${K6_REPORT_DIR}/gate.json")"
+ jq -r '"Regression gate: evaluated=\(.evaluated) regressed=\(.regressed) \(.reason // "")"' "${K6_REPORT_DIR}/gate.json"
+ else
+ echo "No gate.json; the latency gate is not evaluated."
+ fi
+ echo "regressed=${regressed}" >> "$GITHUB_OUTPUT"
+
+ - name: Confirm latency regression
+ id: confirm
+ if: steps.gate.outputs.regressed == 'true'
+ env:
+ K6_LOAD_KEY: ${{ steps.keys.outputs.load_key }}
+ RELEASE_VERSION: ${{ github.head_ref }} (confirmation)
+ GIT_SHA: ${{ github.sha }}
+ GIT_REF: ${{ github.ref }}
+ SCENARIOS: throughput
+ READ_P95_MS: ${{ vars.K6_READ_P95_MS }}
+ WRITE_P95_MS: ${{ vars.K6_WRITE_P95_MS }}
+ MAX_ERROR_RATE: ${{ vars.K6_MAX_ERROR_RATE }}
+ BASELINE_METRICS: ${{ steps.baseline.outputs.path }}
+ K6_REPORT_DIR: k6-confirm
+ K6_NO_USAGE_REPORT: 'true'
+ run: |
+ set -uo pipefail
+ mkdir -p "$K6_REPORT_DIR"
+ k6 run --quiet tests/k6/api-release.js > /dev/null || true
+ confirmed=false
+ if [[ -s "${K6_REPORT_DIR}/gate.json" ]]; then
+ confirmed="$(jq -r '.regressed // false' "${K6_REPORT_DIR}/gate.json")"
+ fi
+ echo "confirmed=${confirmed}" >> "$GITHUB_OUTPUT"
+ echo "Confirmation run regressed: ${confirmed}"
+
+ - name: Publish report to job summary
+ if: always() && steps.auth.outputs.available == 'true'
+ run: |
+ if [[ -s "${K6_REPORT_DIR}/report.md" ]]; then
+ cat "${K6_REPORT_DIR}/report.md" >> "$GITHUB_STEP_SUMMARY"
+ if [[ -s k6-confirm/report.md ]]; then
+ printf '\n---\n## Confirmation run\n\n' >> "$GITHUB_STEP_SUMMARY"
+ sed -n '/^### Regression gate/,/^_A scope regresses/p' k6-confirm/report.md >> "$GITHUB_STEP_SUMMARY"
+ fi
+ else
+ echo "### k6 produced no report" >> "$GITHUB_STEP_SUMMARY"
+ echo "The run did not reach handleSummary(); see the Run k6 step log." >> "$GITHUB_STEP_SUMMARY"
+ fi
+
+ # One comment per PR, updated in place on every run.
+ - name: Post report on the release PR
+ if: always() && steps.auth.outputs.available == 'true' && github.event_name == 'pull_request'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ PR: ${{ github.event.pull_request.number }}
+ CONFIRMED: ${{ steps.confirm.outputs.confirmed }}
+ run: |
+ set -uo pipefail
+ marker='<!-- fleetbase-k6-performance-report -->'
+ {
+ echo "$marker"
+ if [[ -s "${K6_REPORT_DIR}/report.md" ]]; then
+ cat "${K6_REPORT_DIR}/report.md"
+ else
+ echo "### k6 produced no report — see the workflow run."
+ fi
+ if [[ -n "${CONFIRMED:-}" ]]; then
+ echo
+ echo "**Confirmation run:** latency regression $([[ "$CONFIRMED" == "true" ]] && echo "confirmed" || echo "not reproduced — treated as noise")."
+ fi
+ echo
+ echo "[Workflow run](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}) · full HTML report in the \`k6-report\` artifact"
+ } > pr-comment.md
+ # GitHub caps comment bodies at 65536 characters.
+ if [[ "$(wc -c < pr-comment.md)" -gt 65000 ]]; then
+ head -c 64000 pr-comment.md > pr-comment.tmp && printf '\n\n_…truncated; see the workflow run._\n' >> pr-comment.tmp && mv pr-comment.tmp pr-comment.md
+ fi
+ existing="$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments?per_page=100" --paginate \
+ --jq "[.[] | select(.user.login == \"github-actions[bot]\") | select(.body | startswith(\"${marker}\")) | .id] | first // empty" 2>/dev/null || true)"
+ # --paginate applies the filter per page; keep the first match.
+ existing="${existing%%$'\n'*}"
+ if [[ -n "$existing" ]]; then
+ gh api --method PATCH "repos/${GITHUB_REPOSITORY}/issues/comments/${existing}" -F [email protected] > /dev/null
+ else
+ gh api --method POST "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" -F [email protected] > /dev/null
+ fi
+
+ - name: Upload k6 report artifact
+ if: always() && steps.auth.outputs.available == 'true'
+ uses: actions/upload-artifact@v4
+ with:
+ name: k6-report
+ path: |
+ ${{ env.K6_REPORT_DIR }}/
+ k6-confirm/
+ if-no-files-found: warn
+ retention-days: 90
+
+ # Release attachment race: this workflow and create-release.yml both start on the
+ # same tag push. create-release finishes in well under a minute; this job needs an
+ # image build first, so the release almost always exists already — but "almost" is
+ # not a guarantee (queued runners, a create-release re-run). If softprops ran first
+ # it would CREATE the release without RELEASE.md as its body.
+ #
+ # So wait (up to 15 min) for the release create-release.yml publishes, then let
+ # softprops append the files to it. Chosen over `on: workflow_run` because
+ # workflow_run always executes the default branch's copy of this file with the
+ # default branch's context (github.ref_name would be `main`, checkout would need the
+ # tag's sha threaded through by hand), and it would serialise the benchmark behind
+ # release creation for no benefit. If the release never appears, skip the
+ # attachment with a warning; the artifact above still has the report.
+ - name: Wait for the GitHub Release
+ id: release
+ if: always() && steps.auth.outputs.available == 'true' && github.ref_type == 'tag'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ TAG: ${{ github.ref_name }}
+ run: |
+ set -uo pipefail
+ for _attempt in $(seq 1 90); do
+ if gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --silent 2>/dev/null; then
+ echo "exists=true" >> "$GITHUB_OUTPUT"
+ echo "Release ${TAG} found"
+ exit 0
+ fi
+ sleep 10
+ done
+ echo "exists=false" >> "$GITHUB_OUTPUT"
+ echo "::warning::No GitHub Release for ${TAG} after 15 minutes; the report was not attached (it is in the k6-report artifact)."
+
+ - name: Prepare release assets
+ if: always() && steps.release.outputs.exists == 'true'
+ env:
+ TAG: ${{ github.ref_name }}
+ run: |
+ set -uo pipefail
+ mkdir -p release-assets
+ for ext in md html; do
+ if [[ -s "${K6_REPORT_DIR}/report.${ext}" ]]; then
+ cp "${K6_REPORT_DIR}/report.${ext}" "release-assets/performance-report-${TAG}.${ext}"
+ fi
+ done
+ # The next release compares against this.
+ if [[ -s "${K6_REPORT_DIR}/metrics.json" ]]; then
+ cp "${K6_REPORT_DIR}/metrics.json" "release-assets/performance-metrics-${TAG}.json"
+ fi
+ ls -la release-assets
+
+ # Only tag_name + files: with an existing release softprops keeps its name, body,
+ # draft and prerelease flags and just uploads (overwriting same-named assets on a
+ # re-run).
+ - name: Attach report to the GitHub Release
+ if: always() && steps.release.outputs.exists == 'true'
+ uses: softprops/action-gh-release@v2
+ with:
+ tag_name: ${{ github.ref_name }}
+ files: |
+ release-assets/performance-report-${{ github.ref_name }}.md
+ release-assets/performance-report-${{ github.ref_name }}.html
+ release-assets/performance-metrics-${{ github.ref_name }}.json
+ fail_on_unmatched_files: false
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Dump logs on failure
+ if: failure() && steps.auth.outputs.available == 'true'
+ run: |
+ echo "===== docker compose ps ====="
+ docker compose ps || true
+ echo "===== docker compose logs ====="
+ docker compose logs --no-color --tail=300 || true
+
+ # The gate. Runs after publishing so a regression still ships its report.
+ - name: Enforce k6 thresholds
+ if: steps.auth.outputs.available == 'true'
+ env:
+ K6_EXIT: ${{ steps.k6.outputs.exit_code }}
+ run: |
+ if [[ "${K6_EXIT:-}" == "0" ]]; then
+ echo "All k6 thresholds passed."
+ exit 0
+ fi
+ echo "::error::k6 exit code ${K6_EXIT:-missing}: performance or throttling-isolation thresholds failed. See the job summary."
+ docker compose logs --no-color --tail=200 application || true
+ exit 1
+
+ # Runs after the correctness gate, so a label can never mask an error-rate or
+ # isolation failure. The label is read from the API, not the event payload, so
+ # adding it and re-running the job takes effect.
+ - name: Enforce latency regression gate
+ if: steps.confirm.outputs.confirmed == 'true'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ PR: ${{ github.event.pull_request.number }}
+ run: |
+ set -uo pipefail
+ labels="$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/labels" --jq '.[].name' 2>/dev/null || true)"
+ if printf '%s\n' "$labels" | grep -qx 'perf-regression-accepted'; then
+ echo "::warning::Latency regression confirmed but accepted via the perf-regression-accepted label."
+ exit 0
+ fi
+ echo "::error::Latency regression confirmed by a second run (see the Regression gate section of the report). If it is intended, add the perf-regression-accepted label and re-run this job."
+ exit 1
+
+ - name: Tear down
+ if: always() && steps.auth.outputs.available == 'true'
+ run: docker compose down -v || true
diff --git a/RELEASE.md b/RELEASE.md
index b1eb9b71..dbde3dd1 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -1,192 +1,50 @@
-> v0.7.65 ~ "Authenticator app sign-in, a security pass on sign-in and permissions, and Storefront promotions and campaigns"
+> v0.7.66 ~ "One API consumer can no longer rate-limit the whole platform, plus admin rate-limit controls, API consumer visibility and release performance reports"
---
## Highlights
-Fleetbase `0.7.65` ships Core API `1.6.65`, Fleet-Ops `0.6.70`, Storefront `0.4.22` and Ledger `0.0.11`.
+Fleetbase `0.7.66` ships Core API `1.6.66` and Storefront `0.4.23`.
-- **Sign in with an authenticator app.** Two-factor authentication can use an authenticator app, with recovery codes, set up from Account › Auth.
-- **A security pass on sign-in and permissions:**
- - two-factor sign-in checks the password first;
- - changing a password needs the current one;
- - organization settings, reports, API keys and webhooks are behind IAM permissions;
- - Fleet-Ops enforces its permissions across the API and console.
-- **Storefront promotions, promo codes, customer segments and campaigns**, a customer notifications inbox, and rebuilt push notifications.
-- **Fleet-Ops prunes old telematics data automatically**, with retention settings per organization.
-- **Admins get richer organization pages**: search and filters, usage, recent activity, and each member's two-factor and sign-in details.
-- **The Docker installer works on macOS and Windows.**
+- **Rate limiting is per API consumer.** One integration sending a burst of order requests with a single API key put the entire platform into `429 Too many requests` for every tenant, app and console user. Each API key or token now has its own limit, so only the busy consumer is throttled.
+- **Admins control rate limits from the console.** Admin › API Traffic › Rate Limits sets the per-consumer limit and window, and adds per-organization overrides (a custom limit, or unlimited) for high-volume integrations.
+- **Admins can see who is using the API.** Admin › API Traffic › API Consumers shows requests, 429s and a timeline for the last 5 minutes to 7 days, with a per-consumer table. A throttled consumer can be unblocked with one click.
+- **Every release gets an API performance report.** p50/p90/p95/p99 latency, throughput and error rate, overall and per endpoint, compared against the previous release, attached to the GitHub Release.
---
## Component Versions
-- `console`: `0.7.65`
-- `core-api`: `1.6.65`
+- `console`: `0.7.66`
+- `core-api`: `1.6.66`
- `fleetops`: `0.6.70`
-- `storefront`: `0.4.22`
+- `storefront`: `0.4.23`
- `ledger`: `0.0.11`
- `ember-ui`: `0.4.4`
- `registry-bridge`: `0.1.10`
- `customer-portal`: `0.0.15`
---
-## Security
-- **Two-factor sign-in checks the password first** (core-api #272, fleetbase #684, customer-portal #20). The console and Customer Portal asked the server about two-factor before sending the password. That started a two-factor session, so an email address plus the emailed or texted code was enough to sign in. It also revealed whether an account had two-factor on. The password is now checked first. Two-factor sessions expire after 10 minutes, where they used to last for years. The fifth wrong code ends the session, and the console returns you to the login page.
-- **Changing your password needs the current password** (core-api #275, fleetbase #685). The server never checked it, so a stolen session could change the password. It is checked in the same request now. Setting a first password works only once, within 24 hours of accepting an invite. Password checks are limited to 10 a minute.
-- **Organization settings and core endpoints need the right permissions** (core-api #278):
- - Any member could update the organization, including making themselves its owner, or changing its plan and status. Only the owner, the Administrator role or a system admin can now, and ownership, billing and status fields are ignored for anyone else.
- - Only the owner, the Administrator role or a system admin can change the organization's two-factor policy. The system two-factor policy is for system admins only.
- - Reports were open to every user. Running a report query needs `iam execute report`, and exporting needs `iam export report`.
- - Any user could list and create API keys. API keys, webhooks, API events and request logs now need their Developers permissions. Platform metrics are admin-only.
-- **Fleet-Ops enforces its permissions across the API and console** (fleetops #345, ember-ui #185):
- - The Navigator app link could be opened without signing in, and handed out an API key for the first system admin's organization. It is now a signed link that expires after 30 minutes, and only system admins can create one.
- - Saving entity-editing settings overwrote other organizations' settings, and driver onboard settings could be saved for another organization. Both are limited to your own organization.
- - Bulk actions ran without their permission, for example bulk delete, cancel or dispatch. They are now disabled for users who lack it, and navigation hides what you can't open.
-- **Reports check every computed column** (core-api #269). Grouped reports accepted computed SQL from the browser without checking it. Every computed column is now validated, and schema columns always take their SQL from the server.
-- **Wallet updates can no longer set a balance directly** (ledger #24).
+## Fixes
+- **One API consumer could rate-limit the whole platform** (core-api #280, fleetbase #689). The rate limiter ran before the API key was authenticated, so it keyed every bucket on the client IP. Behind a load balancer that is the balancer's address, so every tenant, integration, driver app and console visitor shared one bucket of 120 requests a minute. A single customer creating orders over the API returned 429 to everyone, including people trying to sign in. The limiter now keys on the API key or token, and keeps the public API and the console's sign-in routes apart.
+- **One busy store could rate-limit every other store** (storefront #108). The Storefront API limiter had the same IP-keyed bucket, and its key collided with the core API's. It now keys on the store key plus the client IP, so each device of each store has its own limit.
+- **The API sees the real client IP behind proxies** (fleetbase #689). Proxies on private networks are trusted by default, so rate limiting and request logs see the caller's address instead of the load balancer's. Set `TRUSTED_PROXIES` for load balancers that connect from public addresses (e.g. Google Cloud: `35.191.0.0/16,130.211.0.0/22`).
+- **429 responses tell clients when to retry** (core-api #280). `Retry-After` and `X-RateLimit-*` headers were being dropped.
---
-## Authenticator App Two-Factor Authentication
-(core-api #277, fleetbase #686)
-
-- **Authenticator App** is a two-factor method in Account › Auth, marked Recommended. It works with Authy, Google Authenticator, Microsoft Authenticator, 1Password and other TOTP apps.
-- Setup asks for your current password, shows a QR code and the key for manual entry, checks a code from the app, then gives you 8 single-use recovery codes to copy or download.
-- The **Authenticator App** panel sets the app up, removes it, or issues new recovery codes, each after your current password.
-- At sign-in you enter the code from the app, or **Use a recovery code**, or **Send me a code instead** to fall back to email or SMS.
-- Organization and system two-factor settings can't make the authenticator app the default, since each user has to set it up.
-- The app secret is encrypted, and recovery codes are stored hashed.
-
----
-## Accounts, Access and Administration
-- **Settings › Authentication** has an "Allow users to change their own password" setting, on by default. With it off, users need the `iam change-password` permission. Admins and Administrators can always change their own. Account › Auth shows a note instead of the form when you can't (core-api #275, fleetbase #685).
-- Invited users who aren't admins can set their first password again (core-api #275).
-- Password and auth-setting changes are written to the activity log (core-api #275).
-- **Admin › Organizations**:
- - Search covers owners, emails and phone numbers.
- - New filters for owner name, phone and IP address, timezone, organization type, and registered and updated dates.
- - Choose which columns to show. A new Registered column is added, and Last Activity is renamed Last Updated.
- - Filters survive the dropdown's Apply, **Clear** resets everything, and **Export selected** exports the rows you checked (core-api 1.6.65, fleetbase).
-- **Organization details**:
- - The Overview tab has an organization profile and the owner.
- - Usage shows users, drivers, customers, orders, API calls and webhook callbacks.
- - A recent activity feed is added.
- - The Users tab shows each member's two-factor method, linked sign-in providers and last sign-in.
- - The separate Extensions tab is removed.
- - Admins can open organizations they aren't a member of (core-api 1.6.65, fleetbase).
-
----
-## Fleet-Ops
-- **Telematics data retention** (#341).
- - New settings page: Fleet-Ops › Settings › **Telematics Data**, with storage usage and **Run cleanup now**.
- - Old data is pruned every 15 minutes by `fleetops:prune-telematics-data`. By default it keeps:
- - device events for 30 days, with raw payloads removed after 7;
- - positions for 90 days;
- - processed deliveries for 24 hours, and quarantined ones for 7 days;
- - sync runs for 7 days.
- - New device events no longer store the raw payload twice, which roughly halves their size.
-- **New permissions** (#345):
- - Maintenance schedules, devices, sensors, device events, telematics, warranties, purchase rates, fuel provider connections, transactions and sync runs, analytics, and scheduling and tracking settings.
- - Dispatching an order now needs `dispatch order` instead of `update order`. Fleet-Ops dashboards and metrics need `view analytics`.
- - Buttons, bulk actions, navigation and live map layers follow your permissions. Users who aren't admins used to see an empty live map.
-- **Orders report** (#342, core-api #269):
- - The Orders report adds order ID and Internal ID, tracking number and status, payload items (one row per item), and more order columns.
- - Summaries count each order once. Deleted records are left out, and references to columns that don't exist are removed from the Drivers, Vehicles and Fuel Reports reports.
-- Custom field values on fuel reports and service areas are saved. They were silently dropped (#342).
-- Company settings apply in queued jobs and console commands. Affected: operational alerts, driver shift-change notifications, Vroom orchestration, tracking options and the customer credentials email (#344).
-- Android order push notifications are sent at high priority, so they arrive while a driver's phone is idle (core-api #273).
-
----
-## Storefront
-- **Promotions** (#104, #106):
- - Percentage, fixed-amount, free-delivery and buy-one-get-one discounts.
- - A promotion applies automatically or through a promo code. Each one supports targeting, conditions, schedules, usage limits, budgets and stacking.
- - Discounts are priced into cash, Stripe and QPay checkouts. A promo code that can't be applied stops the checkout with an error.
- - Console screens for promotions and promo codes, including batch code generation.
-- **Customer segments and campaigns** (#105, #106):
- - Rule-based segments with a live preview.
- - Push and inbox campaigns, sent now or scheduled, and a promotion can be announced when it starts.
- - The existing "send push notification" action now creates a campaign, so it respects opt-outs and also writes to the inbox.
-- **Customer notifications inbox API** (#103): `storefront/v1/notifications` endpoints. Customers can list, read and delete notifications, and set whether they get order updates and promotions.
-- **Push notifications rebuilt on one Storefront push channel** (#102):
- - Pushes reach Android and some iOS devices again, and Android pushes are high priority. iOS development builds are retried in the other APNs environment, and APNs channels get an environment setting.
- - Push is sent before email, so a mail error no longer blocks it. Dead device tokens are removed.
- - **Send test** on a notification channel shows Apple's or Google's raw response for a device token.
- - Promotions and Push Notifications move under `promotions/`.
-- Ukrainian translation, thanks to @ispdomnet (#101).
-
----
-## Ledger
-- The base currency and default invoice currency save again, and a wallet's currency can be changed (#24, fixes fleetbase #678).
-- Invoices created in the background, for example from order purchase rates, use the organization's invoice prefix, currency, terms, notes, template and due date (#27).
-- Ledger's widgets have set places on the default dashboard, and Overdue AR is added to it (#25).
-- Ukrainian translation, thanks to @ispdomnet (#23).
-
----
-## Customer Portal
-- The portal can be translated, with a language switcher. Russian is added, thanks to @spanchenko (#13), and Mongolian too.
-- Ticket comment emails use the portal's configured URL slug (#19).
-
----
-## Registry Bridge
-- `flb verify` accepts the emailed code again when you create a developer account. It always said the code was invalid or had expired (#38, fixes fleetbase #683).
-- Ukrainian translation, thanks to @ispdomnet (#37).
-
----
-## Console, UI and Notifications
-- The default dashboard has a set layout: KPIs first, then the live fleet map, reports, and the Blog and GitHub widgets last (fleetbase #682, fleetops #342, ledger #25, ember-ui 0.4.4). Earnings and Average Order Value are no longer on it by default, but can still be added.
-- The GitHub widget has a new look: a Star button, the latest release, and star, watcher, fork and issue counts. It no longer scrolls inside its panel (fleetbase #682).
-- Settings › Notifications apply when the queue runs as its own process, including the Docker Compose setup. They were silently ignored (core-api #274).
-- **Test SMS Provider** and **Test Twilio** in Admin › System Config › Services use the credentials in the form. Under Octane they failed, or tested the saved credentials instead (core-api #270, fixes fleetbase #680).
-- The report builder can group, sort and filter on computed columns, sort grouped reports by a summary, and count distinct values (ember-ui 0.4.4, core-api #269).
-- A signature pad custom field type (ember-ui 0.4.4).
-- Tall modals grow and scroll, and the popover arrow is drawn (ember-ui 0.4.4).
-- "Configutation" is spelled correctly in the Push Notifications settings (fleetbase #681, fixes fleetbase #679).
-
----
-## Installer
-(fleetbase #677)
-
-- `scripts/docker-install.sh` runs on macOS's stock `/bin/bash` 3.2 and on Windows Git Bash. The interactive wizard used to crash on macOS with `bad substitution`.
-- The port check works on macOS and Windows, and only warns.
-- The installer creates `api/.env` before starting the stack. Docker used to create a directory there, and the API couldn't boot.
-- A root `.gitattributes` keeps shell scripts, Dockerfiles and config files LF on Windows checkouts.
-
----
-## Console and API Packages
-- Bumped the root Docker image version to `0.7.65`.
-- Bumped Console to `0.7.65`.
-- Updated the API dependencies: `fleetbase/core-api` to `^1.6.65`, `fleetbase/fleetops-api` to `^0.6.70`, `fleetbase/storefront-api` to `^0.4.22`, `fleetbase/ledger-api` to `^0.0.11`, `fleetbase/registry-bridge` to `^0.1.10`, and `fleetbase/customer-portal-api` to `^0.0.15`.
-- Updated the Console dependencies: `@fleetbase/fleetops-engine` to `^0.6.70`, `@fleetbase/storefront-engine` to `^0.4.22`, `@fleetbase/ledger-engine` to `^0.0.11`, `@fleetbase/registry-bridge-engine` to `^0.1.10`, `@fleetbase/customer-portal-engine` to `^0.0.15`, and `@fleetbase/ember-ui` to `^0.4.4`.
-- Updated the component submodules to their release tags, and the API and Console lockfiles.
-
----
-## Bug Fixes
-- Fixed a two-factor code being enough to sign in without the password.
-- Fixed any organization member being able to take ownership of it or change its plan.
-- Fixed reports, API keys and webhooks being open to every user.
-- Fixed Fleet-Ops bulk actions running without their permission, and the Navigator app link working without sign-in.
-- Fixed the settings page for changing your own password being unreachable, and invited users being unable to set a password.
-- Fixed notification, invoice and Fleet-Ops company settings being ignored in queued jobs.
-- Fixed Test SMS using the saved credentials or failing under Octane.
-- Fixed Storefront push notifications not reaching Android and some iOS devices.
-- Fixed Ledger currencies not saving and wallet currencies not being editable.
-- Fixed custom field values on fuel reports and service areas not saving.
-- Fixed `flb verify` rejecting valid codes.
-- Fixed the Docker installer failing on macOS and Windows, and leaving `api/.env` as a directory.
-- Fixed "Configutation" in the Push Notifications settings.
+## Improvements
+- **Admin › API Traffic › Rate Limits** (core-api #281, fleetbase #690):
+ - Turn rate limiting on or off, and set the requests per window and the window length.
+ - Turn consumer tracking on or off.
+ - Add per-organization overrides.
+ - "Reset to Defaults" returns to the `THROTTLE_*` environment values.
+- **Admin › API Traffic › API Consumers** (core-api #281, fleetbase #690):
+ - Totals for requests, 429s and active consumers, plus a request timeline.
+ - The busiest or most throttled API keys, tokens and addresses, with their organization, request rate, peak and limit.
+ - Counts are kept in Redis.
+- **API performance report on every release** (fleetbase #691). A k6 run exercises the public API: orders, places, contacts, drivers, vehicles, fleets and more. The report is published to the job summary and attached to the GitHub Release as `performance-report-<tag>.md/.html` and `performance-metrics-<tag>.json`.
---
## Upgrade Steps
-This release includes database migrations. `deploy.sh` runs them, creates the new permissions and restarts the queue.
-
-- **Deploy the API and console together.** An older console can't sign in users who have two-factor on, and can't change passwords.
-- **Grant the new permissions to roles other than Administrator.** Users without them lose access:
- - running and exporting reports (`iam execute report`, `iam export report`);
- - API keys, webhooks, events and logs in Developers;
- - dispatching orders (`fleet-ops dispatch order`);
- - Fleet-Ops dashboards and metrics (`fleet-ops view analytics`);
- - the new Fleet-Ops resources.
-- **Telematics retention is on by default** and starts deleting old telematics data on the first scheduler run. To keep history, set the values to `0` under Fleet-Ops › Settings › Telematics Data before upgrading. The Fleet-Ops migrations add indexes to `device_events` and `positions`; on large tables, run them in a maintenance window. Deleted rows free space inside MySQL; run `OPTIMIZE TABLE` off-peak to return it to disk.
-- **Keep the scheduler and a queue worker running.** Storefront campaigns, promotion reservations and telematics pruning depend on them.
-- **Storefront apps:** `customers/register-device` now requires `token` and `platform` (`ios` or `android`). Update your Storefront app so it registers devices this way. Optionally set `STOREFRONT_PUSH_ANDROID_CHANNEL_ID`.
-- Users who accepted an invite before this upgrade and never set a password should use **Forgot password**.
+- **Check `TRUSTED_PROXIES` if your load balancer connects from a public address** (for example Google Cloud load balancers). The default trusts only private and loopback ranges.
+- **High-volume API integrations:** each API key now gets its own `THROTTLE_REQUESTS_PER_MINUTE` (default 120). Give heavy integrations an organization override under Admin › API Traffic › Rate Limits.
+- Consumer metrics need Redis, which the bundled stack provides. Set `THROTTLE_TRACK_CONSUMERS=false` to turn them off.
```bash
# Pull latest version
diff --git a/api/composer.json b/api/composer.json
index 021283d6..8a933769 100644
--- a/api/composer.json
+++ b/api/composer.json
@@ -20,12 +20,12 @@
"require": {
"php": ">=8.0 <8.3",
"appstract/laravel-opcache": "^4.0",
- "fleetbase/core-api": "^1.6.65",
+ "fleetbase/core-api": "^1.6.66",
"fleetbase/ai": "^0.0.5",
"fleetbase/fleetops-api": "^0.6.70",
"fleetbase/registry-bridge": "^0.1.10",
"fleetbase/customer-portal-api": "^0.0.15",
- "fleetbase/storefront-api": "^0.4.22",
+ "fleetbase/storefront-api": "^0.4.23",
"fleetbase/ledger-api": "^0.0.11",
"fleetbase/valhalla-api": "^0.0.4",
"fleetbase/vroom-api": "^0.0.4",
diff --git a/api/composer.lock b/api/composer.lock
index f96c2711..c8047629 100644
--- a/api/composer.lock
+++ b/api/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "17faf44a1de29e590914a962fcdc5d9e",
+ "content-hash": "75df3f80f6787d23dfa3903b6e452efe",
"packages": [
{
"name": "appstract/laravel-opcache",
@@ -2310,16 +2310,16 @@
},
{
"name": "fleetbase/core-api",
- "version": "1.6.65",
+ "version": "1.6.66",
"source": {
"type": "git",
"url": "https://github.com/fleetbase/core-api.git",
- "reference": "b82d921425d4578ae42aff855077e76445a05315"
+ "reference": "74cc07ce7a1805405099dfda8a252451a4fbe0f0"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/fleetbase/core-api/zipball/b82d921425d4578ae42aff855077e76445a05315",
- "reference": "b82d921425d4578ae42aff855077e76445a05315",
+ "url": "https://api.github.com/repos/fleetbase/core-api/zipball/74cc07ce7a1805405099dfda8a252451a4fbe0f0",
+ "reference": "74cc07ce7a1805405099dfda8a252451a4fbe0f0",
"shasum": ""
},
"require": {
@@ -2415,9 +2415,9 @@
],
"support": {
"issues": "https://github.com/fleetbase/core-api/issues",
- "source": "https://github.com/fleetbase/core-api/tree/v1.6.65"
+ "source": "https://github.com/fleetbase/core-api/tree/v1.6.66"
},
- "time": "2026-09-28T09:49:17+00:00"
+ "time": "2026-09-29T09:39:18+00:00"
},
{
"name": "fleetbase/countries",
@@ -2874,16 +2874,16 @@
},
{
"name": "fleetbase/storefront-api",
- "version": "0.4.22",
+ "version": "0.4.23",
"source": {
"type": "git",
"url": "https://github.com/fleetbase/storefront.git",
- "reference": "940c5ae35f9e4b3a6bd2dc53b7e89f1bdcc0ae67"
+ "reference": "6ac5f502e87105d447a5423254ff7956ce788157"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/fleetbase/storefront/zipball/940c5ae35f9e4b3a6bd2dc53b7e89f1bdcc0ae67",
- "reference": "940c5ae35f9e4b3a6bd2dc53b7e89f1bdcc0ae67",
+ "url": "https://api.github.com/repos/fleetbase/storefront/zipball/6ac5f502e87105d447a5423254ff7956ce788157",
+ "reference": "6ac5f502e87105d447a5423254ff7956ce788157",
"shasum": ""
},
"require": {
@@ -2951,9 +2951,9 @@
],
"support": {
"issues": "https://github.com/fleetbase/storefront/issues",
- "source": "https://github.com/fleetbase/storefront/tree/v0.4.22"
+ "source": "https://github.com/fleetbase/storefront/tree/v0.4.23"
},
- "time": "2026-09-28T10:52:32+00:00"
+ "time": "2026-09-29T09:59:16+00:00"
},
{
"name": "fleetbase/twilio",
diff --git a/api/config/trustedproxy.php b/api/config/trustedproxy.php
new file mode 100644
index 00000000..bf0a08a9
--- /dev/null
+++ b/api/config/trustedproxy.php
@@ -0,0 +1,25 @@
+<?php
+
+return [
+ /*
+ |--------------------------------------------------------------------------
+ | Trusted Proxies
+ |--------------------------------------------------------------------------
+ |
+ | The proxies (load balancers, ingress controllers, the bundled httpd) whose
+ | X-Forwarded-* headers are believed when resolving the client IP. Without
+ | this, $request->ip() is the nearest proxy's address, so every caller looks
+ | like the same client to anything keyed on IP (rate limiting, audit logs).
+ |
+ | The default trusts private and loopback ranges only: a public client cannot
+ | spoof its address, and a directly-exposed server ignores the headers. A load
+ | balancer that connects from public addresses (e.g. Google Cloud's front ends)
+ | must be listed explicitly. "*" trusts whichever proxy connected.
+ |
+ | Example: TRUSTED_PROXIES=10.0.0.0/8,35.191.0.0/16,130.211.0.0/22
+ |
+ */
+ 'proxies' => ($proxies = env('TRUSTED_PROXIES', '10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.0/8,::1,fc00::/7')) === '*'
+ ? '*'
+ : array_values(array_filter(array_map('trim', explode(',', (string) $proxies)))),
+];
diff --git a/api/tests/Unit/Http/Middleware/TrustProxiesTest.php b/api/tests/Unit/Http/Middleware/TrustProxiesTest.php
new file mode 100644
index 00000000..1809f637
--- /dev/null
+++ b/api/tests/Unit/Http/Middleware/TrustProxiesTest.php
@@ -0,0 +1,64 @@
+<?php
+
+namespace Tests\Unit\Http\Middleware;
+
+use App\Http\Middleware\TrustProxies;
+use Illuminate\Http\Request;
+use Tests\TestCase;
+
+/**
+ * Rate limiting and request logs key on $request->ip(). Behind the bundled httpd or a
+ * cloud load balancer that is the proxy's address unless the proxy is trusted, which
+ * made every caller on the platform share a single rate-limit bucket.
+ */
+class TrustProxiesTest extends TestCase
+{
+ public function test_a_private_network_proxy_forwards_the_client_ip_by_default(): void
+ {
+ $this->assertSame('41.0.0.1', $this->resolveIp('172.18.0.9', '41.0.0.1'));
+ }
+
+ public function test_a_public_caller_cannot_spoof_its_ip_by_default(): void
+ {
+ $this->assertSame('198.51.100.20', $this->resolveIp('198.51.100.20', '41.0.0.1'));
+ }
+
+ public function test_every_private_hop_is_skipped_to_reach_the_client(): void
+ {
+ $this->assertSame('41.0.0.1', $this->resolveIp('172.18.0.9', '41.0.0.1, 10.0.4.12'));
+ }
+
+ public function test_the_configured_list_replaces_the_default(): void
+ {
+ config(['trustedproxy.proxies' => ['35.191.0.0/16']]);
+
+ $this->assertSame('41.0.0.1', $this->resolveIp('35.191.2.3', '41.0.0.1'));
+ $this->assertSame('172.18.0.9', $this->resolveIp('172.18.0.9', '41.0.0.1'));
+ }
+
+ public function test_a_wildcard_trusts_the_connecting_proxy(): void
+ {
+ config(['trustedproxy.proxies' => '*']);
+
+ $this->assertSame('41.0.0.1', $this->resolveIp('198.51.100.20', '41.0.0.1'));
+ }
+
+ private function resolveIp(string $remoteAddr, string $forwardedFor): string
+ {
+ $request = Request::create('/v1/orders', 'GET', [], [], [], [
+ 'REMOTE_ADDR' => $remoteAddr,
+ 'HTTP_X_FORWARDED_FOR' => $forwardedFor,
+ ]);
+
+ $ip = null;
+ (new TrustProxies())->handle($request, function (Request $request) use (&$ip) {
+ $ip = $request->ip();
+
+ return response('ok');
+ });
+
+ Request::setTrustedProxies([], Request::HEADER_X_FORWARDED_FOR);
+
+ return $ip;
+ }
+}
diff --git a/console/app/components/admin/api-consumers.hbs b/console/app/components/admin/api-consumers.hbs
new file mode 100644
index 00000000..6fdccbf6
--- /dev/null
+++ b/console/app/components/admin/api-consumers.hbs
@@ -0,0 +1,93 @@
+<EmberWormhole @to="next-view-section-subheader-actions">
+ <div class="flex items-center gap-2">
+ <div class="inline-flex overflow-hidden rounded-md border border-gray-300 shadow-sm dark:border-gray-700" role="group" aria-label="Time window" data-test-windows>
+ {{#each this.windows as |option|}}
+ <button
+ type="button"
+ class="border-r border-gray-300 px-2 py-1 text-xs font-medium last:border-r-0 dark:border-gray-700
+ {{if (eq option.value this.window) 'bg-blue-600 text-white' 'bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700'}}"
+ aria-pressed={{if (eq option.value this.window) "true" "false"}}
+ {{on "click" (fn this.setWindow option)}}
+ data-test-window={{option.value}}
+ >{{option.label}}</button>
+ {{/each}}
+ </div>
+ <div class="inline-flex overflow-hidden rounded-md border border-gray-300 shadow-sm dark:border-gray-700" role="group" aria-label="Sort by">
+ <button
+ type="button"
+ class="border-r border-gray-300 px-2 py-1 text-xs font-medium dark:border-gray-700
+ {{if (eq this.sort 'hits') 'bg-blue-600 text-white' 'bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700'}}"
+ {{on "click" (fn this.setSort "hits")}}
+ data-test-sort="hits"
+ >Most requests</button>
+ <button
+ type="button"
+ class="px-2 py-1 text-xs font-medium
+ {{if (eq this.sort 'throttled') 'bg-blue-600 text-white' 'bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700'}}"
+ {{on "click" (fn this.setSort "throttled")}}
+ data-test-sort="throttled"
+ >Most throttled</button>
+ </div>
+ <Button @size="xs" @icon="arrows-rotate" @helpText="Refresh" @onClick={{perform this.load}} @isLoading={{this.load.isRunning}} data-test-refresh />
+ </div>
+</EmberWormhole>
+
+<div class="space-y-3 p-4" ...attributes>
+ {{#if this.data}}
+ {{#unless this.data.available}}
+ <div
+ class="flex items-center rounded-md border border-yellow-400 bg-yellow-50 px-3 py-2 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-100"
+ data-test-unavailable
+ >
+ <FaIcon @icon="triangle-exclamation" class="mr-2" />
+ Consumer metrics are unavailable: they are stored in Redis, which could not be reached.
+ </div>
+ {{/unless}}
+ {{#unless this.data.tracking}}
+ <div
+ class="flex items-center rounded-md border border-blue-300 bg-blue-50 px-3 py-2 text-xs text-blue-800 dark:border-blue-700 dark:bg-blue-900/40 dark:text-blue-100"
+ data-test-not-tracking
+ >
+ <FaIcon @icon="circle-info" class="mr-2" />
+ Consumer tracking is turned off in
+ <LinkTo @route="console.admin.rate-limits" class="mx-1 underline">Rate Limits</LinkTo>, so no new requests are being counted.
+ </div>
+ {{/unless}}
+
+ <div
+ class="grid grid-cols-2 divide-gray-200 overflow-hidden rounded-md border border-gray-200 bg-white shadow-sm sm:grid-cols-5 sm:divide-x dark:divide-gray-700 dark:border-gray-700 dark:bg-gray-800"
+ data-test-stats
+ >
+ {{#each this.stats as |stat|}}
+ <div class="px-3 py-2" data-test-stat={{stat.key}}>
+ <div class="truncate text-[10px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">{{stat.label}}</div>
+ <div class="mt-0.5 flex items-baseline gap-1.5">
+ <span class="text-lg font-bold leading-6 tabular-nums {{if stat.isAlert 'text-rose-600 dark:text-rose-300' 'text-gray-900 dark:text-gray-100'}}">{{stat.value}}</span>
+ {{#if stat.hint}}
+ <span class="truncate text-[11px] text-gray-500 dark:text-gray-400">{{stat.hint}}</span>
+ {{/if}}
+ </div>
+ </div>
+ {{/each}}
+ </div>
+
+ {{#each this.charts as |chart|}}
+ <div class="rounded-md border border-gray-200 bg-white p-3 shadow-sm dark:border-gray-700 dark:bg-gray-800" data-test-timeline>
+ <div class="text-[10px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Requests over the {{this.windowDescription}}</div>
+ <div class="h-48">
+ <Chart @type="line" @labels={{chart.labels}} @datasets={{chart.datasets}} @options={{chart.options}} @wrapperClass="h-full" />
+ </div>
+ </div>
+ {{/each}}
+
+ <div class="overflow-hidden rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800" data-test-consumers-table>
+ {{#if this.consumers.length}}
+ <Table @rows={{this.consumers}} @columns={{this.columns}} />
+ {{else}}
+ <div class="px-4 py-10 text-center text-sm text-gray-500 dark:text-gray-400" data-test-empty>No API requests in the {{this.windowDescription}}.</div>
+ {{/if}}
+ </div>
+ {{else}}
+ <div class="flex justify-center py-10"><Spinner /></div>
+ {{/if}}
+</div>
\ No newline at end of file
diff --git a/console/app/components/admin/api-consumers.js b/console/app/components/admin/api-consumers.js
new file mode 100644
index 00000000..2c5420d3
--- /dev/null
+++ b/console/app/components/admin/api-consumers.js
@@ -0,0 +1,307 @@
+import Component from '@glimmer/component';
+import { inject as service } from '@ember/service';
+import { tracked } from '@glimmer/tracking';
+import { action } from '@ember/object';
+import { task } from 'ember-concurrency';
+import { format, formatDistanceToNowStrict, parseISO } from 'date-fns';
+
+export const WINDOWS = [
+ { value: 5, label: '5m' },
+ { value: 15, label: '15m' },
+ { value: 60, label: '1h' },
+ { value: 360, label: '6h' },
+ { value: 1440, label: '24h' },
+ { value: 10080, label: '7d' },
+];
+
+const WINDOW_DESCRIPTIONS = {
+ 5: 'last 5 minutes',
+ 15: 'last 15 minutes',
+ 60: 'last hour',
+ 360: 'last 6 hours',
+ 1440: 'last 24 hours',
+ 10080: 'last 7 days',
+};
+
+export const CONSUMER_TYPES = {
+ api_key: { label: 'API key', icon: 'key' },
+ token: { label: 'Access token', icon: 'id-badge' },
+ user: { label: 'User', icon: 'user' },
+ ip: { label: 'Anonymous', icon: 'globe' },
+ unknown: { label: 'Unrecognized', icon: 'circle-question' },
+};
+
+function number(value) {
+ return new Intl.NumberFormat().format(value ?? 0);
+}
+
+function parseDate(value) {
+ if (!value) return null;
+ const date = parseISO(value);
+ return Number.isNaN(date.getTime()) ? null : date;
+}
+
+/**
+ * Which API consumers drive traffic and which are being throttled, platform-wide.
+ *
+ * Counts come from the throttle middleware, so they include requests rejected with 429 —
+ * something the API request log never sees.
+ */
+export default class AdminApiConsumersComponent extends Component {
+ @service fetch;
+ @service notifications;
+ @service router;
+ @service currentUser;
+
+ windows = WINDOWS;
+
+ @tracked window = 15;
+ @tracked sort = 'hits';
+ @tracked data = null;
+
+ columns = [
+ {
+ label: 'Consumer',
+ valuePath: 'label',
+ cellComponent: 'admin/table/cell/api-consumer',
+ width: '320px',
+ sticky: true,
+ resizable: true,
+ },
+ {
+ label: 'Organization',
+ valuePath: 'organization',
+ cellComponent: 'table/cell/identity',
+ resourceType: 'company',
+ resourcePath: 'organization',
+ labelPath: 'name',
+ popover: false,
+ hideBadges: true,
+ emptyText: '—',
+ onClick: this.openOrganization,
+ width: '220px',
+ resizable: true,
+ },
+ { label: 'Scope', valuePath: 'scopeLabel', width: '80px', cellClassNames: 'font-mono text-xs' },
+ { label: 'Requests', valuePath: 'hitsLabel', width: '100px', resizable: true },
+ { label: 'Avg / min', valuePath: 'avgLabel', width: '90px' },
+ { label: 'Peak / min', valuePath: 'peakLabel', width: '90px' },
+ { label: 'Throttled', valuePath: 'throttledLabel', cellComponent: 'admin/table/cell/throttled', width: '110px' },
+ { label: 'Limit', valuePath: 'limitLabel', width: '100px' },
+ { label: 'Share', valuePath: 'share', cellComponent: 'admin/table/cell/share', width: '130px' },
+ { label: 'Last seen', valuePath: 'lastSeenLabel', cellComponent: 'admin/table/cell/date-time', width: '210px', resizable: true },
+ {
+ label: '',
+ cellComponent: 'table/cell/dropdown',
+ ddButtonText: false,
+ ddButtonIcon: 'ellipsis-h',
+ ddButtonIconPrefix: 'fas',
+ ddMenuLabel: 'Consumer Actions',
+ cellClassNames: 'overflow-visible',
+ wrapperClass: 'flex items-center justify-end mx-2',
+ sticky: 'right',
+ width: 60,
+ actions: [
+ {
+ label: 'Clear rate-limit window',
+ icon: 'unlock',
+ fn: (consumer) => this.resetConsumer.perform(consumer),
+ },
+ {
+ label: 'View organization',
+ icon: 'building',
+ fn: (consumer) => this.openOrganization(consumer.organization),
+ },
+ {
+ label: 'Manage rate limits',
+ icon: 'gauge',
+ fn: () => this.router.transitionTo('console.admin.rate-limits'),
+ },
+ ],
+ },
+ ];
+
+ constructor() {
+ super(...arguments);
+ this.load.perform();
+ }
+
+ get windowDescription() {
+ return WINDOW_DESCRIPTIONS[this.window];
+ }
+
+ get isMinuteGranularity() {
+ return (this.data?.granularity ?? 'minute') === 'minute';
+ }
+
+ get consumers() {
+ return (this.data?.consumers ?? []).map((consumer) => {
+ const type = CONSUMER_TYPES[consumer.type] ?? { label: consumer.type ?? 'Unknown', icon: 'circle-question' };
+ const isUnlimited = consumer.limit === null || consumer.limit === undefined;
+ const lastSeen = parseDate(consumer.last_seen_at);
+
+ return {
+ ...consumer,
+ label: consumer.label ?? 'Unknown',
+ typeLabel: type.label,
+ typeIcon: type.icon,
+ isUnlimited,
+ isThrottled: consumer.throttled > 0,
+ organization: consumer.company_id
+ ? { id: consumer.company_uuid, uuid: consumer.company_uuid, public_id: consumer.company_id, name: consumer.company_name ?? consumer.company_id }
+ : null,
+ scopeLabel: `/${consumer.scope ?? ''}`,
+ hitsLabel: number(consumer.hits),
+ avgLabel: String(consumer.avg_per_minute ?? 0),
+ peakLabel: consumer.peak_per_minute ? number(consumer.peak_per_minute) : '—',
+ throttledLabel: number(consumer.throttled),
+ limitLabel: isUnlimited ? 'Unlimited' : `${number(consumer.limit)} / ${this.data?.decay_minutes ?? 1}m`,
+ lastSeenLabel: lastSeen ? this.formatDateTime(lastSeen) : null,
+ lastSeenRelative: lastSeen ? formatDistanceToNowStrict(lastSeen, { addSuffix: true }) : null,
+ };
+ });
+ }
+
+ /**
+ * Date and time in the viewer's timezone (their account's, else the browser's), with the
+ * zone named so a screenshot shared across timezones is unambiguous.
+ */
+ formatDateTime(date) {
+ const options = { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZoneName: 'short' };
+ try {
+ return new Intl.DateTimeFormat(undefined, { ...options, timeZone: this.currentUser.timezone }).format(date);
+ } catch {
+ // An unknown zone name throws; fall back to the browser's zone.
+ return new Intl.DateTimeFormat(undefined, options).format(date);
+ }
+ }
+
+ get throttledRate() {
+ const total = this.data?.total_requests ?? 0;
+
+ return total > 0 ? Math.round(((this.data.total_throttled ?? 0) / total) * 10000) / 100 : 0;
+ }
+
+ /**
+ * The busiest bucket in the window, per minute or per hour.
+ */
+ get peak() {
+ const series = this.data?.series ?? [];
+
+ return series.reduce((max, point) => Math.max(max, point.hits), 0);
+ }
+
+ get stats() {
+ const data = this.data ?? {};
+ const unit = this.isMinuteGranularity ? 'min' : 'hour';
+
+ return [
+ { key: 'requests', label: 'Requests', value: number(data.total_requests) },
+ { key: 'throttled', label: 'Throttled (429)', value: number(data.total_throttled), hint: `${this.throttledRate}%`, isAlert: (data.total_throttled ?? 0) > 0 },
+ { key: 'peak', label: `Peak / ${unit}`, value: number(this.peak) },
+ { key: 'consumers', label: 'Consumers', value: number(data.consumer_count) },
+ { key: 'limit', label: 'Default limit', value: number(data.default_limit), hint: `/ ${data.decay_minutes ?? 1}m per consumer` },
+ ];
+ }
+
+ /**
+ * One entry per load so the chart is re-created with the new data; <Chart> only draws
+ * when it is inserted.
+ */
+ get charts() {
+ const series = this.data?.series ?? [];
+ if (!series.length) return [];
+
+ const labelFormat = this.isMinuteGranularity ? 'HH:mm' : this.window > 1440 ? 'EEE d, HH:mm' : 'HH:mm';
+ const titleFormat = this.isMinuteGranularity ? 'EEE d MMM, HH:mm' : 'EEE d MMM, HH:00';
+ const dates = series.map((point) => parseDate(point.bucket));
+ const unit = this.isMinuteGranularity ? 'minute' : 'hour';
+
+ return [
+ {
+ labels: dates.map((date, index) => (date ? format(date, labelFormat) : String(index))),
+ datasets: [
+ {
+ label: 'Requests',
+ data: series.map((point) => point.hits),
+ borderColor: '#3b82f6',
+ backgroundColor: 'rgba(59, 130, 246, 0.15)',
+ fill: true,
+ tension: 0.3,
+ pointRadius: 0,
+ pointHoverRadius: 4,
+ borderWidth: 2,
+ },
+ {
+ label: 'Throttled (429)',
+ data: series.map((point) => point.throttled),
+ borderColor: '#f43f5e',
+ backgroundColor: 'rgba(244, 63, 94, 0.15)',
+ fill: true,
+ tension: 0.3,
+ pointRadius: 0,
+ pointHoverRadius: 4,
+ borderWidth: 2,
+ },
+ ],
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ interaction: { mode: 'index', intersect: false },
+ plugins: {
+ legend: { display: true, position: 'top', align: 'end', labels: { boxWidth: 10, boxHeight: 10, font: { size: 11 } } },
+ tooltip: {
+ callbacks: {
+ title: (items) => {
+ const date = dates[items[0]?.dataIndex];
+ return date ? format(date, titleFormat) : '';
+ },
+ label: (item) => `${item.dataset.label}: ${number(item.parsed.y)} / ${unit}`,
+ },
+ },
+ },
+ scales: {
+ x: { grid: { display: false }, ticks: { maxTicksLimit: 8, maxRotation: 0, font: { size: 10 } } },
+ y: {
+ beginAtZero: true,
+ ticks: { precision: 0, font: { size: 10 } },
+ title: { display: true, text: `Requests / ${unit}`, font: { size: 10 } },
+ },
+ },
+ },
+ },
+ ];
+ }
+
+ @task({ restartable: true }) *load() {
+ try {
+ this.data = yield this.fetch.get('rate-limits/consumers', { window: this.window, sort: this.sort, limit: 100 });
+ } catch (error) {
+ this.notifications.serverError(error);
+ }
+ }
+
+ @task *resetConsumer(consumer) {
+ try {
+ yield this.fetch.post(`rate-limits/consumers/${consumer.signature}/reset`);
+ this.notifications.success(`Rate limit window cleared for ${consumer.label ?? 'consumer'}.`);
+ } catch (error) {
+ this.notifications.serverError(error);
+ }
+ }
+
+ @action setWindow(option) {
+ this.window = option.value;
+ this.load.perform();
+ }
+
+ @action setSort(sort) {
+ this.sort = sort;
+ this.load.perform();
+ }
+
+ @action openOrganization(organization) {
+ if (!organization?.public_id) return;
+ this.router.transitionTo('console.admin.organizations.details', organization.public_id);
+ }
+}
diff --git a/console/app/components/admin/rate-limits.hbs b/console/app/components/admin/rate-limits.hbs
new file mode 100644
index 00000000..299312b6
--- /dev/null
+++ b/console/app/components/admin/rate-limits.hbs
@@ -0,0 +1,94 @@
+<div class="space-y-6" ...attributes>
+ <ContentPanel @title="API Rate Limiting" @open={{true}} @wrapperClass="bordered-classic">
+ <p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
+ Limits apply to each API consumer separately (every API key, access token, or anonymous client address), so a single busy integration is throttled on its own without affecting
+ anyone else.
+ </p>
+
+ <InputGroup @name="Rate limiting" @helpText="When disabled, no API request is ever rejected with 429. Only disable this for load testing.">
+ <Toggle @isToggled={{this.enabled}} @onToggle={{this.toggleEnabled}} @label={{if this.enabled "Enabled" "Disabled"}} @disabled={{this.isBusy}} />
+ </InputGroup>
+
+ {{#unless this.enabled}}
+ <div
+ class="mb-4 flex items-center rounded-md border border-yellow-400 bg-yellow-50 px-3 py-2 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-900 dark:text-yellow-100"
+ data-test-disabled-warning
+ >
+ <FaIcon @icon="triangle-exclamation" class="mr-2" />
+ Rate limiting is off: any consumer can send unlimited requests.
+ </div>
+ {{/unless}}
+
+ <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <InputGroup
+ @name="Requests per window"
+ @type="number"
+ @value={{this.maxAttempts}}
+ @helpText={{concat "Maximum requests each consumer may send per window. Environment default: " this.defaults.max_attempts}}
+ disabled={{this.isBusy}}
+ data-test-max-attempts
+ />
+ <InputGroup
+ @name="Window (minutes)"
+ @type="number"
+ @value={{this.decayMinutes}}
+ @helpText={{concat "Length of the rate-limit window. Environment default: " this.defaults.decay_minutes}}
+ disabled={{this.isBusy}}
+ data-test-decay-minutes
+ />
+ </div>
+
+ <InputGroup @name="Track API consumers" @helpText="Count requests per consumer for the API Consumers view. Requires Redis.">
+ <Toggle @isToggled={{this.trackConsumers}} @onToggle={{this.toggleTrackConsumers}} @label={{if this.trackConsumers "Tracking" "Not tracking"}} @disabled={{this.isBusy}} />
+ </InputGroup>
+
+ {{#if this.unlimitedKeys}}
+ <p class="text-xs text-gray-500 dark:text-gray-400" data-test-unlimited-keys>
+ {{this.unlimitedKeys}}
+ API key(s) bypass rate limiting via THROTTLE_UNLIMITED_API_KEYS.
+ </p>
+ {{/if}}
+ </ContentPanel>
+
+ {{! Flush body: the overrides table spans the panel edge to edge; text and the picker pad themselves. }}
+ <ContentPanel @title="Organization Overrides" @open={{true}} @wrapperClass="bordered-classic" @panelBodyClass="p-0i" @panelBodyWrapperClass="p-0i">
+ <p class="px-4 pt-4 text-sm text-gray-600 dark:text-gray-400">
+ Give an organization's consumers a different limit, or lift the limit entirely, for high-volume integrations.
+ </p>
+
+ {{! No @disabled: ModelSelect reads it once, in its constructor, so binding it to the
+ initial load left the picker disabled for good. }}
+ <div class="px-4 py-4">
+ <InputGroup @name="Add organization" @wrapperClass="mb-0">
+ <ModelSelect
+ @modelName="company"
+ @selectedModel={{this.companyToAdd}}
+ @placeholder="Search organizations"
+ @triggerClass="form-select form-input"
+ @infiniteScroll={{false}}
+ @renderInPlace={{true}}
+ @onChange={{this.addOverride}}
+ @query={{hash view="admin" sort="name"}}
+ as |company|
+ >
+ <SelectOption::Company @option={{company}} />
+ </ModelSelect>
+ </InputGroup>
+ </div>
+
+ {{#if this.overrides.length}}
+ <div class="border-t border-gray-200 dark:border-gray-700" data-test-overrides-table>
+ <Table @rows={{this.overrides}} @columns={{this.overrideColumns}} />
+ </div>
+ {{/if}}
+ </ContentPanel>
+</div>
+
+<EmberWormhole @to="next-view-section-subheader-actions">
+ <div class="flex items-center space-x-2">
+ {{#if this.differsFromDefaults}}
+ <Button @size="sm" @icon="rotate-left" @text="Reset to Defaults" @onClick={{perform this.reset}} @disabled={{this.isBusy}} @isLoading={{this.reset.isRunning}} data-test-reset />
+ {{/if}}
+ <Button @type="primary" @size="sm" @icon="save" @text="Save Changes" @onClick={{perform this.save}} @disabled={{this.isBusy}} @isLoading={{this.save.isRunning}} data-test-save />
+ </div>
+</EmberWormhole>
\ No newline at end of file
diff --git a/console/app/components/admin/rate-limits.js b/console/app/components/admin/rate-limits.js
new file mode 100644
index 00000000..987b22c6
--- /dev/null
+++ b/console/app/components/admin/rate-limits.js
@@ -0,0 +1,225 @@
+import Component from '@glimmer/component';
+import { inject as service } from '@ember/service';
+import { tracked } from '@glimmer/tracking';
+import { action } from '@ember/object';
+import { task } from 'ember-concurrency';
+
+/**
+ * One organization override. Edited in place — its fields are tracked — so typing in the
+ * table's inputs does not replace the row object and re-render (and blur) the input.
+ */
+export class RateLimitOverride {
+ @tracked unlimited;
+ @tracked max_attempts;
+ @tracked note;
+
+ constructor({ company_uuid, company_id = null, company_name = null, unlimited = false, max_attempts = null, note = '' }) {
+ this.company_uuid = company_uuid;
+ this.company_id = company_id;
+ this.company_name = company_name;
+ this.unlimited = unlimited;
+ this.max_attempts = max_attempts;
+ this.note = note;
+ }
+
+ /** The organization, shaped for the table's identity cell. */
+ get organization() {
+ return { id: this.company_uuid, uuid: this.company_uuid, public_id: this.company_id, name: this.company_name ?? this.company_uuid };
+ }
+}
+
+/**
+ * System-wide API rate limits and per-organization overrides.
+ *
+ * Limits apply per API consumer (each API key, access token, or anonymous client IP),
+ * never platform-wide, so one busy integration is throttled on its own. The environment
+ * (THROTTLE_* variables) supplies the defaults; saving here overrides them until reset.
+ */
+export default class AdminRateLimitsComponent extends Component {
+ @service fetch;
+ @service notifications;
+ @service router;
+
+ @tracked enabled = true;
+ @tracked maxAttempts = 120;
+ @tracked decayMinutes = 1;
+ @tracked trackConsumers = true;
+ @tracked overrides = [];
+ @tracked defaults = {};
+ @tracked unlimitedKeys = 0;
+ @tracked companyToAdd = null;
+
+ overrideColumns = [
+ {
+ label: 'Organization',
+ valuePath: 'organization',
+ cellComponent: 'table/cell/identity',
+ resourceType: 'company',
+ resourcePath: 'organization',
+ labelPath: 'name',
+ popover: false,
+ hideBadges: true,
+ onClick: this.openOrganization,
+ width: '240px',
+ resizable: true,
+ },
+ { label: 'Unlimited', valuePath: 'unlimited', cellComponent: 'admin/table/cell/override-unlimited', onToggle: this.updateOverride, width: '100px' },
+ {
+ label: 'Requests / window',
+ valuePath: 'max_attempts',
+ cellComponent: 'admin/table/cell/override-input',
+ inputType: 'number',
+ inputKey: 'max_attempts',
+ onInput: this.updateOverrideInput,
+ width: '150px',
+ },
+ {
+ label: 'Note',
+ valuePath: 'note',
+ cellComponent: 'admin/table/cell/override-input',
+ inputType: 'text',
+ inputKey: 'note',
+ placeholder: 'Why this override exists',
+ onInput: this.updateOverrideInput,
+ width: '260px',
+ resizable: true,
+ },
+ {
+ label: '',
+ cellComponent: 'table/cell/dropdown',
+ ddButtonText: false,
+ ddButtonIcon: 'ellipsis-h',
+ ddButtonIconPrefix: 'fas',
+ ddMenuLabel: 'Override Actions',
+ cellClassNames: 'overflow-visible',
+ wrapperClass: 'flex items-center justify-end mx-2',
+ sticky: 'right',
+ width: 60,
+ actions: [
+ { label: 'View organization', icon: 'building', fn: (override) => this.openOrganization(override.organization) },
+ { label: 'Remove override', icon: 'trash', fn: (override) => this.removeOverride(override) },
+ ],
+ },
+ ];
+
+ constructor() {
+ super(...arguments);
+ this.load.perform();
+ }
+
+ get isBusy() {
+ return this.load.isRunning || this.save.isRunning || this.reset.isRunning;
+ }
+
+ get differsFromDefaults() {
+ const defaults = this.defaults ?? {};
+
+ return (
+ this.enabled !== defaults.enabled ||
+ Number(this.maxAttempts) !== defaults.max_attempts ||
+ Number(this.decayMinutes) !== defaults.decay_minutes ||
+ this.trackConsumers !== defaults.track_consumers ||
+ this.overrides.length > 0
+ );
+ }
+
+ @task *load() {
+ try {
+ const response = yield this.fetch.get('rate-limits/settings');
+ this.apply(response);
+ } catch (error) {
+ this.notifications.serverError(error);
+ }
+ }
+
+ @task *save() {
+ try {
+ const response = yield this.fetch.post('rate-limits/settings', this.payload());
+ this.apply(response);
+ this.notifications.success('Rate limit settings saved.');
+ } catch (error) {
+ this.notifications.serverError(error);
+ }
+ }
+
+ @task *reset() {
+ try {
+ const response = yield this.fetch.delete('rate-limits/settings');
+ this.apply(response);
+ this.notifications.success('Rate limits reset to the environment defaults.');
+ } catch (error) {
+ this.notifications.serverError(error);
+ }
+ }
+
+ apply(response = {}) {
+ const settings = response.settings ?? {};
+
+ this.enabled = settings.enabled ?? true;
+ this.maxAttempts = settings.max_attempts ?? 120;
+ this.decayMinutes = settings.decay_minutes ?? 1;
+ this.trackConsumers = settings.track_consumers ?? true;
+ this.overrides = (settings.overrides ?? []).map((override) => new RateLimitOverride(override));
+ this.defaults = response.defaults ?? {};
+ this.unlimitedKeys = response.unlimited_keys ?? 0;
+ }
+
+ payload() {
+ return {
+ enabled: this.enabled,
+ max_attempts: Number(this.maxAttempts),
+ decay_minutes: Number(this.decayMinutes),
+ track_consumers: this.trackConsumers,
+ overrides: this.overrides.map((override) => ({
+ company_uuid: override.company_uuid,
+ unlimited: Boolean(override.unlimited),
+ max_attempts: override.unlimited || override.max_attempts === '' || override.max_attempts === null ? null : Number(override.max_attempts),
+ note: override.note ?? '',
+ })),
+ };
+ }
+
+ @action toggleEnabled(enabled) {
+ this.enabled = enabled;
+ }
+
+ @action toggleTrackConsumers(trackConsumers) {
+ this.trackConsumers = trackConsumers;
+ }
+
+ @action addOverride(company) {
+ const companyUuid = company?.uuid ?? company?.id;
+ this.companyToAdd = null;
+
+ if (!companyUuid || this.overrides.some((override) => override.company_uuid === companyUuid)) {
+ return;
+ }
+
+ this.overrides = [
+ ...this.overrides,
+ new RateLimitOverride({
+ company_uuid: companyUuid,
+ company_id: company.public_id,
+ company_name: company.name,
+ max_attempts: Number(this.maxAttempts) * 2,
+ }),
+ ];
+ }
+
+ @action updateOverride(override, key, value) {
+ override[key] = value;
+ }
+
+ @action updateOverrideInput(override, key, event) {
+ this.updateOverride(override, key, event.target.value);
+ }
+
+ @action removeOverride(override) {
+ this.overrides = this.overrides.filter((existing) => existing !== override);
+ }
+
+ @action openOrganization(organization) {
+ if (!organization?.public_id) return;
+ this.router.transitionTo('console.admin.organizations.details', organization.public_id);
+ }
+}
diff --git a/console/app/components/admin/table/cell/api-consumer.hbs b/console/app/components/admin/table/cell/api-consumer.hbs
new file mode 100644
index 00000000..b40199f3
--- /dev/null
+++ b/console/app/components/admin/table/cell/api-consumer.hbs
@@ -0,0 +1,28 @@
+{{! An identity cell for an API consumer: type icon, name, then the masked key / token and client address. }}
+<div class="flex min-w-0 items-center gap-2 py-0.5" data-test-api-consumer-cell>
+ <div
+ class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full border shadow-sm
+ {{if
+ @row.isThrottled
+ 'border-rose-200 bg-rose-50 text-rose-600 dark:border-rose-800 dark:bg-rose-900/40 dark:text-rose-300'
+ 'border-gray-200 bg-gray-100 text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400'
+ }}"
+ title={{@row.typeLabel}}
+ >
+ <FaIcon @icon={{@row.typeIcon}} @size="xs" />
+ </div>
+ <div class="min-w-0">
+ <div class="flex min-w-0 items-center gap-1.5">
+ <span class="truncate text-sm leading-4 text-gray-900 dark:text-gray-100" data-test-api-consumer-label>{{@row.label}}</span>
+ <span class="inline-flex flex-shrink-0 items-center rounded-lg bg-gray-200 px-1 text-[10px] leading-4 text-gray-700 dark:bg-gray-700 dark:text-gray-300">{{@row.typeLabel}}</span>
+ {{#if @row.test_mode}}
+ <span class="inline-flex flex-shrink-0 items-center rounded-lg bg-amber-100 px-1 text-[10px] leading-4 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200">test</span>
+ {{/if}}
+ </div>
+ {{#if (or @row.detail @row.ip)}}
+ <div class="mt-0.5 truncate font-mono text-[11px] leading-4 text-gray-500 dark:text-gray-400" data-test-api-consumer-detail>
+ {{@row.detail}}{{#if (and @row.detail @row.ip)}} · {{/if}}{{@row.ip}}
+ </div>
+ {{/if}}
+ </div>
+</div>
\ No newline at end of file
diff --git a/console/app/components/admin/table/cell/date-time.hbs b/console/app/components/admin/table/cell/date-time.hbs
new file mode 100644
index 00000000..6b23bd08
--- /dev/null
+++ b/console/app/components/admin/table/cell/date-time.hbs
@@ -0,0 +1,10 @@
+{{#if @value}}
+ <div class="leading-4" data-test-date-time-cell>
+ <div class="whitespace-nowrap text-xs tabular-nums text-gray-900 dark:text-gray-100">{{@value}}</div>
+ {{#if @row.lastSeenRelative}}
+ <div class="text-[11px] text-gray-500 dark:text-gray-400">{{@row.lastSeenRelative}}</div>
+ {{/if}}
+ </div>
+{{else}}
+ <span class="text-gray-400">—</span>
+{{/if}}
\ No newline at end of file
diff --git a/console/app/components/admin/table/cell/override-input.hbs b/console/app/components/admin/table/cell/override-input.hbs
new file mode 100644
index 00000000..79ba2ab2
--- /dev/null
+++ b/console/app/components/admin/table/cell/override-input.hbs
@@ -0,0 +1,14 @@
+{{! An editable override field. The row object is edited in place, so the input keeps focus. }}
+{{#if (and (eq @column.inputKey "max_attempts") @row.unlimited)}}
+ <span class="text-xs text-gray-500 dark:text-gray-400" data-test-override-no-limit>No limit</span>
+{{else}}
+ <input
+ type={{@column.inputType}}
+ min={{if (eq @column.inputType "number") "1"}}
+ class="form-input form-input-sm w-full"
+ value={{get @row @column.inputKey}}
+ placeholder={{@column.placeholder}}
+ {{on "input" (fn @column.onInput @row @column.inputKey)}}
+ data-test-override-input={{@column.inputKey}}
+ />
+{{/if}}
\ No newline at end of file
diff --git a/console/app/components/admin/table/cell/override-unlimited.hbs b/console/app/components/admin/table/cell/override-unlimited.hbs
new file mode 100644
index 00000000..55c076ba
--- /dev/null
+++ b/console/app/components/admin/table/cell/override-unlimited.hbs
@@ -0,0 +1 @@
+<Toggle @isToggled={{@row.unlimited}} @onToggle={{fn @column.onToggle @row "unlimited"}} data-test-override-unlimited />
\ No newline at end of file
diff --git a/console/app/components/admin/table/cell/share.hbs b/console/app/components/admin/table/cell/share.hbs
new file mode 100644
index 00000000..59e9747f
--- /dev/null
+++ b/console/app/components/admin/table/cell/share.hbs
@@ -0,0 +1,7 @@
+{{! Share of all requests in the window, as a bar and a percentage. }}
+<div class="flex items-center gap-2" data-test-share-cell>
+ <div class="h-1.5 w-14 flex-shrink-0 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700">
+ <div class="h-full rounded-full bg-blue-500" style={{html-safe (concat "width: " (or @value 0) "%")}}></div>
+ </div>
+ <span class="text-xs tabular-nums text-gray-700 dark:text-gray-300">{{or @value 0}}%</span>
+</div>
\ No newline at end of file
diff --git a/console/app/components/admin/table/cell/throttled.hbs b/console/app/components/admin/table/cell/throttled.hbs
new file mode 100644
index 00000000..f5e44827
--- /dev/null
+++ b/console/app/components/admin/table/cell/throttled.hbs
@@ -0,0 +1,8 @@
+{{#if @row.isThrottled}}
+ <span class="inline-flex items-center gap-1 rounded-lg bg-rose-100 px-1.5 text-xs font-semibold leading-5 text-rose-700 dark:bg-rose-900/40 dark:text-rose-200" data-test-throttled-cell>
+ <FaIcon @icon="ban" @size="xs" />
+ {{@value}}
+ </span>
+{{else}}
+ <span class="text-gray-400 dark:text-gray-500" data-test-throttled-cell>0</span>
+{{/if}}
\ No newline at end of file
diff --git a/console/app/controllers/console/admin.js b/console/app/controllers/console/admin.js
index d0f25c7d..fe054fc5 100644
--- a/console/app/controllers/console/admin.js
+++ b/console/app/controllers/console/admin.js
@@ -8,7 +8,14 @@ export default class ConsoleAdminController extends Controller {
@service intl;
get navigationItems() {
- return [...this.coreNavigationItems, ...this.registryNavigationItems, ...this.registryPanelItems, this.authConfigNavigationItem, this.systemConfigNavigationItem];
+ return [
+ ...this.coreNavigationItems,
+ ...this.registryNavigationItems,
+ ...this.registryPanelItems,
+ this.apiTrafficNavigationItem,
+ this.authConfigNavigationItem,
+ this.systemConfigNavigationItem,
+ ];
}
get coreNavigationItems() {
@@ -68,6 +75,35 @@ export default class ConsoleAdminController extends Controller {
});
}
+ /**
+ * Who is calling the public API and how hard, and the limits that keep one busy
+ * consumer from starving the rest of the platform.
+ */
+ get apiTrafficNavigationItem() {
+ return {
+ label: 'API Traffic',
+ description: 'Monitor API consumers and configure rate limiting.',
+ icon: 'gauge-high',
+ keywords: ['api', 'traffic', 'rate limit', 'throttle', 'requests'],
+ children: [
+ {
+ label: 'API Consumers',
+ description: 'See which API keys, users and addresses drive traffic or are being throttled.',
+ icon: 'chart-column',
+ route: 'console.admin.api-consumers',
+ keywords: ['api', 'consumers', 'usage', 'requests', 'throttled', '429'],
+ },
+ {
+ label: 'Rate Limits',
+ description: 'Configure API rate limits and per-organization overrides.',
+ icon: 'gauge',
+ route: 'console.admin.rate-limits',
+ keywords: ['rate limit', 'throttle', 'requests per minute', '429', 'overrides'],
+ },
+ ],
+ };
+ }
+
/**
* How people sign in — kept apart from System Config, which is infrastructure
* (mail, storage, queues). Grouping only affects the sidebar: each child keeps its
diff --git a/console/app/routes/console/admin/api-consumers.js b/console/app/routes/console/admin/api-consumers.js
new file mode 100644
index 00000000..82d5440c
--- /dev/null
+++ b/console/app/routes/console/admin/api-consumers.js
@@ -0,0 +1,3 @@
+import Route from '@ember/routing/route';
+
+export default class ConsoleAdminApiConsumersRoute extends Route {}
diff --git a/console/app/routes/console/admin/rate-limits.js b/console/app/routes/console/admin/rate-limits.js
new file mode 100644
index 00000000..5b03480a
--- /dev/null
+++ b/console/app/routes/console/admin/rate-limits.js
@@ -0,0 +1,3 @@
+import Route from '@ember/routing/route';
+
+export default class ConsoleAdminRateLimitsRoute extends Route {}
diff --git a/console/app/templates/console/admin/api-consumers.hbs b/console/app/templates/console/admin/api-consumers.hbs
new file mode 100644
index 00000000..eb37ca4e
--- /dev/null
+++ b/console/app/templates/console/admin/api-consumers.hbs
@@ -0,0 +1,7 @@
+{{page-title "API Consumers"}}
+<Layout::Section::Header @title="API Consumers" />
+
+<Layout::Section::Body class="overflow-y-scroll h-full">
+ <Admin::ApiConsumers />
+ <Spacer @height="300px" />
+</Layout::Section::Body>
\ No newline at end of file
diff --git a/console/app/templates/console/admin/rate-limits.hbs b/console/app/templates/console/admin/rate-limits.hbs
new file mode 100644
index 00000000..3f7105bf
--- /dev/null
+++ b/console/app/templates/console/admin/rate-limits.hbs
@@ -0,0 +1,11 @@
+{{page-title "Rate Limits"}}
+<Layout::Section::Header @title="Rate Limits" />
+
+<Layout::Section::Body class="overflow-y-scroll h-full">
+ <div class="container mx-auto h-screen">
+ <div class="max-w-4xl my-10 mx-auto space-y-6">
+ <Admin::RateLimits />
+ </div>
+ </div>
+ <Spacer @height="300px" />
+</Layout::Section::Body>
\ No newline at end of file
diff --git a/console/package.json b/console/package.json
index 975bf4c9..1b95953d 100644
--- a/console/package.json
+++ b/console/package.json
@@ -1,6 +1,6 @@
{
"name": "@fleetbase/console",
- "version": "0.7.65",
+ "version": "0.7.66",
"private": true,
"description": "Modular logistics and supply chain operating system (LSOS)",
"repository": "https://github.com/fleetbase/fleetbase",
@@ -46,7 +46,7 @@
"@fleetbase/leaflet-routing-machine": "^3.2.17",
"@fleetbase/ledger-engine": "^0.0.11",
"@fleetbase/registry-bridge-engine": "^0.1.10",
- "@fleetbase/storefront-engine": "^0.4.22",
+ "@fleetbase/storefront-engine": "^0.4.23",
"@fleetbase/valhalla-engine": "^0.0.4",
"@fleetbase/vroom-engine": "^0.0.4",
"@formatjs/intl-datetimeformat": "^6.18.2",
diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yaml
index a9436a58..9da95582 100644
--- a/console/pnpm-lock.yaml
+++ b/console/pnpm-lock.yaml
@@ -50,8 +50,8 @@ importers:
specifier: ^0.1.10
version: 0.1.10(bffd95f1ee8fa5c6dc085f568b2e0221)
'@fleetbase/storefront-engine':
- specifier: ^0.4.22
- version: 0.4.22(bffd95f1ee8fa5c6dc085f568b2e0221)
+ specifier: ^0.4.23
+ version: 0.4.23(bffd95f1ee8fa5c6dc085f568b2e0221)
'@fleetbase/valhalla-engine':
specifier: ^0.0.4
version: 0.0.4(bffd95f1ee8fa5c6dc085f568b2e0221)
@@ -1617,8 +1617,8 @@ packages:
peerDependencies:
ember-engines: ^0.9.0
- '@fleetbase/[email protected]':
- resolution: {integrity: sha512-ZsDa1NiN55HEQVSpzbJbKwIHqJWR//sxeZ7TAfDxvcRsKIJOcpOoNjmYxZul/eIPFtQE14EBA/1fE7/U+yjz4w==}
+ '@fleetbase/[email protected]':
+ resolution: {integrity: sha512-VMYT9GBgypjbahtzrFSoCAmLdaVO4mgJD4tyRLuPoWaS7ULMjmmDWr6nSiZPz+oDh3luMXex+k5NPkLYKuaiMg==}
engines: {node: '>= 18'}
peerDependencies:
ember-engines: ^0.9.0
@@ -11494,7 +11494,7 @@ snapshots:
- webpack-command
- yaml
- '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':
+ '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':
dependencies:
'@babel/core': 7.29.7
diff --git a/console/pnpm-workspace.yaml b/console/pnpm-workspace.yaml
index 34eae96d..c108045e 100644
--- a/console/pnpm-workspace.yaml
+++ b/console/pnpm-workspace.yaml
@@ -16,9 +16,4 @@ allowBuilds:
core-js: false
fsevents: false
minimumReleaseAgeExclude:
- - '@fleetbase/[email protected]'
- - '@fleetbase/[email protected]'
- - '@fleetbase/[email protected]'
- - '@fleetbase/[email protected]'
- - '@fleetbase/[email protected]'
- - '@fleetbase/[email protected]'
+ - '@fleetbase/[email protected]'
diff --git a/console/router.map.js b/console/router.map.js
index e709f6dd..481f6b70 100644
--- a/console/router.map.js
+++ b/console/router.map.js
@@ -57,6 +57,8 @@ Router.map(function () {
this.route('two-fa-settings');
this.route('oauth-settings');
this.route('platform-api-token');
+ this.route('api-consumers');
+ this.route('rate-limits');
this.route('virtual', { path: '/:slug' });
this.route('organizations', function () {
this.route('index', { path: '/' });
diff --git a/console/tests/integration/components/admin/api-consumers-test.js b/console/tests/integration/components/admin/api-consumers-test.js
new file mode 100644
index 00000000..a2912265
--- /dev/null
+++ b/console/tests/integration/components/admin/api-consumers-test.js
@@ -0,0 +1,293 @@
+import { module, test } from 'qunit';
+import { setupRenderingTest } from '@fleetbase/console/tests/helpers';
+import { render, click } from '@ember/test-helpers';
+import { hbs } from 'ember-cli-htmlbars';
+import Service from '@ember/service';
+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';
+import AdminApiConsumersComponent from '@fleetbase/console/components/admin/api-consumers';
+
+/**
+ * Lets the task's fetch (a native promise, which settled() does not track) resolve.
+ */
+function flush() {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const KEY = 'a'.repeat(40);
+// Relative to now: a fixed timestamp reads "in 26 minutes" instead of "... ago" when the
+// suite happens to run before it.
+const LAST_SEEN = new Date(Date.now() - 5 * 60 * 1000);
+// The component's format, built independently so assertions do not depend on the CI
+// browser's locale.
+const FORMAT = { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZoneName: 'short' };
+const ANON = 'b'.repeat(40);
+
+function metrics(overrides = {}) {
+ return {
+ available: true,
+ tracking: true,
+ window: 15,
+ granularity: 'minute',
+ sort: 'hits',
+ total_requests: 400,
+ total_throttled: 40,
+ consumer_count: 4,
+ default_limit: 120,
+ decay_minutes: 1,
+ consumers: [
+ {
+ signature: KEY,
+ type: 'api_key',
+ label: 'Pharma integration',
+ detail: 'flb_live_abc…',
+ test_mode: true,
+ company_uuid: 'company-uuid',
+ company_id: 'company_abc',
+ company_name: 'Acme Pharma',
+ scope: 'v1',
+ ip: '41.0.0.1',
+ limit: 120,
+ hits: 360,
+ throttled: 40,
+ share: 90,
+ avg_per_minute: 24,
+ peak_per_minute: 160,
+ last_seen_at: LAST_SEEN.toISOString(),
+ },
+ { signature: ANON, type: 'ip', label: '197.0.0.3', scope: 'int', limit: null, hits: 30, throttled: 0, share: 7.5, avg_per_minute: 2, last_seen_at: 'not a date' },
+ { signature: 'c'.repeat(40), type: 'webhook', company_id: 'company_def', scope: 'v1', hits: 10, throttled: 0, share: 2.5 },
+ { signature: 'e'.repeat(40), limit: 60, hits: 0, throttled: 0, share: 0 },
+ ],
+ series: [
+ { bucket: '2026-09-29T09:59:00+00:00', hits: 0, throttled: 0 },
+ { bucket: '2026-09-29T10:00:00+00:00', hits: 400, throttled: 40 },
+ ],
+ ...overrides,
+ };
+}
+
+module('Integration | Component | admin/api-consumers', function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ const context = this;
+ this.requests = [];
+ this.transitions = [];
+ this.response = metrics();
+ this.fail = {};
+
+ class FetchStub extends Service {
+ get(path, query) {
+ context.requests.push({ method: 'get', path, query });
+ return context.fail.get ? Promise.reject(new Error('get failed')) : Promise.resolve(context.response);
+ }
+ post(path) {
+ context.requests.push({ method: 'post', path });
+ return context.fail.post ? Promise.reject(new Error('post failed')) : Promise.resolve({ status: 'OK' });
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ errors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error) {
+ this.errors.push(error.message);
+ }
+ }
+
+ // The table reads the locale; set it before render so the first read does not
+ // update tracked state mid-render.
+ this.owner.lookup('service:intl').setLocale('en-us');
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.notifications = () => this.owner.lookup('service:notifications');
+
+ const captured = captureComponent(this.owner, 'admin/api-consumers', AdminApiConsumersComponent);
+ this.build = async () => {
+ await render(hbs`
+ <div id="next-view-section-subheader-actions"></div>
+ <Admin::ApiConsumers />
+ `);
+ await flush();
+ const component = captured.instance;
+ // Framework-provided services are patched on the instance, not re-registered:
+ // they resolve before a test's beforeEach can win the race.
+ Object.defineProperty(component, 'router', {
+ configurable: true,
+ value: { transitionTo: (...args) => context.transitions.push(args) },
+ });
+ Object.defineProperty(component, 'currentUser', { configurable: true, value: { timezone: 'UTC' } });
+ return component;
+ };
+ });
+
+ test('it shows compact stats, a labelled timeline and a consumer table', async function (assert) {
+ const component = await this.build();
+
+ assert.deepEqual(this.requests[0], { method: 'get', path: 'rate-limits/consumers', query: { window: 15, sort: 'hits', limit: 100 } });
+ assert.dom('#next-view-section-subheader-actions [data-test-window="15"]').hasAttribute('aria-pressed', 'true', 'controls live in the header');
+ assert.dom('[data-test-stat="requests"]').containsText('400');
+ assert.dom('[data-test-stat="throttled"]').containsText('10%');
+ assert.dom('[data-test-stat="peak"]').containsText('Peak / min');
+ assert.dom('[data-test-stat="peak"]').containsText('400');
+ assert.dom('[data-test-stat="consumers"]').containsText('4');
+ assert.dom('[data-test-stat="limit"]').containsText('/ 1m per consumer');
+ assert.dom('[data-test-timeline]').containsText('Requests over the last 15 minutes');
+ assert.dom('[data-test-timeline] canvas').exists();
+ assert.dom('[data-test-api-consumer-label]').exists({ count: 4 });
+ assert.dom('[data-test-consumers-table]').containsText('Pharma integration');
+ assert.dom('[data-test-consumers-table]').containsText('Acme Pharma');
+ assert.dom('[data-test-api-consumer-detail]').containsText('flb_live_abc… · 41.0.0.1');
+ assert.dom('[data-test-throttled-cell]').exists();
+ assert.dom('[data-test-share-cell]').exists();
+ assert.dom('[data-test-date-time-cell]').exists();
+ assert.dom('[data-test-unavailable]').doesNotExist();
+ assert.dom('[data-test-not-tracking]').doesNotExist();
+ assert.strictEqual(component.windowDescription, 'last 15 minutes');
+ });
+
+ test('it maps consumers to display rows', async function (assert) {
+ const component = await this.build();
+ const [key, anon, webhook, bare] = component.consumers;
+
+ assert.deepEqual([key.typeLabel, key.typeIcon, key.isUnlimited, key.isThrottled], ['API key', 'key', false, true]);
+ assert.deepEqual(key.organization, { id: 'company-uuid', uuid: 'company-uuid', public_id: 'company_abc', name: 'Acme Pharma' });
+ assert.deepEqual([key.scopeLabel, key.hitsLabel, key.avgLabel, key.peakLabel, key.throttledLabel, key.limitLabel], ['/v1', '360', '24', '160', '40', '120 / 1m']);
+ assert.strictEqual(key.lastSeenLabel, new Intl.DateTimeFormat(undefined, { ...FORMAT, timeZone: 'UTC' }).format(LAST_SEEN), 'absolute date and time in the viewer zone');
+ assert.ok(key.lastSeenRelative.endsWith('ago'));
+
+ assert.deepEqual([anon.typeLabel, anon.isUnlimited, anon.organization, anon.limitLabel, anon.peakLabel], ['Anonymous', true, null, 'Unlimited', '—']);
+ assert.deepEqual([anon.lastSeenLabel, anon.lastSeenRelative], [null, null], 'an unparseable timestamp shows nothing');
+
+ assert.deepEqual([webhook.typeLabel, webhook.typeIcon, webhook.avgLabel], ['webhook', 'circle-question', '0']);
+ assert.strictEqual(webhook.organization.name, 'company_def', 'an organization without a name falls back to its id');
+
+ assert.deepEqual([bare.typeLabel, bare.label, bare.scopeLabel, bare.lastSeenLabel], ['Unknown', 'Unknown', '/', null]);
+
+ component.data = { ...metrics(), decay_minutes: undefined };
+ assert.strictEqual(component.consumers[0].limitLabel, '120 / 1m', 'the window defaults to one minute');
+ });
+
+ test('it charts requests with dated tooltips and axis context', async function (assert) {
+ const component = await this.build();
+ const [chart] = component.charts;
+ const { title, label } = chart.options.plugins.tooltip.callbacks;
+
+ assert.deepEqual(
+ chart.datasets.map((dataset) => [dataset.label, dataset.data]),
+ [
+ ['Requests', [0, 400]],
+ ['Throttled (429)', [0, 40]],
+ ]
+ );
+ assert.strictEqual(chart.labels.length, 2);
+ assert.strictEqual(chart.options.scales.y.title.text, 'Requests / minute');
+ assert.ok(title([{ dataIndex: 1 }]).length > 0, 'the tooltip title is the bucket time');
+ assert.strictEqual(title([]), '', 'no item, no title');
+ assert.strictEqual(label({ dataset: { label: 'Requests' }, parsed: { y: 1200 } }), `Requests: ${new Intl.NumberFormat().format(1200)} / minute`);
+
+ component.window = 1440;
+ component.data = metrics({ granularity: 'hour', series: [{ bucket: 'bad', hits: 1, throttled: 0 }] });
+ const [hourly] = component.charts;
+ assert.strictEqual(hourly.options.scales.y.title.text, 'Requests / hour');
+ assert.deepEqual(hourly.labels, ['0'], 'an unparseable bucket is labelled by position');
+ assert.strictEqual(hourly.options.plugins.tooltip.callbacks.title([{ dataIndex: 0 }]), '');
+ assert.strictEqual(component.stats.find((stat) => stat.key === 'peak').label, 'Peak / hour');
+
+ component.window = 10080;
+ component.data = metrics({ granularity: 'hour' });
+ assert.strictEqual(component.charts[0].labels.length, 2, 'the week view labels include the day');
+
+ component.data = metrics({ series: [] });
+ assert.deepEqual(component.charts, []);
+ });
+
+ test('it reloads when the window or sort changes', async function (assert) {
+ const component = await this.build();
+
+ await click('[data-test-window="60"]');
+ assert.deepEqual(this.requests.at(-1).query, { window: 60, sort: 'hits', limit: 100 });
+ assert.strictEqual(component.windowDescription, 'last hour');
+
+ await click('[data-test-sort="throttled"]');
+ assert.deepEqual(this.requests.at(-1).query, { window: 60, sort: 'throttled', limit: 100 });
+
+ await click('[data-test-sort="hits"]');
+ await click('[data-test-refresh]');
+ assert.strictEqual(this.requests.length, 5);
+ });
+
+ test('its row actions clear a window, open the organization and manage limits', async function (assert) {
+ const component = await this.build();
+ const actions = component.columns.at(-1).actions;
+ const [key, anon] = component.consumers;
+
+ await actions[0].fn(key);
+ await component.resetConsumer.perform({ signature: 'd'.repeat(40) });
+ actions[1].fn(key);
+ actions[1].fn(anon);
+ actions[2].fn(key);
+ component.openOrganization(undefined);
+
+ assert.deepEqual(
+ this.requests.filter((request) => request.method === 'post').map((request) => request.path),
+ [`rate-limits/consumers/${KEY}/reset`, `rate-limits/consumers/${'d'.repeat(40)}/reset`]
+ );
+ assert.deepEqual(this.notifications().successes, ['Rate limit window cleared for Pharma integration.', 'Rate limit window cleared for consumer.']);
+ assert.deepEqual(this.transitions, [['console.admin.organizations.details', 'company_abc'], ['console.admin.rate-limits']], 'no organization, no transition');
+ });
+
+ test('it formats times in the viewer timezone and survives an unknown zone', async function (assert) {
+ const component = await this.build();
+ const date = new Date('2026-09-29T10:00:00Z');
+
+ Object.defineProperty(component, 'currentUser', { configurable: true, value: { timezone: 'Asia/Singapore' } });
+ let singapore = null;
+ try {
+ singapore = new Intl.DateTimeFormat(undefined, { ...FORMAT, timeZone: 'Asia/Singapore' }).format(date);
+ } catch {
+ // A browser without that zone's data takes the component's fallback path instead.
+ // (CI's headless Chrome goes further and silently formats named zones as UTC, so
+ // this test checks the zone is passed to Intl, not how the browser renders it.)
+ }
+ assert.strictEqual(component.formatDateTime(date), singapore ?? new Intl.DateTimeFormat(undefined, FORMAT).format(date), 'converted to the account timezone');
+
+ Object.defineProperty(component, 'currentUser', { configurable: true, value: { timezone: 'Not/AZone' } });
+ assert.strictEqual(component.formatDateTime(date), new Intl.DateTimeFormat(undefined, FORMAT).format(date), 'falls back to the browser timezone');
+ });
+
+ test('it reports failures', async function (assert) {
+ this.fail = { get: true, post: true };
+ const component = await this.build();
+
+ await component.resetConsumer.perform({ signature: KEY });
+
+ assert.deepEqual(this.notifications().errors, ['get failed', 'post failed']);
+ assert.strictEqual(component.data, null);
+ assert.deepEqual(component.consumers, []);
+ assert.deepEqual(component.charts, []);
+ assert.strictEqual(component.throttledRate, 0);
+ assert.strictEqual(component.peak, 0);
+ assert.true(component.isMinuteGranularity, 'minute granularity until data says otherwise');
+ assert.deepEqual(
+ component.stats.map((stat) => stat.value),
+ ['0', '0', '0', '0', '0']
+ );
+ });
+
+ test('it explains when metrics are unavailable or not being tracked', async function (assert) {
+ this.response = metrics({ available: false, tracking: false, consumers: [], series: [], total_requests: 0, total_throttled: undefined });
+ const component = await this.build();
+
+ assert.dom('[data-test-unavailable]').exists();
+ assert.dom('[data-test-not-tracking]').exists();
+ assert.dom('[data-test-empty]').containsText('No API requests in the last 15 minutes');
+ assert.dom('[data-test-timeline]').doesNotExist();
+ assert.strictEqual(component.throttledRate, 0);
+
+ component.data = metrics({ total_throttled: undefined });
+ assert.strictEqual(component.throttledRate, 0, 'a missing throttled count reads as zero');
+ });
+});
diff --git a/console/tests/integration/components/admin/rate-limits-test.js b/console/tests/integration/components/admin/rate-limits-test.js
new file mode 100644
index 00000000..f8ee9955
--- /dev/null
+++ b/console/tests/integration/components/admin/rate-limits-test.js
@@ -0,0 +1,243 @@
+import { module, test } from 'qunit';
+import { setupRenderingTest } from '@fleetbase/console/tests/helpers';
+import { render, click, settled } from '@ember/test-helpers';
+import { hbs } from 'ember-cli-htmlbars';
+import Service from '@ember/service';
+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';
+import AdminRateLimitsComponent, { RateLimitOverride } from '@fleetbase/console/components/admin/rate-limits';
+
+const DEFAULTS = { enabled: true, max_attempts: 120, decay_minutes: 1, track_consumers: true, overrides: [] };
+
+function settingsResponse(settings = {}) {
+ return {
+ settings: { ...DEFAULTS, ...settings },
+ defaults: { ...DEFAULTS },
+ unlimited_keys: 2,
+ };
+}
+
+/**
+ * Lets the task's fetch (a native promise, which settled() does not track) resolve.
+ */
+function flush() {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+module('Integration | Component | admin/rate-limits', function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ const context = this;
+ this.requests = [];
+ this.getResponse = settingsResponse({
+ overrides: [{ company_uuid: 'company-1', company_id: 'company_abc', company_name: 'Acme Pharma', unlimited: false, max_attempts: 600, note: 'bulk import' }],
+ });
+ this.writeResponse = settingsResponse({ max_attempts: 300 });
+ this.fail = {};
+
+ class FetchStub extends Service {
+ request(method, path, payload) {
+ context.requests.push({ method, path, payload });
+ if (context.fail[method]) {
+ return Promise.reject(new Error(`${method} failed`));
+ }
+
+ return Promise.resolve(method === 'get' ? context.getResponse : context.writeResponse);
+ }
+ get(path) {
+ return this.request('get', path);
+ }
+ post(path, payload) {
+ return this.request('post', path, payload);
+ }
+ delete(path) {
+ return this.request('delete', path);
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ errors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error) {
+ this.errors.push(error.message);
+ }
+ }
+
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.notifications = () => this.owner.lookup('service:notifications');
+
+ const captured = captureComponent(this.owner, 'admin/rate-limits', AdminRateLimitsComponent);
+ this.build = async () => {
+ await render(hbs`
+ <div id="next-view-section-subheader-actions"></div>
+ <Admin::RateLimits />
+ `);
+ await flush();
+ const component = captured.instance;
+ // Framework-provided services are patched on the instance, not re-registered.
+ this.transitions = [];
+ Object.defineProperty(component, 'router', {
+ configurable: true,
+ value: { transitionTo: (...args) => this.transitions.push(args) },
+ });
+ return component;
+ };
+ });
+
+ test('it loads the effective settings and lists organization overrides', async function (assert) {
+ const component = await this.build();
+
+ assert.deepEqual(this.requests[0], { method: 'get', path: 'rate-limits/settings', payload: undefined });
+ assert.strictEqual(component.maxAttempts, 120);
+ assert.strictEqual(component.unlimitedKeys, 2);
+ assert.dom('[data-test-overrides-table]').containsText('Acme Pharma', 'overrides render in the table');
+ assert.dom('[data-test-override-input="max_attempts"]').hasValue('600');
+ assert.dom('[data-test-override-input="note"]').hasValue('bulk import');
+ assert.dom('[data-test-override-unlimited]').exists();
+ assert.dom('[data-test-unlimited-keys]').containsText('2');
+ assert.dom('[data-test-disabled-warning]').doesNotExist();
+ assert.dom('#next-view-section-subheader-actions [data-test-save]').exists('save is wormholed to the subheader');
+ assert.dom('[data-test-reset]').exists('an override differs from the defaults, so reset is offered');
+ // ModelSelect reads @disabled once; the picker must not stay disabled after the load.
+ assert.dom('.ember-power-select-trigger').hasAttribute('aria-disabled', 'false', 'the organization picker is usable');
+ });
+
+ test('it saves the settings and overrides as numbers', async function (assert) {
+ const component = await this.build();
+ component.toggleEnabled(false);
+ component.toggleTrackConsumers(false);
+ component.maxAttempts = '250';
+ component.decayMinutes = '2';
+ await settled();
+
+ assert.dom('[data-test-disabled-warning]').exists('disabling warns the admin');
+
+ await click('[data-test-save]');
+ await flush();
+
+ const { method, path, payload } = this.requests.at(-1);
+ assert.strictEqual(method, 'post');
+ assert.strictEqual(path, 'rate-limits/settings');
+ assert.deepEqual(payload, {
+ enabled: false,
+ max_attempts: 250,
+ decay_minutes: 2,
+ track_consumers: false,
+ overrides: [{ company_uuid: 'company-1', unlimited: false, max_attempts: 600, note: 'bulk import' }],
+ });
+ assert.strictEqual(component.maxAttempts, 300, 'the saved response is applied');
+ assert.deepEqual(this.notifications().successes, ['Rate limit settings saved.']);
+ });
+
+ test('it resets to the environment defaults', async function (assert) {
+ this.writeResponse = settingsResponse();
+ const component = await this.build();
+
+ await click('[data-test-reset]');
+ await flush();
+
+ assert.strictEqual(this.requests.at(-1).method, 'delete');
+ assert.strictEqual(this.requests.at(-1).path, 'rate-limits/settings');
+ assert.deepEqual(component.overrides, []);
+ assert.deepEqual(this.notifications().successes, ['Rate limits reset to the environment defaults.']);
+ assert.dom('[data-test-reset]').doesNotExist('nothing left to reset');
+ });
+
+ test('it reports failed loads, saves and resets', async function (assert) {
+ this.fail = { get: true, post: true, delete: true };
+ const component = await this.build();
+
+ await component.save.perform();
+ await component.reset.perform();
+
+ assert.deepEqual(this.notifications().errors, ['get failed', 'post failed', 'delete failed']);
+ });
+
+ test('it adds, edits and removes organization overrides', async function (assert) {
+ const component = await this.build();
+
+ component.addOverride({ uuid: 'company-2', public_id: 'company_def', name: 'Beta Logistics' });
+ component.addOverride({ id: 'company-3', public_id: 'company_ghi', name: 'Gamma Freight' });
+ component.addOverride({ uuid: 'company-2', name: 'Duplicate' });
+ component.addOverride(null);
+ component.addOverride({ name: 'No identifier' });
+
+ assert.deepEqual(
+ component.overrides.map((override) => override.company_uuid),
+ ['company-1', 'company-2', 'company-3'],
+ 'uuid or id identifies the organization; duplicates and blanks are ignored'
+ );
+ assert.strictEqual(component.overrides[1].max_attempts, 240, 'a new override starts at double the default');
+ assert.strictEqual(component.companyToAdd, null);
+
+ const [first, second, third] = component.overrides;
+ component.updateOverride(second, 'unlimited', true);
+ component.updateOverrideInput(third, 'max_attempts', { target: { value: '' } });
+ component.updateOverrideInput(component.overrides[0], 'note', { target: { value: 'renewed' } });
+ component.overrides = [...component.overrides, new RateLimitOverride({ company_uuid: 'company-4', note: null })];
+
+ assert.deepEqual(component.payload().overrides, [
+ { company_uuid: 'company-1', unlimited: false, max_attempts: 600, note: 'renewed' },
+ { company_uuid: 'company-2', unlimited: true, max_attempts: null, note: '' },
+ { company_uuid: 'company-3', unlimited: false, max_attempts: null, note: '' },
+ { company_uuid: 'company-4', unlimited: false, max_attempts: null, note: '' },
+ ]);
+ assert.strictEqual(component.overrides[0], first, 'edits happen in place, so an input keeps focus while typing');
+ assert.deepEqual(component.overrides[3].organization, { id: 'company-4', uuid: 'company-4', public_id: null, name: 'company-4' }, 'an unnamed organization shows its id');
+
+ const [view, remove] = component.overrideColumns.at(-1).actions;
+ view.fn(second);
+ view.fn(component.overrides[3]);
+ assert.deepEqual(this.transitions, [['console.admin.organizations.details', 'company_def']], 'no public id, no transition');
+
+ remove.fn(component.overrides[3]);
+ component.removeOverride(first);
+ await settled();
+
+ assert.deepEqual(
+ component.overrides.map((override) => override.company_uuid),
+ ['company-2', 'company-3']
+ );
+ assert.dom('[data-test-override-no-limit]').exists('an unlimited override shows no limit input');
+ });
+
+ test('it only offers a reset when something differs from the environment', async function (assert) {
+ this.getResponse = settingsResponse();
+ const component = await this.build();
+
+ assert.false(component.differsFromDefaults, 'identical to the defaults');
+
+ component.enabled = false;
+ assert.true(component.differsFromDefaults, 'enabled differs');
+ component.enabled = true;
+ component.maxAttempts = '121';
+ assert.true(component.differsFromDefaults, 'limit differs');
+ component.maxAttempts = '120';
+ component.decayMinutes = 5;
+ assert.true(component.differsFromDefaults, 'window differs');
+ component.decayMinutes = 1;
+ component.trackConsumers = false;
+ assert.true(component.differsFromDefaults, 'tracking differs');
+ component.trackConsumers = true;
+
+ component.defaults = null;
+ assert.true(component.differsFromDefaults, 'with no defaults known every value differs');
+ });
+
+ test('it falls back to safe values for a sparse response', async function (assert) {
+ const component = await this.build();
+
+ component.apply();
+ assert.true(component.enabled);
+ assert.strictEqual(component.maxAttempts, 120);
+ assert.strictEqual(component.decayMinutes, 1);
+ assert.true(component.trackConsumers);
+ assert.deepEqual(component.overrides, []);
+ assert.deepEqual(component.defaults, {});
+ assert.strictEqual(component.unlimitedKeys, 0);
+ assert.false(component.isBusy);
+ });
+});
diff --git a/console/tests/unit/controllers/console/admin-test.js b/console/tests/unit/controllers/console/admin-test.js
index 8ad71512..2f95c108 100644
--- a/console/tests/unit/controllers/console/admin-test.js
+++ b/console/tests/unit/controllers/console/admin-test.js
@@ -237,6 +237,20 @@ module('Unit | Controller | console/admin', function (hooks) {
);
});
+ test('it groups api consumers and rate limits under api traffic, before auth config', function (assert) {
+ const controller = this.owner.lookup('controller:console/admin');
+ const apiTraffic = navItem(controller, 'API Traffic');
+ const labels = controller.navigationItems.map((item) => item.label);
+
+ assert.ok(apiTraffic, 'the group exists');
+ assert.deepEqual(
+ apiTraffic.children.map((item) => item.route),
+ ['console.admin.api-consumers', 'console.admin.rate-limits'],
+ 'visibility first, then the limits'
+ );
+ assert.strictEqual(labels.indexOf('API Traffic') + 1, labels.indexOf('Auth Config'), 'api traffic sits just before auth config');
+ });
+
test('it adds system config as a nested navigator branch', function (assert) {
const controller = this.owner.lookup('controller:console/admin');
const systemConfig = navItem(controller, 'System Config');
diff --git a/console/tests/unit/routes/console/admin/api-consumers-test.js b/console/tests/unit/routes/console/admin/api-consumers-test.js
new file mode 100644
index 00000000..c0ef24c2
--- /dev/null
+++ b/console/tests/unit/routes/console/admin/api-consumers-test.js
@@ -0,0 +1,11 @@
+import { module, test } from 'qunit';
+import { setupTest } from '@fleetbase/console/tests/helpers';
+
+module('Unit | Route | console/admin/api-consumers', function (hooks) {
+ setupTest(hooks);
+
+ test('it exists', function (assert) {
+ let route = this.owner.lookup('route:console/admin/api-consumers');
+ assert.ok(route);
+ });
+});
diff --git a/console/tests/unit/routes/console/admin/rate-limits-test.js b/console/tests/unit/routes/console/admin/rate-limits-test.js
new file mode 100644
index 00000000..130f8cc9
--- /dev/null
+++ b/console/tests/unit/routes/console/admin/rate-limits-test.js
@@ -0,0 +1,11 @@
+import { module, test } from 'qunit';
+import { setupTest } from '@fleetbase/console/tests/helpers';
+
+module('Unit | Route | console/admin/rate-limits', function (hooks) {
+ setupTest(hooks);
+
+ test('it exists', function (assert) {
+ let route = this.owner.lookup('route:console/admin/rate-limits');
+ assert.ok(route);
+ });
+});
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 0ee04de1..346966a4 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -76,7 +76,7 @@ ENV QUEUE_CONNECTION=redis
ENV CADDYFILE_PATH=/fleetbase/Caddyfile
ENV CONSOLE_PATH=/fleetbase/console
ENV OCTANE_SERVER=frankenphp
-ENV FLEETBASE_VERSION=0.7.65
+ENV FLEETBASE_VERSION=0.7.66
# Set environment
ARG ENVIRONMENT=production
diff --git a/packages/core-api b/packages/core-api
index b82d9214..74cc07ce 160000
--- a/packages/core-api
+++ b/packages/core-api
@@ -1 +1 @@
-Subproject commit b82d921425d4578ae42aff855077e76445a05315
+Subproject commit 74cc07ce7a1805405099dfda8a252451a4fbe0f0
diff --git a/packages/storefront b/packages/storefront
index 940c5ae3..6ac5f502 160000
--- a/packages/storefront
+++ b/packages/storefront
@@ -1 +1 @@
-Subproject commit 940c5ae35f9e4b3a6bd2dc53b7e89f1bdcc0ae67
+Subproject commit 6ac5f502e87105d447a5423254ff7956ce788157
diff --git a/scripts/ci/mint-k6-keys.php b/scripts/ci/mint-k6-keys.php
new file mode 100644
index 00000000..20d2e41b
--- /dev/null
+++ b/scripts/ci/mint-k6-keys.php
@@ -0,0 +1,104 @@
+// scripts/ci/mint-k6-keys.php
+//
+// CI helper: mint the three public-API keys the k6 release benchmark needs
+// (tests/k6/api-release.js) against a booted stack.
+//
+// Like mint-api-key.php this is NOT a standalone script. It is base64-encoded and
+// eval()'d inside `php artisan tinker --execute="eval(base64_decode('...'));"`, so it
+// intentionally OMITS the opening <?php tag and uses fully-qualified class names.
+//
+// docker compose exec -T application php artisan tinker \
+// --execute="eval(base64_decode('$(base64 < scripts/ci/mint-k6-keys.php | tr -d '\n')'));"
+//
+// Each role gets its OWN organization, owner and live credential:
+//
+// load — the throughput scenario. The workflow adds this key to
+// THROTTLE_UNLIMITED_API_KEYS after minting, so it measures the API rather
+// than the rate limiter.
+// noisy — the noisy-neighbour scenario's flood. Normal per-key limit; expected to
+// be throttled hard.
+// victim — a different tenant sending a trickle during the flood. Must never be
+// throttled: that is the regression gate for the shared-bucket incident.
+//
+// Separate organizations matter: per-organization overrides (ApiRateLimits) key on
+// company_uuid, and the incident was one tenant starving every other tenant.
+//
+// Idempotent: reruns reuse the same org, user and credential (firstOrCreate on stable
+// names), so a local rerun prints the same keys and does not pile up rows.
+//
+// Output (one per line, parsed by .github/workflows/performance.yml):
+// K6_LOAD_KEY=flb_live_... K6_NOISY_KEY=flb_live_... K6_VICTIM_KEY=flb_live_...
+// K6_RATE_LIMIT=<effective per-key requests/minute, or "unlimited">
+// K6_THROTTLE_ENABLED=true|false
+// K6_MINT_OK=1 (last line; its absence means the snippet aborted)
+// K6_MINT_ERROR: ... (on exception)
+
+try {
+ $roles = [
+ 'load' => ['org' => 'CI k6 Load Org', 'email' => '[email protected]', 'name' => 'CI k6 Load'],
+ 'noisy' => ['org' => 'CI k6 Noisy Org', 'email' => '[email protected]', 'name' => 'CI k6 Noisy'],
+ 'victim' => ['org' => 'CI k6 Victim Org', 'email' => '[email protected]', 'name' => 'CI k6 Victim'],
+ ];
+
+ $keys = [];
+ foreach ($roles as $role => $spec) {
+ $company = \Fleetbase\Models\Company::firstOrCreate(['name' => $spec['org']]);
+
+ $user = \Fleetbase\Models\User::where('email', $spec['email'])->withoutGlobalScopes()->first();
+ if (!$user) {
+ $user = new \Fleetbase\Models\User();
+ $user->name = $spec['name'];
+ $user->email = $spec['email'];
+ $user->company_uuid = $company->uuid;
+ $user->type = 'user';
+ $user->status = 'active';
+ // Never used to log in; random so no guessable password exists on the stack.
+ $user->password = 'CiK6!' . bin2hex(random_bytes(12));
+ $user->save();
+ }
+
+ // The public-API middleware rejects a key whose company has no owner (401).
+ if (empty($company->owner_uuid)) {
+ $company->setOwner($user, true);
+ $company->save();
+ }
+
+ // test_mode=false => flb_live_ key on the default (mysql) connection. The key is
+ // generated by ApiCredentialObserver on insert, hence create-then-fresh().
+ $credential = \Fleetbase\Models\ApiCredential::firstOrCreate(
+ ['company_uuid' => $company->uuid, 'name' => 'CI k6 ' . ucfirst($role) . ' Key'],
+ ['user_uuid' => $user->uuid, 'test_mode' => false]
+ );
+
+ $keys[$role] = $credential->fresh()->key;
+ if (empty($keys[$role])) {
+ throw new \RuntimeException("Credential for role '{$role}' has no key after insert.");
+ }
+ }
+
+ echo PHP_EOL;
+ echo 'K6_LOAD_KEY=' . $keys['load'] . PHP_EOL;
+ echo 'K6_NOISY_KEY=' . $keys['noisy'] . PHP_EOL;
+ echo 'K6_VICTIM_KEY=' . $keys['victim'] . PHP_EOL;
+
+ // Report what the limiter will actually enforce for the noisy tenant, so the k6 run
+ // can size its flood and the report can state the limit it was measured against.
+ // Administrator overrides (system.rate-limits) win over the environment.
+ // ApiRateLimits arrived in core-api 1.6.66; on an older core-api the limits are
+ // environment-only, so read them from config instead of failing the whole run.
+ if (class_exists(\Fleetbase\Support\ApiRateLimits::class)) {
+ $settings = \Fleetbase\Support\ApiRateLimits::settings();
+ $noisyOrg = \Fleetbase\Models\Company::where('name', $roles['noisy']['org'])->value('uuid');
+ $noisyLimit = \Fleetbase\Support\ApiRateLimits::limitFor($noisyOrg, $settings);
+ } else {
+ $settings = ['enabled' => config('api.throttle.enabled', true) !== false];
+ $noisyLimit = (int) config('api.throttle.max_attempts', 120);
+ }
+ echo 'K6_THROTTLE_ENABLED=' . ($settings['enabled'] ? 'true' : 'false') . PHP_EOL;
+ echo 'K6_RATE_LIMIT=' . ($noisyLimit === null ? 'unlimited' : $noisyLimit) . PHP_EOL;
+
+ echo 'K6_MINT_OK=1' . PHP_EOL;
+} catch (\Throwable $e) {
+ echo PHP_EOL . 'K6_MINT_ERROR: ' . get_class($e) . ': ' . $e->getMessage() . PHP_EOL;
+ echo $e->getFile() . ':' . $e->getLine() . PHP_EOL;
+}
diff --git a/tests/k6/README.md b/tests/k6/README.md
new file mode 100644
index 00000000..87914885
--- /dev/null
+++ b/tests/k6/README.md
@@ -0,0 +1,162 @@
+# k6 release benchmark
+
+`api-release.js` produces the API performance report for every release: throughput and
+avg/p50/p90/p95/p99/max latency overall, for reads vs writes, and per endpoint across a
+weighted catalogue of the public API, compared against the previous release. It also runs
+a secondary rate-limit isolation check. CI runs it on every `v*` tag
+(`.github/workflows/performance.yml`), publishes the report to the job summary and the
+`k6-report` artifact, and attaches `performance-report-<tag>.md/.html` and
+`performance-metrics-<tag>.json` to the tag's GitHub Release.
+
+## Release PR gate
+
+Pull requests from `release/v*` (or `dev-v*`) into `main` run the same benchmark, which
+posts the report as a PR comment and can be made a required check. They fail on:
+
+- **Correctness, always:** error rate at or above `MAX_ERROR_RATE`, or a failed rate-limit
+ isolation check.
+- **Latency regression, confirmed:** the aggregate read or write p95 is **more than 35%
+ and more than 150 ms** slower than the previous release's `performance-metrics-<tag>.json`
+ (`PERF_MAX_REGRESSION`, `PERF_MIN_REGRESSION_MS`). A regression is re-measured once in
+ the same job and only fails if the second run agrees. Per-endpoint changes are reported
+ but never gate: with a few hundred requests each they are too noisy.
+
+To ship an intended regression, add the `perf-regression-accepted` label and re-run the
+job. The label never overrides the correctness gate. Tag runs publish the report and do
+not apply the latency gate.
+
+## What it runs
+
+| Phase | Scenario(s) | Key | What it proves |
+|---|---|---|---|
+| `throughput` | `throughput` (ramping arrival rate) | LOAD, listed in `THROTTLE_UNLIMITED_API_KEYS` | The performance report. A weighted catalogue (see `CATALOGUE` in the script): order list/filtered/get/create/update, places and contacts list/get/create/update, drivers and vehicles list/get, fleets, vendors, service areas, service rates, issues and fuel reports. `setup()` probes each endpoint once; ones this install cannot serve are listed as "not measured". The key is unthrottled so it measures the API, not the limiter. |
+| `noisy_neighbour` | `noisy_flood`, `victim`, `public_probe` (constant arrival rate) | NOISY and VICTIM, **different organizations** | One tenant floods create/update well above its per-key limit. Another tenant sends ~1 req/s of reads and writes, and an anonymous client loads a public console route (`GET /int/v1/settings/branding`). |
+
+The phases run one after the other (`PHASE_GAP` apart), so the throughput numbers are not
+skewed by the flood. The victim and the probe start `NOISY_WARMUP` into the flood, when the
+noisy tenant's bucket is already exhausted.
+
+### The isolation gate
+
+The incident: one customer sent ~1 order write per second with one API key and **every**
+consumer on the platform got HTTP 429, because the limiter keyed its buckets on the load
+balancer's IP. Behind a proxy every tenant, key and console visitor shared that one bucket.
+
+The `noisy_neighbour` phase recreates that shape from a single machine (one source IP,
+exactly like traffic behind a load balancer) and requires:
+
+- `victim_throttled == 0`: the other tenant never sees a 429,
+- `public_probe_throttled == 0`: the anonymous console route never sees a 429,
+- `noisy_throttled > 0`: the flooding tenant **is** throttled, so the gate cannot pass
+ just because throttling was off,
+- `noisy_429_missing_retry_after == 0`: every 429 carries `Retry-After`,
+- `victim_requests > 0`, `public_probe_requests > 0`: the bystanders really sent traffic.
+
+With the old IP-keyed limiter the victim and the probe share the noisy bucket and the gate
+fails. `X-RateLimit-*` on 429s is reported but only warns.
+
+### Other thresholds
+
+| Metric | Default | Override |
+|---|---|---|
+| `http_req_failed` (expected noisy 429s excluded) | `rate<0.01` | `MAX_ERROR_RATE` |
+| `http_req_duration{role:load,kind:read}` p95 (report-only unless `ENFORCE_BUDGETS=true`) | `< 800 ms` | `READ_P95_MS` (`READ_P99_MS` adds a p99 gate) |
+| `http_req_duration{role:load,kind:write}` p95 (report-only unless `ENFORCE_BUDGETS=true`) | `< 1500 ms` | `WRITE_P95_MS` (`WRITE_P99_MS` adds a p99 gate) |
+
+In CI the budgets can be tuned without a code change through the repository variables
+`K6_READ_P95_MS`, `K6_WRITE_P95_MS` and `K6_MAX_ERROR_RATE`. CI numbers come from a shared
+GitHub runner that also hosts the whole stack; compare them release to release, not with
+production.
+
+k6 exits `99` when any threshold fails. The workflow publishes the report first and then
+fails the job.
+
+## Running locally
+
+1. Mint the three keys (idempotent: reruns print the same keys):
+
+ ```bash
+ docker compose exec -T application php artisan tinker \
+ --execute="eval(base64_decode('$(base64 < scripts/ci/mint-k6-keys.php | tr -d '\n')'));" \
+ | grep '^K6_' > /tmp/k6-keys.env
+ set -a; . /tmp/k6-keys.env; set +a
+ ```
+
+ This creates the organizations `CI k6 Load Org`, `CI k6 Noisy Org` and `CI k6 Victim Org`,
+ each with an owner and a live key, and also prints `K6_THROTTLE_ENABLED` and
+ `K6_RATE_LIMIT` (the limit the noisy tenant will get).
+
+2. Make the stack match what the phases need:
+
+ - `throughput` needs the LOAD key unthrottled. Add it to `THROTTLE_UNLIMITED_API_KEYS`
+ in `api/.env`, then reload (`php artisan config:cache` first if the config is
+ cached). `setup()` aborts with an explanation if the key still gets
+ `X-RateLimit-Limit`. `api/.env` is a single-file bind mount, so edit it in place;
+ `sed -i` swaps the inode and the container keeps reading the old file.
+ - `noisy_neighbour` needs throttling on (`THROTTLE_ENABLED=true`, or the
+ administrator's rate-limit setting). With throttling off the gate fails on
+ `noisy_throttled`.
+
+3. Run it:
+
+ ```bash
+ k6 run -e BASE_URL=http://localhost:8000 \
+ -e K6_LOAD_KEY=$K6_LOAD_KEY -e K6_NOISY_KEY=$K6_NOISY_KEY -e K6_VICTIM_KEY=$K6_VICTIM_KEY \
+ tests/k6/api-release.js
+ ```
+
+ The dev stack's amd64 image runs under Rosetta on Apple silicon and is far slower than
+ CI. Scale down (`-e THROUGHPUT_PEAK_RATE=3 -e THROUGHPUT_DURATION=60s`) or run one
+ phase (`-e SCENARIOS=noisy_neighbour`).
+
+ Without a local k6: `docker run --rm -i -v "$PWD:/work" -w /work grafana/k6 run -e
+ BASE_URL=http://host.docker.internal:8000 ... tests/k6/api-release.js`.
+
+The report is written to `K6_REPORT_DIR` (default: the current directory). k6 does not
+create directories, so `mkdir -p` a custom one first:
+
+- `summary.json`: raw k6 summary data
+- `report.md`: release, commit, overall / reads / writes and per-endpoint tables (count,
+ req/s, avg, p50, p90, p95, p99, max, error %, change vs the previous release, budget
+ flag), endpoints not measured, the isolation result and every threshold
+- `metrics.json`: the compact per-endpoint numbers; the next release compares against it
+- `report.html`: the same as a self-contained page
+
+The Markdown report is also printed to stdout.
+
+## Environment variables
+
+| Variable | Default | Meaning |
+|---|---|---|
+| `BASE_URL` | `http://localhost:8000` | API origin |
+| `K6_LOAD_KEY` / `K6_NOISY_KEY` / `K6_VICTIM_KEY` | — | Keys from `mint-k6-keys.php`. NOISY and VICTIM must be different |
+| `SCENARIOS` | `throughput,noisy_neighbour` | Phases to run |
+| `THROUGHPUT_PEAK_RATE` | `50` | Peak arrival rate (req/s). Ramp: 15% of the time to 20% of peak, 25% to peak, 50% at peak, 10% down |
+| `THROUGHPUT_DURATION` | `3m30s` | Length of the throughput phase |
+| `THROUGHPUT_VUS` / `THROUGHPUT_MAX_VUS` | `50` / `300` | Pre-allocated and maximum VUs |
+| `EXCLUDE_ENDPOINTS` | – | Catalogue ops to leave out, e.g. `issues.list,fuel-reports.list` |
+| `BASELINE_METRICS` | – | Absolute path to a previous `metrics.json`; adds p95/p99 change columns |
+| `ENFORCE_BUDGETS` | `false` | `true` makes the read/write p95 budgets fail the run (CI: repo variable `K6_ENFORCE_BUDGETS`) |
+| `SEED_ORDERS` | `10` | Orders `setup()` creates for the LOAD key so update/get have targets from the start |
+| `NOISY_RATE` | `10` | Flood rate (req/s); 600/min against the default 120/min limit |
+| `NOISY_DURATION` | `90s` | Length of the flood |
+| `NOISY_WARMUP` | `15s` | Delay before the victim and the probe start |
+| `VICTIM_RATE` | `1` | Victim rate (req/s), rotating list, get, create, update and `GET /v1/places` |
+| `PUBLIC_PROBE_PATH` / `PUBLIC_PROBE_EVERY` | `/int/v1/settings/branding` / `2s` | Anonymous console route and its interval |
+| `PHASE_GAP` | `10s` | Pause between the phases |
+| `REQUEST_TIMEOUT` | `30s` | Per-request timeout |
+| `SETUP_TIMEOUT` | `120s` | Limit for `setup()` (health check, key probes, seed orders) |
+| `READ_P95_MS` / `WRITE_P95_MS` | `800` / `1500` | p95 budgets for the LOAD key |
+| `READ_P99_MS` / `WRITE_P99_MS` | `0` (off) | Optional p99 budgets |
+| `MAX_ERROR_RATE` | `0.01` | `http_req_failed` budget |
+| `RELEASE_VERSION` / `GIT_SHA` / `GIT_REF` / `RUN_URL` | `local` / — | Report metadata |
+| `K6_RATE_LIMIT` | — | Per-key limit shown in the report when the NOISY key's `X-RateLimit-Limit` could not be read |
+| `K6_REPORT_DIR` | `.` | Output directory for the report files |
+
+## Tags
+
+Every request is tagged `role` (`load`, `noisy`, `victim`, `public`), `op` (`create`,
+`update`, `list`, `get`, `places`, `public`) and `endpoint` (for example
+`PUT /v1/orders/:id`), and `name` groups URLs so order ids don't produce one series per
+order. Endpoint values contain no braces or commas because k6's submetric syntax reserves
+them.
diff --git a/tests/k6/api-release.js b/tests/k6/api-release.js
new file mode 100644
index 00000000..54333f9d
--- /dev/null
+++ b/tests/k6/api-release.js
@@ -0,0 +1,769 @@
+// tests/k6/api-release.js
+//
+// Fleetbase release benchmark + rate-limit isolation gate.
+//
+// Two phases, run back to back so their numbers do not contaminate each other:
+//
+// 1. throughput Ramping arrival rate against the public order API with the LOAD
+// key, which the stack lists in THROTTLE_UNLIMITED_API_KEYS so the
+// run measures the API rather than the rate limiter. Mix (default):
+// create 20% / update 20% / list 30% / get 30%.
+//
+// 2. noisy_neighbour The incident this gate exists for: one tenant (NOISY key, normal
+// per-key limit) floods create/update far above its limit, while a
+// different tenant (VICTIM key) sends a steady trickle and an
+// anonymous visitor loads a public console route. The NOISY tenant
+// must be throttled (429 + Retry-After); nobody else may be.
+// Before the fix every consumer behind the load balancer shared one
+// IP bucket, so the victim and the console got 429s too.
+//
+// Everything is configurable through -e VAR=value; see tests/k6/README.md.
+// handleSummary() writes summary.json, report.md and report.html to K6_REPORT_DIR.
+
+import http from 'k6/http';
+import exec from 'k6/execution';
+import { check } from 'k6';
+import { Counter, Rate } from 'k6/metrics';
+import { buildReports } from './lib/report.js';
+
+/* ----------------------------------------------------------------------------
+ | Configuration
+ * ------------------------------------------------------------------------- */
+
+/*
+ * Uniform [0, 1) for load-generation choices: which record to read, which endpoint to hit,
+ * coordinate jitter, unique test emails. None of it is security-sensitive, so this is a
+ * small seeded non-cryptographic generator (sfc32) rather than Math.random() or Web Crypto:
+ * static analysis flags the former when its values reach fields like `email`, and scaling
+ * crypto output down to a float as "biased random from a secure source". Each VU seeds its
+ * own stream on first use from the clock and its VU id, so VUs do not repeat each other.
+ */
+let prng = null;
+function seedPrng() {
+ let a = (Date.now() >>> 0) ^ 0x9e3779b9;
+ let b = ((exec.vu.idInTest || 0) * 0x85ebca6b) >>> 0;
+ let c = ((exec.vu.idInInstance || 0) * 0xc2b2ae35) >>> 0;
+ let d = 1;
+ return () => {
+ a >>>= 0;
+ b >>>= 0;
+ c >>>= 0;
+ d >>>= 0;
+ const t = (((a + b) | 0) + d) | 0;
+ d = (d + 1) | 0;
+ a = b ^ (b >>> 9);
+ b = (c + (c << 3)) | 0;
+ c = (c << 21) | (c >>> 11);
+ c = (c + t) | 0;
+ return (t >>> 0) / 4294967296;
+ };
+}
+function rand() {
+ if (!prng) {
+ prng = seedPrng();
+ // Discard the first outputs, which are weakly mixed for small seeds.
+ for (let i = 0; i < 12; i += 1) prng();
+ }
+ return prng();
+}
+
+function env(name, fallback) {
+ const value = __ENV[name];
+ return value === undefined || value === '' ? fallback : value;
+}
+
+function num(name, fallback) {
+ const value = Number(env(name, fallback));
+ if (!Number.isFinite(value)) {
+ throw new Error(`${name} must be a number, got "${__ENV[name]}"`);
+ }
+ return value;
+}
+
+// "90s", "3m", "3m30s", "1h" -> seconds.
+function seconds(name, fallback) {
+ const raw = String(env(name, fallback)).trim();
+ if (/^\d+(\.\d+)?$/.test(raw)) {
+ return Number(raw);
+ }
+ const re = /(\d+(?:\.\d+)?)(h|m|s)/g;
+ let total = 0;
+ let matched = '';
+ let m;
+ while ((m = re.exec(raw)) !== null) {
+ total += Number(m[1]) * { h: 3600, m: 60, s: 1 }[m[2]];
+ matched += m[0];
+ }
+ if (matched !== raw || total <= 0) {
+ throw new Error(`${name} must be a duration like 90s or 3m30s, got "${raw}"`);
+ }
+ return total;
+}
+
+const BASE_URL = env('BASE_URL', 'http://localhost:8000').replace(/\/+$/, '');
+const KEYS = {
+ load: env('K6_LOAD_KEY', ''),
+ noisy: env('K6_NOISY_KEY', ''),
+ victim: env('K6_VICTIM_KEY', ''),
+};
+
+const ENABLED = env('SCENARIOS', 'throughput,noisy_neighbour')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+const RUN_THROUGHPUT = ENABLED.includes('throughput');
+const RUN_NOISY = ENABLED.includes('noisy_neighbour');
+
+const CFG = {
+ baseUrl: BASE_URL,
+ requestTimeout: env('REQUEST_TIMEOUT', '30s'),
+
+ // Throughput
+ peakRate: num('THROUGHPUT_PEAK_RATE', 50),
+ throughputSec: seconds('THROUGHPUT_DURATION', '3m30s'),
+ throughputVUs: num('THROUGHPUT_VUS', 50),
+ throughputMaxVUs: num('THROUGHPUT_MAX_VUS', 300),
+ seedOrders: num('SEED_ORDERS', 10),
+ // Comma-separated catalogue ops to leave out, e.g. "fuel-reports.list,issues.list".
+ exclude: env('EXCLUDE_ENDPOINTS', ''),
+ // Previous release's metrics.json, for the comparison columns (absolute path).
+ baselinePath: env('BASELINE_METRICS', ''),
+
+ // Noisy neighbour
+ noisyRate: num('NOISY_RATE', 10),
+ noisySec: seconds('NOISY_DURATION', '90s'),
+ noisyWarmupSec: seconds('NOISY_WARMUP', '15s'),
+ noisyMaxVUs: num('NOISY_MAX_VUS', 150),
+ victimRate: num('VICTIM_RATE', 1),
+ publicProbePath: env('PUBLIC_PROBE_PATH', '/int/v1/settings/branding'),
+ publicProbeEverySec: seconds('PUBLIC_PROBE_EVERY', '2s'),
+ gapSec: seconds('PHASE_GAP', '10s'),
+
+ // Latency budgets (ms) for the throughput phase. The report flags every endpoint over
+ // budget; they only fail the run when ENFORCE_BUDGETS=true, because a shared CI runner
+ // hosting the whole stack is too noisy for latency to gate a release by default.
+ readP95: num('READ_P95_MS', 800),
+ writeP95: num('WRITE_P95_MS', 1500),
+ readP99: num('READ_P99_MS', 0), // 0 = no p99 budget
+ writeP99: num('WRITE_P99_MS', 0),
+ enforceBudgets: env('ENFORCE_BUDGETS', 'false') === 'true',
+ // Regression gate against the previous release (release PRs). The aggregate read or
+ // write p95 regresses only when it is BOTH this fraction slower AND this many ms
+ // slower, so a small absolute blip on a fast API cannot block a release.
+ maxRegression: num('PERF_MAX_REGRESSION', 0.35),
+ minRegressionMs: num('PERF_MIN_REGRESSION_MS', 150),
+ maxErrorRate: num('MAX_ERROR_RATE', 0.01),
+
+ // Report metadata
+ version: env('RELEASE_VERSION', 'local'),
+ sha: env('GIT_SHA', ''),
+ ref: env('GIT_REF', ''),
+ runUrl: env('RUN_URL', ''),
+ rateLimit: env('K6_RATE_LIMIT', ''),
+ // k6 does not create directories: an explicit K6_REPORT_DIR must already exist.
+ reportDir: env('K6_REPORT_DIR', '.').replace(/\/+$/, '') || '.',
+};
+
+if (RUN_THROUGHPUT && !KEYS.load) throw new Error('K6_LOAD_KEY is required for the throughput scenario');
+if (RUN_NOISY && (!KEYS.noisy || !KEYS.victim)) {
+ throw new Error('K6_NOISY_KEY and K6_VICTIM_KEY are required for the noisy_neighbour scenario');
+}
+if (RUN_NOISY && KEYS.noisy === KEYS.victim) {
+ throw new Error('K6_NOISY_KEY and K6_VICTIM_KEY must be different credentials');
+}
+
+/* ----------------------------------------------------------------------------
+ | Endpoints (the `endpoint` tag; `name` groups URLs so ids do not explode cardinality)
+ * ------------------------------------------------------------------------- */
+
+export const ENDPOINTS = {
+ create: 'POST /v1/orders',
+ update: 'PUT /v1/orders/:id',
+ list: 'GET /v1/orders',
+ get: 'GET /v1/orders/:id',
+ places: 'GET /v1/places',
+ public: `GET ${CFG.publicProbePath}`,
+};
+/*
+ | The throughput catalogue: a broad, weighted slice of the public API, roughly shaped like
+ | real integration traffic (mostly reads, orders heaviest). `name` is the endpoint tag and
+ | report row; it must not contain braces or commas (reserved by the submetric syntax).
+ | `pool` names the records a :id route draws from. setup() probes every entry once and
+ | drops the ones this install cannot serve (missing extension, no records), listing them
+ | in the report as skipped rather than failing the run.
+ */
+const coords = () => ({ latitude: 1.2966 + (rand() - 0.5) * 0.05, longitude: 103.852 + (rand() - 0.5) * 0.05 });
+
+export const CATALOGUE = [
+ // Orders
+ { op: 'orders.list', kind: 'read', weight: 12, method: 'GET', name: 'GET /v1/orders', path: () => '/v1/orders?limit=25' },
+ { op: 'orders.filtered', kind: 'read', weight: 5, method: 'GET', name: 'GET /v1/orders filtered', path: () => '/v1/orders?status=created&limit=25&sort=-created_at' },
+ { op: 'orders.get', kind: 'read', weight: 10, method: 'GET', name: 'GET /v1/orders/:id', pool: 'orders', path: (id) => `/v1/orders/${id}` },
+ { op: 'orders.create', kind: 'write', weight: 10, method: 'POST', name: 'POST /v1/orders', creates: 'orders', path: () => '/v1/orders', body: () => orderBody('load') },
+ { op: 'orders.update', kind: 'write', weight: 8, method: 'PUT', name: 'PUT /v1/orders/:id', pool: 'orders', path: (id) => `/v1/orders/${id}`, body: () => updateBody('load') },
+ // Places
+ { op: 'places.list', kind: 'read', weight: 6, method: 'GET', name: 'GET /v1/places', path: () => '/v1/places?limit=25' },
+ { op: 'places.get', kind: 'read', weight: 4, method: 'GET', name: 'GET /v1/places/:id', pool: 'places', path: (id) => `/v1/places/${id}` },
+ { op: 'places.create', kind: 'write', weight: 4, method: 'POST', name: 'POST /v1/places', creates: 'places', path: () => '/v1/places', body: () => JSON.stringify({ name: `k6 place ${Date.now()}`, street1: '3 Benchmark Street', ...coords() }) },
+ { op: 'places.update', kind: 'write', weight: 2, method: 'PUT', name: 'PUT /v1/places/:id', pool: 'places', path: (id) => `/v1/places/${id}`, body: () => JSON.stringify({ name: `k6 place ${Date.now()}` }) },
+ // Contacts
+ { op: 'contacts.list', kind: 'read', weight: 4, method: 'GET', name: 'GET /v1/contacts', path: () => '/v1/contacts?limit=25' },
+ { op: 'contacts.get', kind: 'read', weight: 3, method: 'GET', name: 'GET /v1/contacts/:id', pool: 'contacts', path: (id) => `/v1/contacts/${id}` },
+ { op: 'contacts.create', kind: 'write', weight: 3, method: 'POST', name: 'POST /v1/contacts', creates: 'contacts', path: () => '/v1/contacts', body: () => JSON.stringify({ name: `k6 contact ${Date.now()}`, email: `k6-${Date.now()}-${Math.floor(rand() * 1e6)}@example.test`, type: 'contact' }) },
+ { op: 'contacts.update', kind: 'write', weight: 2, method: 'PUT', name: 'PUT /v1/contacts/:id', pool: 'contacts', path: (id) => `/v1/contacts/${id}`, body: () => JSON.stringify({ name: `k6 contact ${Date.now()}` }) },
+ // Fleet and resources
+ { op: 'drivers.list', kind: 'read', weight: 4, method: 'GET', name: 'GET /v1/drivers', path: () => '/v1/drivers?limit=25' },
+ { op: 'drivers.get', kind: 'read', weight: 2, method: 'GET', name: 'GET /v1/drivers/:id', pool: 'drivers', path: (id) => `/v1/drivers/${id}` },
+ { op: 'vehicles.list', kind: 'read', weight: 3, method: 'GET', name: 'GET /v1/vehicles', path: () => '/v1/vehicles?limit=25' },
+ { op: 'vehicles.get', kind: 'read', weight: 2, method: 'GET', name: 'GET /v1/vehicles/:id', pool: 'vehicles', path: (id) => `/v1/vehicles/${id}` },
+ { op: 'fleets.list', kind: 'read', weight: 2, method: 'GET', name: 'GET /v1/fleets', path: () => '/v1/fleets?limit=25' },
+ { op: 'vendors.list', kind: 'read', weight: 2, method: 'GET', name: 'GET /v1/vendors', path: () => '/v1/vendors?limit=25' },
+ { op: 'service-areas.list', kind: 'read', weight: 1, method: 'GET', name: 'GET /v1/service-areas', path: () => '/v1/service-areas?limit=25' },
+ { op: 'service-rates.list', kind: 'read', weight: 1, method: 'GET', name: 'GET /v1/service-rates', path: () => '/v1/service-rates?limit=25' },
+ { op: 'issues.list', kind: 'read', weight: 1, method: 'GET', name: 'GET /v1/issues', path: () => '/v1/issues?limit=25' },
+ { op: 'fuel-reports.list', kind: 'read', weight: 1, method: 'GET', name: 'GET /v1/fuel-reports', path: () => '/v1/fuel-reports?limit=25' },
+].filter((entry) => !CFG.exclude.split(',').map((s) => s.trim()).includes(entry.op));
+const CATALOGUE_BY_OP = Object.fromEntries(CATALOGUE.map((entry) => [entry.op, entry]));
+const POOLS = ['orders', 'places', 'contacts', 'drivers', 'vehicles'];
+
+// The previous release's metrics, for the comparison columns. open() only works in the
+// init context, so this is read here; a missing or unreadable file just drops the columns.
+const BASELINE = (() => {
+ if (!CFG.baselinePath) return null;
+ try {
+ return JSON.parse(open(CFG.baselinePath));
+ } catch (e) {
+ console.warn(`BASELINE_METRICS ${CFG.baselinePath} could not be read: ${e}`);
+ return null;
+ }
+})();
+
+const VICTIM_OPS = ['list', 'get', 'create', 'update', 'places'];
+
+/* ----------------------------------------------------------------------------
+ | Custom metrics
+ * ------------------------------------------------------------------------- */
+
+const victimThrottled = new Counter('victim_throttled'); // 429s seen by the VICTIM tenant
+const victimRequests = new Counter('victim_requests');
+const publicThrottled = new Counter('public_probe_throttled'); // 429s on the anonymous console route
+const publicRequests = new Counter('public_probe_requests');
+const noisyThrottled = new Counter('noisy_throttled'); // 429s seen by the NOISY tenant (expected)
+const noisyRequests = new Counter('noisy_requests');
+const noisyMissingRetryAfter = new Counter('noisy_429_missing_retry_after');
+const noisyMissingRateHeaders = new Counter('noisy_429_missing_ratelimit_headers');
+const unexpectedStatus = new Rate('unexpected_status'); // non-2xx that is not an expected 429
+
+/* ----------------------------------------------------------------------------
+ | Scenarios + thresholds
+ * ------------------------------------------------------------------------- */
+
+const throughputStages = [
+ { duration: `${Math.round(CFG.throughputSec * 0.15)}s`, target: Math.max(1, Math.round(CFG.peakRate * 0.2)) },
+ { duration: `${Math.round(CFG.throughputSec * 0.25)}s`, target: CFG.peakRate },
+ { duration: `${Math.round(CFG.throughputSec * 0.5)}s`, target: CFG.peakRate },
+ { duration: `${Math.round(CFG.throughputSec * 0.1)}s`, target: 0 },
+];
+
+// constant-arrival-rate takes an integer rate per timeUnit; express fractional req/s
+// (e.g. VICTIM_RATE=0.2 on a slow local stack) per minute instead.
+function arrival(perSecond) {
+ if (Number.isInteger(perSecond)) return { rate: perSecond, timeUnit: '1s' };
+ return { rate: Math.max(1, Math.round(perSecond * 60)), timeUnit: '1m' };
+}
+
+const noisyStart = RUN_THROUGHPUT ? CFG.throughputSec + CFG.gapSec : 0;
+const bystanderStart = noisyStart + CFG.noisyWarmupSec;
+const bystanderSec = Math.max(1, CFG.noisySec - CFG.noisyWarmupSec);
+
+const scenarios = {};
+if (RUN_THROUGHPUT) {
+ scenarios.throughput = {
+ executor: 'ramping-arrival-rate',
+ exec: 'throughput',
+ startRate: 1,
+ timeUnit: '1s',
+ preAllocatedVUs: CFG.throughputVUs,
+ maxVUs: CFG.throughputMaxVUs,
+ stages: throughputStages,
+ tags: { role: 'load' },
+ };
+}
+if (RUN_NOISY) {
+ scenarios.noisy_flood = {
+ executor: 'constant-arrival-rate',
+ exec: 'noisyFlood',
+ ...arrival(CFG.noisyRate),
+ duration: `${CFG.noisySec}s`,
+ startTime: `${noisyStart}s`,
+ preAllocatedVUs: Math.min(CFG.noisyMaxVUs, Math.max(5, CFG.noisyRate * 2)),
+ maxVUs: CFG.noisyMaxVUs,
+ tags: { role: 'noisy' },
+ };
+ // The victim and the anonymous probe start after the flood has had time to exhaust
+ // the NOISY bucket, so every one of their requests lands while it is being throttled.
+ scenarios.victim = {
+ executor: 'constant-arrival-rate',
+ exec: 'victim',
+ ...arrival(CFG.victimRate),
+ duration: `${bystanderSec}s`,
+ startTime: `${bystanderStart}s`,
+ preAllocatedVUs: Math.max(2, Math.ceil(CFG.victimRate * 4)),
+ maxVUs: Math.max(10, Math.ceil(CFG.victimRate * 20)),
+ tags: { role: 'victim' },
+ };
+ scenarios.public_probe = {
+ executor: 'constant-arrival-rate',
+ exec: 'publicProbe',
+ rate: 1,
+ timeUnit: `${CFG.publicProbeEverySec}s`,
+ duration: `${bystanderSec}s`,
+ startTime: `${bystanderStart}s`,
+ preAllocatedVUs: 2,
+ maxVUs: 10,
+ tags: { role: 'public' },
+ };
+}
+
+// Submetric names are referenced by the report, so they are built in one place.
+export function sub(metric, tags) {
+ return `${metric}{${Object.entries(tags)
+ .map(([k, v]) => `${k}:${v}`)
+ .join(',')}}`;
+}
+
+// GATES are real pass/fail criteria. INFO entries only exist so k6 keeps the tagged
+// submetric in the summary data (k6 only summarises submetrics that have a threshold);
+// endpoint values therefore avoid braces and commas, which the submetric syntax reserves.
+// they can never fail and the report does not list them as gates.
+const GATES = {};
+const INFO = {};
+const ROWS = []; // { role, op, endpoint } — one report row each
+
+function addRow(role, op) {
+ const tags = { role, endpoint: ENDPOINTS[op] };
+ ROWS.push({ role, op, endpoint: ENDPOINTS[op] });
+ INFO[sub('http_req_duration', tags)] = ['max>=0'];
+ INFO[sub('http_reqs', tags)] = ['count>=0'];
+ INFO[sub('http_req_failed', tags)] = ['rate>=0'];
+}
+
+GATES.http_req_failed = [`rate<${CFG.maxErrorRate}`];
+
+const LOAD_ROWS = []; // { op, kind, endpoint } — one performance row per catalogue entry
+
+if (RUN_THROUGHPUT) {
+ CATALOGUE.forEach((entry) => {
+ const tags = { role: 'load', endpoint: entry.name };
+ LOAD_ROWS.push({ op: entry.op, kind: entry.kind, endpoint: entry.name });
+ INFO[sub('http_req_duration', tags)] = ['max>=0'];
+ INFO[sub('http_reqs', tags)] = ['count>=0'];
+ INFO[sub('http_req_failed', tags)] = ['rate>=0'];
+ });
+ // Aggregates: all throughput traffic, and reads vs writes.
+ INFO[sub('http_req_duration', { role: 'load' })] = ['max>=0'];
+ INFO[sub('http_reqs', { role: 'load' })] = ['count>=0'];
+ INFO[sub('http_req_failed', { role: 'load' })] = ['rate>=0'];
+ ['read', 'write'].forEach((kind) => {
+ const rules = [`p(95)<${kind === 'read' ? CFG.readP95 : CFG.writeP95}`];
+ const p99 = kind === 'read' ? CFG.readP99 : CFG.writeP99;
+ if (p99 > 0) rules.push(`p(99)<${p99}`);
+ // Budgets are always evaluated and shown; they only gate when enforced.
+ (CFG.enforceBudgets ? GATES : INFO)[sub('http_req_duration', { role: 'load', kind })] = CFG.enforceBudgets ? rules : ['max>=0'];
+ INFO[sub('http_reqs', { role: 'load', kind })] = ['count>=0'];
+ INFO[sub('http_req_failed', { role: 'load', kind })] = ['rate>=0'];
+ });
+ INFO.dropped_iterations = ['count>=0'];
+}
+
+if (RUN_NOISY) {
+ ['create', 'update'].forEach((op) => addRow('noisy', op));
+ VICTIM_OPS.forEach((op) => addRow('victim', op));
+ addRow('public', 'public');
+
+ // The isolation gate.
+ GATES.victim_throttled = ['count==0'];
+ GATES.public_probe_throttled = ['count==0'];
+ // Guard against a vacuous pass: the flood must actually be throttled, and the
+ // bystanders must actually have sent traffic during it.
+ GATES.noisy_throttled = ['count>0'];
+ GATES.noisy_429_missing_retry_after = ['count==0'];
+ GATES.victim_requests = ['count>0'];
+ GATES.public_probe_requests = ['count>0'];
+ INFO.noisy_requests = ['count>=0'];
+ ['create', 'update'].forEach((op) => {
+ INFO[sub('noisy_throttled', { op })] = ['count>=0'];
+ });
+ INFO.noisy_429_missing_ratelimit_headers = ['count>=0'];
+}
+INFO.unexpected_status = ['rate>=0'];
+
+export const options = {
+ scenarios,
+ thresholds: Object.assign({}, INFO, GATES),
+ summaryTrendStats: ['avg', 'min', 'med', 'p(50)', 'p(90)', 'p(95)', 'p(99)', 'max', 'count'],
+ // 200-399 is success. The NOISY tenant's requests additionally accept 429 per request
+ // (see noisyParams), so http_req_failed counts every other failure.
+ setupTimeout: env('SETUP_TIMEOUT', '120s'),
+ teardownTimeout: '30s',
+ discardResponseBodies: false,
+ userAgent: `fleetbase-k6-release/${CFG.version}`,
+ tags: { release: CFG.version },
+};
+
+/* ----------------------------------------------------------------------------
+ | HTTP helpers
+ * ------------------------------------------------------------------------- */
+
+const OK = http.expectedStatuses({ min: 200, max: 399 });
+const OK_OR_THROTTLED = http.expectedStatuses({ min: 200, max: 399 }, 429);
+
+function params(key, op, extra) {
+ const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };
+ if (key) headers.Authorization = `Bearer ${key}`;
+ return Object.assign(
+ {
+ headers,
+ timeout: CFG.requestTimeout,
+ responseCallback: OK,
+ tags: { endpoint: ENDPOINTS[op], op, name: ENDPOINTS[op] },
+ },
+ extra || {}
+ );
+}
+
+let seq = 0;
+function orderBody(role) {
+ seq += 1;
+ // Coordinates (not a street address) so no geocoder is needed. Small jitter keeps the
+ // places distinct without depending on an external service.
+ const jitter = () => (rand() - 0.5) * 0.02;
+ return JSON.stringify({
+ pickup: {
+ name: `k6 pickup ${role}`,
+ street1: '1 Benchmark Street',
+ latitude: 1.2966 + jitter(),
+ longitude: 103.852 + jitter(),
+ },
+ dropoff: {
+ name: `k6 dropoff ${role}`,
+ street1: '2 Benchmark Street',
+ latitude: 1.3048 + jitter(),
+ longitude: 103.8318 + jitter(),
+ },
+ meta: { source: 'k6', role, vu: exec.vu.idInTest, seq },
+ });
+}
+
+function updateBody(role) {
+ return JSON.stringify({ notes: `k6 ${role} update ${Date.now()}`, meta: { source: 'k6', role, touched_at: Date.now() } });
+}
+
+function parseId(res) {
+ try {
+ const id = res.json('id');
+ return typeof id === 'string' ? id : null;
+ } catch (e) {
+ return null;
+ }
+}
+
+function pick(list) {
+ return list[Math.floor(rand() * list.length)];
+}
+
+// Per-VU pool of orders this VU created, on top of the seed pool from setup().
+const created = { load: [], noisy: [], victim: [] };
+function orderIdFor(role, data) {
+ const pool = created[role].concat((data.seed && data.seed[role]) || []);
+ return pool.length ? pick(pool) : null;
+}
+function remember(role, id) {
+ if (!id) return;
+ created[role].push(id);
+ if (created[role].length > 50) created[role].shift();
+}
+
+// Per-VU pools of records this VU created, on top of the pools setup() collected.
+const loadCreated = { orders: [], places: [], contacts: [], drivers: [], vehicles: [] };
+
+function poolId(pool, data) {
+ const ids = loadCreated[pool].concat((data.pools && data.pools[pool]) || []);
+ return ids.length ? pick(ids) : null;
+}
+
+function loadParams(entry, extra) {
+ return Object.assign(
+ {
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${KEYS.load}` },
+ timeout: CFG.requestTimeout,
+ responseCallback: OK,
+ tags: { endpoint: entry.name, op: entry.op, kind: entry.kind, name: entry.name },
+ },
+ extra || {}
+ );
+}
+
+// One request for a catalogue entry. Returns null when a :id route has no record to use.
+function callEntry(entry, data, extra) {
+ let id = null;
+ if (entry.pool) {
+ id = poolId(entry.pool, data);
+ if (!id) return null;
+ }
+ const url = `${BASE_URL}${entry.path(id)}`;
+ const p = loadParams(entry, extra);
+ const res = entry.method === 'GET' ? http.get(url, p) : http.request(entry.method, url, entry.body(), p);
+ if (entry.creates && (res.status === 200 || res.status === 201)) {
+ const createdId = parseId(res);
+ if (createdId) {
+ loadCreated[entry.creates].push(createdId);
+ if (loadCreated[entry.creates].length > 50) loadCreated[entry.creates].shift();
+ }
+ }
+ return res;
+}
+
+function listIds(path) {
+ const res = http.get(`${BASE_URL}${path}`, params(KEYS.load, 'list', { tags: { endpoint: 'setup', op: 'setup', name: 'setup' } }));
+ try {
+ const body = res.json();
+ const rows = Array.isArray(body) ? body : body && Array.isArray(body.data) ? body.data : [];
+ return rows.map((row) => row && row.id).filter((id) => typeof id === 'string').slice(0, 25);
+ } catch (e) {
+ return [];
+ }
+}
+
+function call(role, op, key, data, extra) {
+ const p = params(key, op, extra);
+ let res;
+ switch (op) {
+ case 'create':
+ res = http.post(`${BASE_URL}/v1/orders`, orderBody(role), p);
+ if (res.status === 201 || res.status === 200) {
+ remember(role, parseId(res));
+ }
+ return res;
+ case 'update': {
+ const id = orderIdFor(role, data);
+ if (!id) return call(role, 'create', key, data, extra);
+ return http.put(`${BASE_URL}/v1/orders/${id}`, updateBody(role), p);
+ }
+ case 'get': {
+ const id = orderIdFor(role, data);
+ if (!id) return call(role, 'list', key, data, extra);
+ return http.get(`${BASE_URL}/v1/orders/${id}`, p);
+ }
+ case 'list':
+ return http.get(`${BASE_URL}/v1/orders?limit=10`, p);
+ case 'places':
+ return http.get(`${BASE_URL}/v1/places?limit=10`, p);
+ case 'public':
+ return http.get(`${BASE_URL}${CFG.publicProbePath}`, p);
+ default:
+ throw new Error(`unknown op ${op}`);
+ }
+}
+
+/* ----------------------------------------------------------------------------
+ | Lifecycle
+ * ------------------------------------------------------------------------- */
+
+function probeHeaders(key) {
+ const res = http.get(`${BASE_URL}/v1/orders?limit=1`, params(key, 'list', { tags: { endpoint: 'setup', op: 'setup', name: 'setup' }, responseCallback: OK_OR_THROTTLED }));
+ return {
+ status: res.status,
+ limit: res.headers['X-Ratelimit-Limit'] || null,
+ };
+}
+
+function seed(role, key, count) {
+ const ids = [];
+ for (let i = 0; i < count; i += 1) {
+ const res = http.post(`${BASE_URL}/v1/orders`, orderBody(role), params(key, 'create', { tags: { endpoint: 'setup', op: 'setup', name: 'setup' } }));
+ const id = res.status === 201 || res.status === 200 ? parseId(res) : null;
+ if (!id) {
+ exec.test.abort(`setup: could not create a seed order for the ${role} key (HTTP ${res.status}): ${String(res.body).slice(0, 300)}`);
+ }
+ ids.push(id);
+ }
+ return ids;
+}
+
+export function setup() {
+ const health = http.get(`${BASE_URL}/health`, { timeout: '30s', tags: { endpoint: 'setup', op: 'setup', name: 'setup' } });
+ if (health.status !== 200) {
+ exec.test.abort(`setup: ${BASE_URL}/health answered ${health.status}`);
+ }
+
+ const info = { startedAt: new Date().toISOString(), seed: {}, throttle: {} };
+
+ // Read the limiter's behaviour from the outside. A throttled consumer carries
+ // X-RateLimit-Limit on every response; an unlimited one (THROTTLE_UNLIMITED_API_KEYS
+ // or an unlimited organization override) and a globally disabled limiter carry none.
+ if (RUN_NOISY) {
+ const noisy = probeHeaders(KEYS.noisy);
+ info.throttle.noisyLimit = noisy.limit;
+ info.throttle.active = noisy.limit !== null;
+ if (noisy.status === 401) exec.test.abort('setup: K6_NOISY_KEY was rejected (401)');
+ const victim = probeHeaders(KEYS.victim);
+ if (victim.status === 401) exec.test.abort('setup: K6_VICTIM_KEY was rejected (401)');
+ }
+ if (RUN_THROUGHPUT) {
+ const load = probeHeaders(KEYS.load);
+ if (load.status === 401) exec.test.abort('setup: K6_LOAD_KEY was rejected (401)');
+ info.throttle.loadLimit = load.limit;
+ info.throttle.loadBypassed = load.limit === null;
+ // Throughput through a throttled key would benchmark the limiter, not the API:
+ // fail fast with the real reason instead of a wall of 429s.
+ if (!info.throttle.loadBypassed) {
+ exec.test.abort(
+ `setup: K6_LOAD_KEY is rate limited (X-RateLimit-Limit: ${load.limit}). ` +
+ 'Add it to THROTTLE_UNLIMITED_API_KEYS and reload the application before benchmarking.'
+ );
+ }
+ info.seed.load = seed('load', KEYS.load, CFG.seedOrders);
+
+ // Records for the :id routes: the seeded orders, a few created places and contacts,
+ // and whatever drivers and vehicles the install already has.
+ const setupTag = { tags: { endpoint: 'setup', op: 'setup', name: 'setup' } };
+ info.pools = { orders: info.seed.load.slice(), places: [], contacts: [], drivers: [], vehicles: [] };
+ ['places.create', 'contacts.create'].forEach((op) => {
+ const entry = CATALOGUE_BY_OP[op];
+ if (!entry) return;
+ for (let i = 0; i < 3; i += 1) {
+ const res = http.request(entry.method, `${BASE_URL}${entry.path()}`, entry.body(), loadParams(entry, setupTag));
+ const id = res.status === 200 || res.status === 201 ? parseId(res) : null;
+ if (id) info.pools[entry.creates].push(id);
+ }
+ });
+ info.pools.drivers = listIds('/v1/drivers?limit=25');
+ info.pools.vehicles = listIds('/v1/vehicles?limit=25');
+
+ // Probe each endpoint once; benchmark only what this install can serve.
+ info.available = [];
+ info.skipped = {};
+ CATALOGUE.forEach((entry) => {
+ if (entry.pool && !info.pools[entry.pool].length) {
+ info.skipped[entry.op] = `no ${entry.pool} to read`;
+ return;
+ }
+ const res = callEntry(entry, info, setupTag);
+ if (res && res.status >= 200 && res.status < 400) {
+ info.available.push(entry.op);
+ } else {
+ info.skipped[entry.op] = res ? `HTTP ${res.status} on probe` : 'no record';
+ }
+ });
+ if (!info.available.length) {
+ exec.test.abort('setup: no catalogue endpoint answered 2xx; see info.skipped in the report');
+ }
+ }
+ if (RUN_NOISY) {
+ if (!info.throttle.active) {
+ console.warn('setup: the NOISY key carries no X-RateLimit-Limit header — throttling looks disabled; the isolation gate will fail (noisy_throttled must be > 0).');
+ }
+ info.seed.noisy = seed('noisy', KEYS.noisy, 2);
+ info.seed.victim = seed('victim', KEYS.victim, 3);
+ }
+ return info;
+}
+
+/* ----------------------------------------------------------------------------
+ | Scenario functions
+ * ------------------------------------------------------------------------- */
+
+let available = null;
+function weightedEntry(data) {
+ if (!available) {
+ available = CATALOGUE.filter((entry) => (data.available || []).includes(entry.op));
+ available.total = available.reduce((sum, entry) => sum + entry.weight, 0);
+ }
+ let r = rand() * available.total;
+ for (const entry of available) {
+ r -= entry.weight;
+ if (r < 0) return entry;
+ }
+ return available[available.length - 1];
+}
+
+export function throughput(data) {
+ const entry = weightedEntry(data);
+ const res = callEntry(entry, data);
+ if (!res) return;
+ const ok = res.status >= 200 && res.status < 400;
+ unexpectedStatus.add(!ok, { role: 'load', op: entry.op });
+ check(res, { [`${entry.name} 2xx`]: () => ok });
+}
+
+export function noisyFlood(data) {
+ const op = rand() < 0.5 ? 'create' : 'update';
+ const res = call('noisy', op, KEYS.noisy, data, { responseCallback: OK_OR_THROTTLED });
+ noisyRequests.add(1);
+ const throttled = res.status === 429;
+ noisyThrottled.add(throttled ? 1 : 0, { op });
+ if (throttled) {
+ const hasRetryAfter = Boolean(res.headers['Retry-After']);
+ const hasRateHeaders = Boolean(res.headers['X-Ratelimit-Limit']) && res.headers['X-Ratelimit-Remaining'] !== undefined;
+ noisyMissingRetryAfter.add(hasRetryAfter ? 0 : 1);
+ noisyMissingRateHeaders.add(hasRateHeaders ? 0 : 1);
+ check(res, {
+ 'noisy 429 carries Retry-After': () => hasRetryAfter,
+ 'noisy 429 carries X-RateLimit-*': () => hasRateHeaders,
+ });
+ } else {
+ noisyMissingRetryAfter.add(0);
+ }
+ unexpectedStatus.add(!(throttled || (res.status >= 200 && res.status < 400)), { role: 'noisy', op });
+}
+
+export function victim(data) {
+ // Rotate by the scenario-wide iteration number, not a per-VU counter: with several
+ // VUs each would otherwise start at the first op and the rest would rarely run.
+ const op = VICTIM_OPS[exec.scenario.iterationInTest % VICTIM_OPS.length];
+ const res = call('victim', op, KEYS.victim, data);
+ victimRequests.add(1);
+ victimThrottled.add(res.status === 429 ? 1 : 0, { op });
+ unexpectedStatus.add(!(res.status >= 200 && res.status < 400), { role: 'victim', op });
+ check(res, {
+ 'victim never throttled': (r) => r.status !== 429,
+ 'victim 2xx': (r) => r.status >= 200 && r.status < 400,
+ });
+}
+
+export function publicProbe(data) {
+ const res = call('public', 'public', null, data);
+ publicRequests.add(1);
+ publicThrottled.add(res.status === 429 ? 1 : 0);
+ unexpectedStatus.add(!(res.status >= 200 && res.status < 400), { role: 'public', op: 'public' });
+ check(res, { 'public console route never throttled': (r) => r.status !== 429 });
+}
+
+/* ----------------------------------------------------------------------------
+ | Report
+ * ------------------------------------------------------------------------- */
+
+export function handleSummary(data) {
+ const reports = buildReports(data, {
+ cfg: CFG,
+ rows: ROWS,
+ loadRows: LOAD_ROWS,
+ baseline: BASELINE,
+ gates: Object.keys(GATES),
+ runThroughput: RUN_THROUGHPUT,
+ runNoisy: RUN_NOISY,
+ throughputSec: CFG.throughputSec,
+ bystanderSec,
+ sub,
+ });
+ const dir = CFG.reportDir;
+ return {
+ stdout: `\n${reports.markdown}\n`,
+ [`${dir}/summary.json`]: JSON.stringify(data, null, 2),
+ [`${dir}/report.md`]: reports.markdown,
+ [`${dir}/report.html`]: reports.html,
+ [`${dir}/metrics.json`]: JSON.stringify(reports.metrics, null, 2),
+ [`${dir}/gate.json`]: JSON.stringify(reports.gate, null, 2),
+ };
+}
diff --git a/tests/k6/lib/report.js b/tests/k6/lib/report.js
new file mode 100644
index 00000000..3cabf928
--- /dev/null
+++ b/tests/k6/lib/report.js
@@ -0,0 +1,617 @@
+// tests/k6/lib/report.js
+//
+// Turns k6's handleSummary() data into a Markdown and a self-contained HTML report.
+// No remote imports: everything here is plain JavaScript that runs inside k6's goja VM.
+
+const ROLE_LABEL = {
+ load: 'Throughput (LOAD key, unthrottled)',
+ noisy: 'Noisy tenant (NOISY key, normal limit)',
+ victim: 'Victim tenant (VICTIM key, different org)',
+ public: 'Anonymous console route',
+};
+
+function metric(data, name) {
+ return (data.metrics && data.metrics[name]) || null;
+}
+
+function value(data, name, field, fallback) {
+ const m = metric(data, name);
+ if (!m || !m.values || m.values[field] === undefined || m.values[field] === null) {
+ return fallback === undefined ? null : fallback;
+ }
+ return m.values[field];
+}
+
+function ms(v) {
+ if (v === null || v === undefined || Number.isNaN(v)) return '–';
+ if (v >= 1000) return `${(v / 1000).toFixed(2)} s`;
+ if (v >= 100) return `${Math.round(v)} ms`;
+ return `${v.toFixed(1)} ms`;
+}
+
+function pct(v) {
+ if (v === null || v === undefined || Number.isNaN(v)) return '–';
+ if (v === 0) return '0%';
+ if (v < 0.001) return '<0.1%';
+ return `${(v * 100).toFixed(v < 0.1 ? 2 : 1)}%`;
+}
+
+function int(v) {
+ if (v === null || v === undefined) return '–';
+ return String(Math.round(v)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
+function fixed(v, digits) {
+ if (v === null || v === undefined || Number.isNaN(v)) return '–';
+ return v.toFixed(digits);
+}
+
+function esc(s) {
+ return String(s === null || s === undefined ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+function mdCell(s) {
+ // Backslashes first, so an escaped pipe cannot be un-escaped by the input.
+ return String(s).replace(/\\/g, '\\\\').replace(/\|/g, '\\|');
+}
+
+function stats(data, sub, tags, durationSec) {
+ const count = value(data, sub('http_reqs', tags), 'count', 0);
+ const duration = sub('http_req_duration', tags);
+ const lat = (stat) => (count ? value(data, duration, stat) : null);
+ return {
+ count,
+ rps: durationSec ? count / durationSec : null,
+ avg: lat('avg'),
+ p50: lat('p(50)'),
+ p90: lat('p(90)'),
+ p95: lat('p(95)'),
+ p99: lat('p(99)'),
+ max: lat('max'),
+ errorRate: count ? value(data, sub('http_req_failed', tags), 'rate', 0) : null,
+ };
+}
+
+function change(current, previous) {
+ if (current === null || current === undefined || !previous) return null;
+ return (current - previous) / previous;
+}
+
+// The throughput phase: overall, reads vs writes, and every catalogue endpoint.
+function performance(data, ctx) {
+ if (!ctx.runThroughput) return null;
+ const { cfg, sub } = ctx;
+ const sec = ctx.throughputSec;
+ const setup = data.setup_data || {};
+ const baseline = ctx.baseline && Array.isArray(ctx.baseline.endpoints) ? ctx.baseline : null;
+ const baselineByEndpoint = {};
+ (baseline ? baseline.endpoints : []).forEach((row) => (baselineByEndpoint[row.endpoint] = row));
+ const budget = (kind) => (kind === 'read' ? cfg.readP95 : cfg.writeP95);
+
+ const endpoints = (ctx.loadRows || [])
+ .map((row) => {
+ const st = stats(data, sub, { role: 'load', endpoint: row.endpoint }, sec);
+ const prev = baselineByEndpoint[row.endpoint];
+ return Object.assign({ op: row.op, kind: row.kind, endpoint: row.endpoint }, st, {
+ skipped: (setup.skipped && setup.skipped[row.op]) || null,
+ overBudget: st.p95 !== null && st.p95 > budget(row.kind),
+ p95Change: prev ? change(st.p95, prev.p95) : null,
+ p99Change: prev ? change(st.p99, prev.p99) : null,
+ });
+ })
+ .sort((a, b) => (b.p95 || -1) - (a.p95 || -1));
+
+ const scope = (label, tags) => {
+ const st = stats(data, sub, tags, sec);
+ const key = tags.kind || 'overall';
+ const prev = baseline && baseline[key];
+ return Object.assign({ label, key }, st, {
+ baselineP95: prev ? prev.p95 : null,
+ p95Change: prev ? change(st.p95, prev.p95) : null,
+ p99Change: prev ? change(st.p99, prev.p99) : null,
+ });
+ };
+
+ return {
+ overall: scope('All requests', { role: 'load' }),
+ read: scope('Reads', { role: 'load', kind: 'read' }),
+ write: scope('Writes', { role: 'load', kind: 'write' }),
+ endpoints: endpoints.filter((row) => row.count > 0),
+ skipped: endpoints.filter((row) => row.count === 0).map((row) => ({ endpoint: row.endpoint, reason: row.skipped || 'no requests' })),
+ baselineVersion: baseline ? baseline.version : null,
+ budgets: { read: cfg.readP95, write: cfg.writeP95, enforced: cfg.enforceBudgets },
+ };
+}
+
+// The latency regression gate: aggregate read and write p95 against the previous release.
+// Evaluated here (the baseline is only known at summary time) and handed to the workflow
+// as gate.json; k6 thresholds cannot compare against a previous run.
+function regressionGate(perf, cfg) {
+ const base = { maxRegression: cfg.maxRegression, minRegressionMs: cfg.minRegressionMs };
+ if (!perf) return Object.assign(base, { evaluated: false, regressed: false, reason: 'throughput phase did not run', checks: [] });
+ if (!perf.baselineVersion) return Object.assign(base, { evaluated: false, regressed: false, reason: 'no previous release metrics to compare against', checks: [] });
+
+ const checks = [perf.read, perf.write]
+ .filter((row) => row.count > 0 && row.p95 !== null && row.baselineP95)
+ .map((row) => {
+ const deltaMs = row.p95 - row.baselineP95;
+ return {
+ scope: row.label,
+ p95: row.p95,
+ baselineP95: row.baselineP95,
+ change: row.p95Change,
+ deltaMs,
+ regressed: row.p95Change > cfg.maxRegression && deltaMs > cfg.minRegressionMs,
+ };
+ });
+
+ return Object.assign(base, {
+ evaluated: checks.length > 0,
+ regressed: checks.some((check) => check.regressed),
+ reason: checks.length ? null : 'no comparable read or write traffic',
+ baselineVersion: perf.baselineVersion,
+ checks,
+ });
+}
+
+// Compact per-release metrics: published with the release so the next one can compare.
+function metricsDocument(r) {
+ const strip = (row) => ({ count: row.count, rps: row.rps, avg: row.avg, p50: row.p50, p90: row.p90, p95: row.p95, p99: row.p99, max: row.max, errorRate: row.errorRate });
+ return {
+ version: r.meta.version,
+ sha: r.meta.sha,
+ startedAt: r.meta.startedAt,
+ overall: r.perf ? strip(r.perf.overall) : null,
+ read: r.perf ? strip(r.perf.read) : null,
+ write: r.perf ? strip(r.perf.write) : null,
+ endpoints: r.perf ? r.perf.endpoints.map((row) => Object.assign({ endpoint: row.endpoint, kind: row.kind }, strip(row))) : [],
+ };
+}
+
+function delta(v) {
+ if (v === null || v === undefined || Number.isNaN(v)) return '–';
+ const sign = v > 0 ? '+' : '';
+ const text = `${sign}${(v * 100).toFixed(Math.abs(v) < 0.1 ? 1 : 0)}%`;
+ if (v >= 0.2) return `🔺 ${text}`;
+ if (v <= -0.2) return `🟢 ${text}`;
+ return text;
+}
+
+// Collect everything both renderers need, once.
+function collect(data, ctx) {
+ const { cfg, rows, gates, sub } = ctx;
+ const activeSec = { load: ctx.throughputSec, noisy: cfg.noisySec, victim: ctx.bystanderSec, public: ctx.bystanderSec };
+
+ const endpointRows = rows.map((row) => {
+ const tags = { role: row.role, endpoint: row.endpoint };
+ const count = value(data, sub('http_reqs', tags), 'count', 0);
+ const lat = (stat) => (count ? value(data, sub('http_req_duration', tags), stat) : null);
+ return {
+ role: row.role,
+ op: row.op,
+ endpoint: row.endpoint,
+ count,
+ rps: activeSec[row.role] ? count / activeSec[row.role] : null,
+ p50: lat('p(50)'),
+ p95: lat('p(95)'),
+ p99: lat('p(99)'),
+ max: lat('max'),
+ throttled: row.role === 'noisy' ? value(data, sub('noisy_throttled', { op: row.op }), 'count', 0) : null,
+ errorRate: count ? value(data, sub('http_req_failed', tags), 'rate', 0) : null,
+ };
+ });
+
+ const thresholdRows = [];
+ gates.forEach((name) => {
+ const m = metric(data, name);
+ const results = (m && m.thresholds) || {};
+ const exprs = Object.keys(results);
+ if (!exprs.length) {
+ thresholdRows.push({ name, expr: '(no data)', ok: false, observed: '–' });
+ }
+ exprs.forEach((expr) => {
+ thresholdRows.push({ name, expr, ok: results[expr].ok !== false, observed: observed(m, expr) });
+ });
+ });
+
+ const iso = ctx.runNoisy
+ ? {
+ noisyRequests: value(data, 'noisy_requests', 'count', 0),
+ noisyThrottled: value(data, 'noisy_throttled', 'count', 0),
+ missingRetryAfter: value(data, 'noisy_429_missing_retry_after', 'count', 0),
+ missingRateHeaders: value(data, 'noisy_429_missing_ratelimit_headers', 'count', 0),
+ victimRequests: value(data, 'victim_requests', 'count', 0),
+ victimThrottled: value(data, 'victim_throttled', 'count', 0),
+ publicRequests: value(data, 'public_probe_requests', 'count', 0),
+ publicThrottled: value(data, 'public_probe_throttled', 'count', 0),
+ }
+ : null;
+ if (iso) {
+ iso.limiterEngaged = iso.noisyThrottled > 0 && iso.missingRetryAfter === 0;
+ iso.victimIsolated = iso.victimRequests > 0 && iso.victimThrottled === 0;
+ iso.publicIsolated = iso.publicRequests > 0 && iso.publicThrottled === 0;
+ iso.pass = iso.limiterEngaged && iso.victimIsolated && iso.publicIsolated;
+ }
+
+ const setup = data.setup_data || {};
+ const checks = metric(data, 'checks');
+
+ const perf = performance(data, ctx);
+
+ return {
+ perf,
+ gate: regressionGate(perf, cfg),
+ meta: {
+ version: cfg.version,
+ sha: cfg.sha,
+ shortSha: cfg.sha ? cfg.sha.slice(0, 12) : '',
+ ref: cfg.ref,
+ runUrl: cfg.runUrl,
+ baseUrl: cfg.baseUrl,
+ startedAt: setup.startedAt || '',
+ setupCompleted: Boolean(data.setup_data),
+ durationSec: data.state && data.state.testRunDurationMs ? data.state.testRunDurationMs / 1000 : null,
+ // What the limiter actually advertised to the NOISY key beats what the mint predicted.
+ rateLimit: (setup.throttle && setup.throttle.noisyLimit) || cfg.rateLimit || '',
+ throttleActive: setup.throttle ? setup.throttle.active : undefined,
+ loadBypassed: setup.throttle ? setup.throttle.loadBypassed : undefined,
+ },
+ config: configRows(ctx),
+ endpointRows,
+ thresholdRows,
+ allPass: thresholdRows.every((t) => t.ok),
+ iso,
+ totals: {
+ requests: value(data, 'http_reqs', 'count', 0),
+ failed: value(data, 'http_req_failed', 'rate', 0),
+ dropped: value(data, 'dropped_iterations', 'count', 0),
+ checksPass: checks ? checks.values.passes : null,
+ checksFail: checks ? checks.values.fails : null,
+ },
+ };
+}
+
+function observed(m, expr) {
+ if (!m || !m.values) return '–';
+ const match = /^\s*([a-z]+(?:\(\d+(?:\.\d+)?\))?)/.exec(expr);
+ if (!match) return '–';
+ const key = match[1];
+ const v = m.values[key];
+ if (v === undefined) return '–';
+ if (m.type === 'trend') return ms(v);
+ if (m.type === 'rate') return pct(v);
+ return int(v);
+}
+
+function configRows(ctx) {
+ const { cfg } = ctx;
+ const rows = [['Base URL', cfg.baseUrl]];
+ if (ctx.runThroughput) {
+ rows.push(['Throughput', `ramping arrival rate to ${cfg.peakRate} req/s over ${cfg.throughputSec}s (${cfg.throughputVUs}–${cfg.throughputMaxVUs} VUs)`]);
+ rows.push(['Endpoints', 'weighted catalogue across orders, places, contacts, drivers, vehicles, fleets, vendors, service areas/rates, issues and fuel reports']);
+ rows.push(['Latency budget (p95)', `reads < ${cfg.readP95} ms, writes < ${cfg.writeP95} ms`]);
+ } else {
+ rows.push(['Throughput', 'skipped']);
+ }
+ if (ctx.runNoisy) {
+ rows.push(['Noisy flood', `${cfg.noisyRate} req/s for ${cfg.noisySec}s (create/update)`]);
+ rows.push(['Victim', `${cfg.victimRate} req/s for ${ctx.bystanderSec}s, starting ${cfg.noisyWarmupSec}s into the flood`]);
+ rows.push(['Public probe', `GET ${cfg.publicProbePath} every ${cfg.publicProbeEverySec}s, anonymous`]);
+ } else {
+ rows.push(['Noisy neighbour', 'skipped']);
+ }
+ rows.push(['Max error rate', pct(cfg.maxErrorRate) + ' (expected 429s on the noisy tenant excluded)']);
+ return rows;
+}
+
+/* ------------------------------------------------------------------------- */
+
+function markdown(r) {
+ const out = [];
+ const badge = (ok) => (ok ? '✅ PASS' : '❌ FAIL');
+ out.push(`# Fleetbase API performance — ${r.meta.version}`);
+ out.push('');
+ const facts = [];
+ if (r.perf) {
+ facts.push(`**p95:** ${ms(r.perf.overall.p95)}`);
+ facts.push(`**p99:** ${ms(r.perf.overall.p99)}`);
+ facts.push(`**Throughput:** ${fixed(r.perf.overall.rps, 1)} req/s`);
+ facts.push(`**Errors:** ${pct(r.perf.overall.errorRate)}`);
+ }
+ facts.push(`**Thresholds:** ${badge(r.allPass)}`);
+ if (r.iso) facts.push(`**Rate-limit isolation:** ${badge(r.iso.pass)}`);
+ out.push(facts.join(' · '));
+ out.push('');
+ if (!r.meta.setupCompleted) {
+ out.push('> ⚠️ `setup()` did not complete (timed out or aborted), so no scenario traffic was generated. See the k6 log.');
+ out.push('');
+ }
+ const meta = [];
+ meta.push(['Release', `\`${r.meta.version}\``]);
+ if (r.meta.sha) meta.push(['Commit', `\`${r.meta.shortSha}\``]);
+ if (r.meta.ref) meta.push(['Ref', `\`${r.meta.ref}\``]);
+ if (r.meta.startedAt) meta.push(['Started', r.meta.startedAt]);
+ if (r.meta.durationSec) meta.push(['Duration', `${Math.round(r.meta.durationSec)}s`]);
+ if (r.meta.throttleActive === false) meta.push(['Per-key limit', 'throttling inactive for the NOISY key']);
+ else if (r.meta.rateLimit) meta.push(['Per-key limit', `${r.meta.rateLimit} req/min`]);
+ if (r.meta.runUrl) meta.push(['Run', `[workflow run](${r.meta.runUrl})`]);
+ out.push('| | |');
+ out.push('|---|---|');
+ meta.forEach(([k, v]) => out.push(`| ${k} | ${v} |`));
+ out.push('');
+
+ if (r.perf) {
+ const p = r.perf;
+ const vs = p.baselineVersion ? ` vs ${p.baselineVersion}` : '';
+ out.push('## Performance');
+ out.push('');
+ out.push('| Scope | Requests | req/s | avg | p50 | p90 | p95 | p99 | max | Errors |' + (p.baselineVersion ? ` p95${vs} | p99${vs} |` : ''));
+ out.push('|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|' + (p.baselineVersion ? '---:|---:|' : ''));
+ [p.overall, p.read, p.write].forEach((row) => {
+ const cmp = p.baselineVersion ? ` ${delta(row.p95Change)} | ${delta(row.p99Change)} |` : '';
+ out.push(`| **${row.label}** | ${int(row.count)} | ${fixed(row.rps, 2)} | ${ms(row.avg)} | ${ms(row.p50)} | ${ms(row.p90)} | ${ms(row.p95)} | ${ms(row.p99)} | ${ms(row.max)} | ${pct(row.errorRate)} |${cmp}`);
+ });
+ out.push('');
+ out.push(`### Endpoints (slowest p95 first)`);
+ out.push('');
+ out.push('| Endpoint | Requests | req/s | p50 | p90 | p95 | p99 | max | Errors |' + (p.baselineVersion ? ` p95${vs} |` : '') + ' Budget |');
+ out.push('|---|---:|---:|---:|---:|---:|---:|---:|---:|' + (p.baselineVersion ? '---:|' : '') + '---|');
+ p.endpoints.forEach((row) => {
+ const cmp = p.baselineVersion ? ` ${delta(row.p95Change)} |` : '';
+ out.push(
+ `| \`${mdCell(row.endpoint)}\` | ${int(row.count)} | ${fixed(row.rps, 2)} | ${ms(row.p50)} | ${ms(row.p90)} | ${ms(row.p95)} | ${ms(row.p99)} | ${ms(row.max)} | ${pct(row.errorRate)} |${cmp} ${row.overBudget ? '⚠️ over' : '✓'} |`
+ );
+ });
+ out.push('');
+ out.push(
+ `_Budgets (p95): reads < ${p.budgets.read} ms, writes < ${p.budgets.write} ms — ${p.budgets.enforced ? 'enforced: a breach fails the run' : 'report only'}. ` +
+ (p.baselineVersion ? `Changes are against ${p.baselineVersion}; 🔺/🟢 mark a change of 20% or more._` : 'No previous release metrics were available to compare against._')
+ );
+ out.push('');
+ if (p.skipped.length) {
+ out.push('**Not measured:** ' + p.skipped.map((row) => `\`${mdCell(row.endpoint)}\` (${row.reason})`).join(', '));
+ out.push('');
+ }
+ }
+
+ if (r.gate) {
+ const g = r.gate;
+ const limits = `more than ${Math.round(g.maxRegression * 100)}% and more than ${g.minRegressionMs} ms slower p95`;
+ if (!g.evaluated) {
+ out.push(`### Regression gate — not evaluated`);
+ out.push('');
+ out.push(`_${g.reason}._`);
+ } else {
+ out.push(`### Regression gate vs ${g.baselineVersion} — ${g.regressed ? '❌ REGRESSED' : '✅ PASS'}`);
+ out.push('');
+ out.push('| Scope | p95 | Baseline p95 | Change | Result |');
+ out.push('|---|---:|---:|---:|---|');
+ g.checks.forEach((c) => out.push(`| ${c.scope} | ${ms(c.p95)} | ${ms(c.baselineP95)} | ${delta(c.change)} (${c.deltaMs >= 0 ? '+' : ''}${ms(c.deltaMs)}) | ${c.regressed ? '❌ regressed' : '✅ ok'} |`));
+ out.push('');
+ out.push(`_A scope regresses when it is ${limits} than the previous release. On a release PR a regression is re-measured once before it fails the check._`);
+ }
+ out.push('');
+ }
+
+ const sections = [...new Set(r.endpointRows.map((row) => row.role))];
+ if (sections.length) {
+ out.push('## Rate-limit isolation traffic');
+ out.push('');
+ }
+ sections.forEach((role) => {
+ out.push(`### ${ROLE_LABEL[role] || role}`);
+ out.push('');
+ const noisy = role === 'noisy';
+ out.push(`| Endpoint | Requests | req/s | p50 | p95 | p99 | max | Errors |${noisy ? ' 429s |' : ''}`);
+ out.push(`|---|---:|---:|---:|---:|---:|---:|---:|${noisy ? '---:|' : ''}`);
+ r.endpointRows
+ .filter((row) => row.role === role)
+ .forEach((row) => {
+ const extra = noisy ? ` ${int(row.throttled)} |` : '';
+ out.push(
+ `| \`${mdCell(row.endpoint)}\` | ${int(row.count)} | ${fixed(row.rps, 2)} | ${ms(row.p50)} | ${ms(row.p95)} | ${ms(row.p99)} | ${ms(row.max)} | ${pct(row.errorRate)} |${extra}`
+ );
+ });
+ if (role === 'noisy') {
+ out.push('');
+ out.push('_Noisy errors exclude the expected 429 responses (the 429s column); latencies include them._');
+ }
+ out.push('');
+ });
+
+ if (r.iso) {
+ const i = r.iso;
+ out.push(`### Isolation result — ${badge(i.pass)}`);
+ out.push('');
+ out.push('One tenant floods the API far above its per-key limit while a second tenant and an anonymous console visitor keep working. Only the flooding tenant may be throttled.');
+ out.push('');
+ out.push('| Check | Observed | Result |');
+ out.push('|---|---|---|');
+ out.push(`| Noisy tenant is throttled | ${int(i.noisyThrottled)} of ${int(i.noisyRequests)} requests got 429 (${pct(i.noisyRequests ? i.noisyThrottled / i.noisyRequests : 0)}) | ${badge(i.noisyThrottled > 0)} |`);
+ out.push(`| Every 429 carries \`Retry-After\` | ${int(i.missingRetryAfter)} missing | ${badge(i.missingRetryAfter === 0)} |`);
+ out.push(`| Every 429 carries \`X-RateLimit-*\` | ${int(i.missingRateHeaders)} missing | ${i.missingRateHeaders === 0 ? '✅ PASS' : '⚠️ WARN'} |`);
+ out.push(`| Victim tenant never throttled | ${int(i.victimThrottled)} × 429 in ${int(i.victimRequests)} requests | ${badge(i.victimIsolated)} |`);
+ out.push(`| Anonymous console route never throttled | ${int(i.publicThrottled)} × 429 in ${int(i.publicRequests)} requests | ${badge(i.publicIsolated)} |`);
+ out.push('');
+ }
+
+ out.push(`## Thresholds — ${badge(r.allPass)}`);
+ out.push('');
+ out.push('| Metric | Threshold | Observed | Result |');
+ out.push('|---|---|---:|---|');
+ r.thresholdRows.forEach((t) => out.push(`| \`${mdCell(t.name)}\` | \`${mdCell(t.expr)}\` | ${t.observed} | ${badge(t.ok)} |`));
+ out.push('');
+
+ out.push('## Run');
+ out.push('');
+ out.push('| | |');
+ out.push('|---|---|');
+ r.config.forEach(([k, v]) => out.push(`| ${k} | ${mdCell(v)} |`));
+ out.push(`| Total requests | ${int(r.totals.requests)} (failed ${pct(r.totals.failed)}) |`);
+ if (r.totals.dropped) out.push(`| Dropped iterations | ${int(r.totals.dropped)} (the API could not keep up with the arrival rate) |`);
+ if (r.totals.checksPass !== null) out.push(`| Checks | ${int(r.totals.checksPass)} passed, ${int(r.totals.checksFail)} failed |`);
+ out.push('');
+ return out.join('\n');
+}
+
+/* ------------------------------------------------------------------------- */
+
+function html(r) {
+ const badge = (ok, warn) => `<span class="badge ${ok ? 'pass' : warn ? 'warn' : 'fail'}">${ok ? 'PASS' : warn ? 'WARN' : 'FAIL'}</span>`;
+ const parts = [];
+ const sections = [...new Set(r.endpointRows.map((row) => row.role))];
+ const maxP95 = Math.max(1, ...r.endpointRows.map((row) => row.p95 || 0));
+
+ parts.push(`<header><p class="eyebrow">Fleetbase API performance</p><h1>${esc(r.meta.version)}</h1>`);
+ parts.push('<div class="summary">');
+ if (r.perf) {
+ parts.push(`<div class="tile"><span>p95</span><strong>${ms(r.perf.overall.p95)}</strong></div>`);
+ parts.push(`<div class="tile"><span>p99</span><strong>${ms(r.perf.overall.p99)}</strong></div>`);
+ parts.push(`<div class="tile"><span>Throughput</span><strong>${fixed(r.perf.overall.rps, 1)} req/s</strong></div>`);
+ }
+ parts.push(`<div class="tile"><span>Thresholds</span>${badge(r.allPass)}</div>`);
+ if (r.iso) parts.push(`<div class="tile"><span>Rate-limit isolation</span>${badge(r.iso.pass)}</div>`);
+ parts.push(`<div class="tile"><span>Requests</span><strong>${int(r.totals.requests)}</strong></div>`);
+ parts.push(`<div class="tile"><span>Failed</span><strong>${pct(r.totals.failed)}</strong></div>`);
+ if (r.meta.throttleActive === false) parts.push('<div class="tile"><span>Per-key limit</span><strong>inactive</strong></div>');
+ else if (r.meta.rateLimit) parts.push(`<div class="tile"><span>Per-key limit</span><strong>${esc(r.meta.rateLimit)}/min</strong></div>`);
+ parts.push('</div>');
+ const meta = [];
+ if (r.meta.sha) meta.push(`commit <code>${esc(r.meta.shortSha)}</code>`);
+ if (r.meta.ref) meta.push(`ref <code>${esc(r.meta.ref)}</code>`);
+ if (r.meta.startedAt) meta.push(esc(r.meta.startedAt));
+ if (r.meta.durationSec) meta.push(`${Math.round(r.meta.durationSec)}s`);
+ if (r.meta.runUrl) meta.push(`<a href="${esc(r.meta.runUrl)}">workflow run</a>`);
+ parts.push(`<p class="meta">${meta.join(' · ')}</p>`);
+ if (!r.meta.setupCompleted) parts.push('<p class="alert"><code>setup()</code> did not complete (timed out or aborted), so no scenario traffic was generated. See the k6 log.</p>');
+ parts.push('</header>');
+
+ if (r.perf) {
+ const p = r.perf;
+ const vs = p.baselineVersion ? ` vs ${esc(p.baselineVersion)}` : '';
+ const maxP95 = Math.max(1, ...p.endpoints.map((row) => row.p95 || 0));
+ parts.push('<section><h2>Performance</h2><div class="scroll"><table>');
+ parts.push(`<thead><tr><th>Scope</th><th class="n">Requests</th><th class="n">req/s</th><th class="n">avg</th><th class="n">p50</th><th class="n">p90</th><th class="n">p95</th><th class="n">p99</th><th class="n">max</th><th class="n">Errors</th>${p.baselineVersion ? `<th class="n">p95${vs}</th><th class="n">p99${vs}</th>` : ''}</tr></thead><tbody>`);
+ [p.overall, p.read, p.write].forEach((row) => {
+ parts.push(
+ `<tr><th scope="row">${esc(row.label)}</th><td class="n">${int(row.count)}</td><td class="n">${fixed(row.rps, 2)}</td><td class="n">${ms(row.avg)}</td><td class="n">${ms(row.p50)}</td><td class="n">${ms(row.p90)}</td><td class="n">${ms(row.p95)}</td><td class="n">${ms(row.p99)}</td><td class="n">${ms(row.max)}</td><td class="n">${pct(row.errorRate)}</td>` +
+ (p.baselineVersion ? `<td class="n">${esc(delta(row.p95Change))}</td><td class="n">${esc(delta(row.p99Change))}</td>` : '') +
+ '</tr>'
+ );
+ });
+ parts.push('</tbody></table></div>');
+ parts.push('<h3>Endpoints (slowest p95 first)</h3><div class="scroll"><table>');
+ parts.push(`<thead><tr><th>Endpoint</th><th class="n">Requests</th><th class="n">req/s</th><th class="n">p50</th><th class="n">p90</th><th class="n">p95</th><th class="n">p99</th><th class="n">max</th><th class="n">Errors</th>${p.baselineVersion ? `<th class="n">p95${vs}</th>` : ''}<th>Budget</th></tr></thead><tbody>`);
+ p.endpoints.forEach((row) => {
+ const width = row.p95 ? Math.max(2, Math.round((row.p95 / maxP95) * 100)) : 0;
+ parts.push(
+ `<tr><td><code>${esc(row.endpoint)}</code></td><td class="n">${int(row.count)}</td><td class="n">${fixed(row.rps, 2)}</td><td class="n">${ms(row.p50)}</td><td class="n">${ms(row.p90)}</td>` +
+ `<td class="n bar"><span style="--w:${width}%"></span>${ms(row.p95)}</td><td class="n">${ms(row.p99)}</td><td class="n">${ms(row.max)}</td><td class="n${row.errorRate ? ' bad' : ''}">${pct(row.errorRate)}</td>` +
+ (p.baselineVersion ? `<td class="n">${esc(delta(row.p95Change))}</td>` : '') +
+ `<td>${row.overBudget ? '<span class="badge warn">OVER</span>' : '<span class="badge pass">OK</span>'}</td></tr>`
+ );
+ });
+ parts.push('</tbody></table></div>');
+ parts.push(
+ `<p class="note">Budgets (p95): reads &lt; ${p.budgets.read} ms, writes &lt; ${p.budgets.write} ms — ${p.budgets.enforced ? 'enforced' : 'report only'}. ` +
+ (p.baselineVersion ? `Changes are against ${esc(p.baselineVersion)}.` : 'No previous release metrics were available to compare against.') +
+ '</p>'
+ );
+ if (p.skipped.length) {
+ parts.push(`<p class="note">Not measured: ${p.skipped.map((row) => `<code>${esc(row.endpoint)}</code> (${esc(row.reason)})`).join(', ')}</p>`);
+ }
+ parts.push('</section>');
+ }
+
+ sections.forEach((role) => {
+ parts.push(`<section><h2>${esc(ROLE_LABEL[role] || role)}</h2><div class="scroll"><table>`);
+ const noisy = role === 'noisy';
+ parts.push(`<thead><tr><th>Endpoint</th><th class="n">Requests</th><th class="n">req/s</th><th class="n">p50</th><th class="n">p95</th><th class="n">p99</th><th class="n">max</th><th class="n">Errors</th>${noisy ? '<th class="n">429s</th>' : ''}</tr></thead><tbody>`);
+ r.endpointRows
+ .filter((row) => row.role === role)
+ .forEach((row) => {
+ const width = row.p95 ? Math.max(2, Math.round((row.p95 / maxP95) * 100)) : 0;
+ parts.push(
+ `<tr><td><code>${esc(row.endpoint)}</code></td><td class="n">${int(row.count)}</td><td class="n">${fixed(row.rps, 2)}</td><td class="n">${ms(row.p50)}</td>` +
+ `<td class="n bar"><span style="--w:${width}%"></span>${ms(row.p95)}</td><td class="n">${ms(row.p99)}</td><td class="n">${ms(row.max)}</td>` +
+ `<td class="n${row.errorRate ? ' bad' : ''}">${pct(row.errorRate)}</td>${noisy ? `<td class="n">${int(row.throttled)}</td>` : ''}</tr>`
+ );
+ });
+ parts.push('</tbody></table></div>');
+ if (role === 'noisy') parts.push('<p class="note">Noisy errors exclude the expected 429 responses (the 429s column); latencies include them.</p>');
+ parts.push('</section>');
+ });
+
+ if (r.iso) {
+ const i = r.iso;
+ parts.push(`<section><h2>Rate-limit isolation ${badge(i.pass)}</h2>`);
+ parts.push('<p class="note">One tenant floods the API far above its per-key limit while a second tenant and an anonymous console visitor keep working. Only the flooding tenant may be throttled.</p>');
+ parts.push('<div class="scroll"><table><thead><tr><th>Check</th><th>Observed</th><th>Result</th></tr></thead><tbody>');
+ const rows = [
+ ['Noisy tenant is throttled', `${int(i.noisyThrottled)} of ${int(i.noisyRequests)} requests got 429 (${pct(i.noisyRequests ? i.noisyThrottled / i.noisyRequests : 0)})`, badge(i.noisyThrottled > 0)],
+ ['Every 429 carries <code>Retry-After</code>', `${int(i.missingRetryAfter)} missing`, badge(i.missingRetryAfter === 0)],
+ ['Every 429 carries <code>X-RateLimit-*</code>', `${int(i.missingRateHeaders)} missing`, badge(i.missingRateHeaders === 0, true)],
+ ['Victim tenant never throttled', `${int(i.victimThrottled)} × 429 in ${int(i.victimRequests)} requests`, badge(i.victimIsolated)],
+ ['Anonymous console route never throttled', `${int(i.publicThrottled)} × 429 in ${int(i.publicRequests)} requests`, badge(i.publicIsolated)],
+ ];
+ rows.forEach(([a, b, c]) => parts.push(`<tr><td>${a}</td><td>${b}</td><td>${c}</td></tr>`));
+ parts.push('</tbody></table></div></section>');
+ }
+
+ parts.push(`<section><h2>Thresholds ${badge(r.allPass)}</h2><div class="scroll"><table><thead><tr><th>Metric</th><th>Threshold</th><th class="n">Observed</th><th>Result</th></tr></thead><tbody>`);
+ r.thresholdRows.forEach((t) => parts.push(`<tr><td><code>${esc(t.name)}</code></td><td><code>${esc(t.expr)}</code></td><td class="n">${esc(t.observed)}</td><td>${badge(t.ok)}</td></tr>`));
+ parts.push('</tbody></table></div></section>');
+
+ parts.push('<section><h2>Run</h2><div class="scroll"><table><tbody>');
+ r.config.forEach(([k, v]) => parts.push(`<tr><th scope="row">${esc(k)}</th><td>${esc(v)}</td></tr>`));
+ if (r.totals.dropped) parts.push(`<tr><th scope="row">Dropped iterations</th><td>${int(r.totals.dropped)} (the API could not keep up with the arrival rate)</td></tr>`);
+ if (r.totals.checksPass !== null) parts.push(`<tr><th scope="row">Checks</th><td>${int(r.totals.checksPass)} passed, ${int(r.totals.checksFail)} failed</td></tr>`);
+ parts.push('</tbody></table></div></section>');
+
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>API Performance ${esc(r.meta.version)}</title>
+<style>
+:root{--bg:#f7f7f5;--card:#fff;--fg:#1b1d21;--muted:#646973;--line:#e3e4e8;--pass:#157347;--pass-bg:#e3f4ea;--fail:#b42318;--fail-bg:#fde8e7;--warn:#8a5a00;--warn-bg:#fdf1d8;--bar:#c9d6f2}
+@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121316;--card:#1b1d21;--fg:#e8e9ec;--muted:#9aa0aa;--line:#2c2f36;--pass:#5fd394;--pass-bg:#15351f;--fail:#ff8a80;--fail-bg:#3d1714;--warn:#ffc861;--warn-bg:#3a2c0b;--bar:#2e3d63}}
+:root[data-theme="dark"]{--bg:#121316;--card:#1b1d21;--fg:#e8e9ec;--muted:#9aa0aa;--line:#2c2f36;--pass:#5fd394;--pass-bg:#15351f;--fail:#ff8a80;--fail-bg:#3d1714;--warn:#ffc861;--warn-bg:#3a2c0b;--bar:#2e3d63}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
+main{max-width:1040px;margin:0 auto;padding:32px 16px 64px}
+header{margin-bottom:24px}.eyebrow{margin:0;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;font-size:12px}
+h1{margin:4px 0 16px;font-size:28px}h3{font-size:14px;margin:18px 0 8px}h2{font-size:17px;margin:0 0 12px;display:flex;gap:10px;align-items:center}
+.summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}
+.tile{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:6px;align-items:flex-start}
+.tile span{color:var(--muted);font-size:12px}.tile strong{font-size:18px}
+.meta{color:var(--muted);margin:14px 0 0}
+section{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px;margin-top:16px}
+.scroll{overflow-x:auto}table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}
+th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);white-space:nowrap}
+thead th{color:var(--muted);font-weight:600;font-size:12px}tbody tr:last-child>*{border-bottom:0}
+tbody th{color:var(--muted);font-weight:500;width:1%}td.n,th.n{text-align:right}td.bad{color:var(--fail);font-weight:600}
+td.bar{position:relative}td.bar span{position:absolute;right:0;top:50%;transform:translateY(-50%);height:60%;width:var(--w);background:var(--bar);border-radius:3px;z-index:-1;opacity:.6}
+td.bar{isolation:isolate}
+code{font:12.5px ui-monospace,SFMono-Regular,Menlo,monospace}
+.badge{display:inline-block;padding:1px 8px;border-radius:999px;font-size:12px;font-weight:700;letter-spacing:.03em}
+.pass{color:var(--pass);background:var(--pass-bg)}.fail{color:var(--fail);background:var(--fail-bg)}.warn{color:var(--warn);background:var(--warn-bg)}
+.note{color:var(--muted);margin:8px 0 0;font-size:13px}.alert{margin:14px 0 0;padding:10px 14px;border-radius:8px;color:var(--fail);background:var(--fail-bg)}a{color:inherit}
+</style>
+</head>
+<body><main>
+${parts.join('\n')}
+</main></body>
+</html>
+`;
+}
+
+export function buildReports(data, ctx) {
+ const r = collect(data, ctx);
+ return { markdown: markdown(r), html: html(r), metrics: metricsDocument(r), gate: r.gate, result: r };
+}