#!/usr/bin/env bash
# Time two-step workflows with N ms of added delay on each direction of the
# scheduler <-> PostgreSQL link. Usage: latency.sh "0 5 20 40"
set -euo pipefail
LAB=$(cd "$(dirname "$0")" && pwd)
TOX=http://127.0.0.1:8474/proxies/pg/toxics
for MS in $1; do
  for t in lat_up lat_down; do curl -s -o /dev/null -X DELETE "$TOX/$t" || true; done
  if [ "$MS" != "0" ]; then
    curl -s -o /dev/null -X POST "$TOX" -d "{\"name\":\"lat_up\",\"type\":\"latency\",\"stream\":\"upstream\",\"attributes\":{\"latency\":$MS}}"
    curl -s -o /dev/null -X POST "$TOX" -d "{\"name\":\"lat_down\",\"type\":\"latency\",\"stream\":\"downstream\",\"attributes\":{\"latency\":$MS}}"
  fi
  RUN="lat${MS}x$(date +%s)"
  for i in 1 2 3 4 5 6 7 8 9 10; do
    "$LAB/submit.sh" "$RUN-$i" lab-add pure.add '[1,2,3]' >/dev/null
    until [ "$("$LAB/psql.sh" -At -c "SELECT state FROM engine.workflow_executions WHERE workflow_id='$RUN-$i'")" = "SUCCEEDED" ]; do sleep 0.3; done
  done
  # Duration comes from the engine's own history timestamps (database clock), not from this script's polling.
  "$LAB/psql.sh" -At -F ' ' -c "WITH d AS (SELECT workflow_id, extract(epoch FROM max(created_at)-min(created_at))*1000 AS ms
      FROM engine.transition_history WHERE workflow_id LIKE '$RUN-%' GROUP BY 1)
    SELECT '+${MS}ms each way (round trip +$((MS*2))ms): n=' || count(*), 'min=' || round(min(ms)::numeric) || 'ms',
      'median=' || round((percentile_cont(0.5) WITHIN GROUP (ORDER BY ms))::numeric) || 'ms', 'max=' || round(max(ms)::numeric) || 'ms' FROM d"
done
for t in lat_up lat_down; do curl -s -o /dev/null -X DELETE "$TOX/$t" || true; done
