#!/bin/sh
# Reproduce the slow-receiver webhook dispatch benchmark from
# https://runcycles.io/blog/one-slow-webhook-receiver-stalled-every-tenant
#
# Needs Docker with Compose v2.17+, and compose.yaml plus dispatch.py in this
# directory. On Windows, run it from Git Bash or WSL. The worker images are
# linux/amd64; ARM hosts run them under emulation, which changes timings.
#
#   sh run-benchmark.sh                 # the four published deployments, about 20 minutes
#   sh run-benchmark.sh 0.1.25.32 2 16  # one deployment: release, workers, tenants
#   LOAD_COUNT=160 sh run-benchmark.sh  # shorter trials (8 s of input instead of 60 s)
#
# Each measured trial is appended to my-results.jsonl (override with OUT=...)
# in the same format as the published results, labelled with events_image and
# workers. A deployment fails on a missing, duplicated or out-of-order delivery,
# and the script exits non-zero if any deployment fails or records are missing.
set -eu
cd "$(dirname "$0")"

positive_int() {
  case $1 in ''|0*|*[!0-9]*) return 1 ;; esac
}

LOAD_COUNT=${LOAD_COUNT:-1200}
LOAD_REPEATS=${LOAD_REPEATS:-2}
positive_int "$LOAD_COUNT" || { echo "invalid LOAD_COUNT: $LOAD_COUNT" >&2; exit 2; }
positive_int "$LOAD_REPEATS" || { echo "invalid LOAD_REPEATS: $LOAD_REPEATS" >&2; exit 2; }
export LOAD_COUNT LOAD_REPEATS
OUT=${OUT:-my-results.jsonl}
RUN_ID="$(date +%Y%m%d%H%M%S)-$$"
active=""
child=""

# Stop a running benchmark and remove its containers, volumes, network and
# locally built load image. Returns non-zero if teardown fails.
cleanup() {
  result=0
  if [ -n "$child" ]; then
    kill "$child" 2> /dev/null || true
    wait "$child" 2> /dev/null || true
    child=""
  fi
  if [ -n "$active" ]; then
    if ! docker compose -p "$active" -f compose.yaml down --volumes --rmi local > /dev/null 2>&1; then
      echo "   cleanup of Compose project $active failed; remove it with:" >&2
      echo "   docker compose -p $active -f compose.yaml down --volumes --rmi local" >&2
      result=1
    fi
    active=""
  fi
  return "$result"
}
trap 'cleanup || exit 1' EXIT
trap 'cleanup; exit 130' INT HUP TERM

run() {
  release=$1 workers=$2 tenants=$3
  case $release in ''|*[!0-9.]*) echo "invalid release: $release" >&2; return 2 ;; esac
  positive_int "$workers" || { echo "invalid worker count: $workers" >&2; return 2; }
  positive_int "$tenants" || { echo "invalid tenant count: $tenants" >&2; return 2; }
  if [ "$tenants" -lt 2 ] || [ "$tenants" -gt "$LOAD_COUNT" ]; then
    echo "tenant count must be between 2 and LOAD_COUNT ($LOAD_COUNT): $tenants" >&2
    return 2
  fi

  project="cycles-dispatch-$(echo "$release" | tr -d .)-w$workers-t$tenants-$RUN_ID"
  log="$project.log"
  staged="$project.jsonl"
  echo "== $release, $workers worker(s), $tenants tenants, $LOAD_COUNT deliveries per trial" >&2
  active=$project
  status=0
  # Run Compose in the background so an interrupt reaches the trap immediately.
  EVENTS_IMAGE="ghcr.io/runcycles/cycles-server-events:$release" LOAD_TENANTS=$tenants \
    docker compose -p "$project" -f compose.yaml up --build --scale "worker=$workers" \
      --attach load --exit-code-from load > "$log" 2>&1 &
  child=$!
  wait "$child" || status=$?
  child=""
  teardown=0
  cleanup || teardown=1
  if [ "$status" -ne 0 ]; then
    echo "   failed with exit code $status; see $log" >&2
    return 1
  fi
  [ "$teardown" -eq 0 ] || return 1

  # Keep measured trial records only, labelled with the deployment. Each
  # repeat runs fast then mixed, or mixed then fast on even repeats; every
  # record must be complete and arrive in that order.
  expected=$((LOAD_REPEATS * 2))
  if ! awk -v release="$release" -v workers="$workers" -v expected="$expected" '
    BEGIN {
      # The exact field sequence dispatch.py prints with json.dumps.
      num = "-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][-+]?[0-9]+)?"
      n_fields = split("count target_per_s slow_ms tenants healthy_received_per_s" \
        " healthy_pending_at_last_enqueue offered_per_s completed_per_s" \
        " healthy_p50_ms healthy_p95_ms healthy_p99_ms" \
        " pending_receipt_at_last_enqueue drain_after_input_s", fields, " ")
      shape = "^[{]\"trial\": \"[0-9]+-(fast|mixed)\""
      for (i = 1; i <= n_fields; i++) shape = shape ", \"" fields[i] "\": " num
      shape = shape "[}]$"
    }
    {
      start = index($0, "{\"trial\": ")
      if (start == 0) next
      record = substr($0, start)
      if (index(record, "\"trial\": \"warmup\"")) next
      n++
      repeat = int((n - 1) / 2) + 1
      first = (n % 2 == 1)
      mixed_first = (repeat % 2 == 0)
      label = repeat "-" ((first == mixed_first) ? "mixed" : "fast")
      sub(/[[:space:]]+$/, "", record)
      if (index(record, "{\"trial\": \"" label "\", ") != 1 || record !~ shape) {
        print "   unexpected trial record " n " (wanted " label ")" > "/dev/stderr"
        bad = 1
        exit 1
      }
      print "{\"events_image\": \"" release "\", \"workers\": " workers ", " substr(record, 2)
    }
    END { if (bad) exit 1; if (n != expected) { print "   expected " expected " measured trials but found " n + 0 > "/dev/stderr"; exit 1 } }
  ' "$log" > "$staged"; then
    echo "   see $log" >&2
    return 1
  fi
  if ! cat "$staged" >> "$OUT"; then
    echo "   could not append results to $OUT" >&2
    return 1
  fi
  rm -f "$staged"
  sed -n 's/.*"trial": "\([^"]*\)".*"healthy_p95_ms": \([0-9.]*\).*"drain_after_input_s": \([0-9.]*\).*/   \1: healthy p95 \2 ms, drain \3 s/p' \
    "$OUT" | tail -n "$expected" >&2
}

if [ "$#" -eq 3 ]; then
  run "$1" "$2" "$3"
elif [ "$#" -eq 0 ]; then
  run 0.1.25.27 1 8
  run 0.1.25.32 1 8
  run 0.1.25.32 2 16
  run 0.1.25.27 2 16
else
  echo "usage: sh run-benchmark.sh [release workers tenants]" >&2
  exit 2
fi
echo "Results appended to $OUT" >&2
