#!/usr/bin/env bash
# Stop PostgreSQL while a 20-second activity is running, poke the API, then bring it back.
# Usage: db-outage.sh <workflow_id>
set -uo pipefail
WF=$1
LAB=$(cd "$(dirname "$0")" && pwd)
ts() { date -u +%H:%M:%S; }
code() { curl -s -m 5 -o /tmp/ddwe-body -w '%{http_code}' "$@"; echo " $(cut -c1-110 /tmp/ddwe-body)"; }

echo "[$(ts)] submit $WF (20s activity)"; "$LAB/submit.sh" "$WF" lab-slow dur048.sleep '"hello"' | tail -1
sleep 5
echo "[$(ts)] stopping postgres with the activity in flight"
"$LAB/dc.sh" stop postgres >/dev/null 2>&1
echo "[$(ts)] GET status      -> $(code http://127.0.0.1:8080/v1/workflows/$WF)"
BODY="{\"workflow_id\":\"$WF-b\",\"namespace\":\"local-runtime\",\"submission_key\":\"$WF-b\",\"definition_id\":\"lab-add\",\"definition_version\":1,\"initial_node_id\":\"pure.add\",\"initial_input\":[1,2,3],\"payload\":{}}"
SUBMIT=$(code -H 'Content-Type: application/json' -X POST http://127.0.0.1:8080/v1/workflows --data "$BODY")
echo "[$(ts)] POST new submit -> $SUBMIT"
echo "[$(ts)] healthz a/b     -> $(code http://127.0.0.1:8080/healthz) | $(code http://127.0.0.1:8081/healthz)"
sleep 30   # the worker finishes its 20s sleep during this window and has nowhere to report
echo "[$(ts)] starting postgres again (outage ~35s)"
"$LAB/dc.sh" start postgres >/dev/null 2>&1
until [ "$("$LAB/psql.sh" -At -c "SELECT state FROM engine.workflow_executions WHERE workflow_id='$WF'" 2>/dev/null)" = "SUCCEEDED" ]; do sleep 1; done
echo "[$(ts)] $WF SUCCEEDED"
"$LAB/psql.sh" -c "SELECT attempt_number AS attempt, state, worker_id FROM engine.activity_attempts WHERE workflow_id='$WF' ORDER BY 1"
echo "[$(ts)] retry the submit that got an error during the outage (same submission_key)"
"$LAB/submit.sh" "$WF-b" lab-add pure.add '[1,2,3]' | tail -1
"$LAB/dc.sh" logs --no-log-prefix worker-a worker-b 2>&1 | grep "$WF " | grep -E 'outcome=' | cut -c1-330
"$LAB/dc.sh" ps --format '{{.Service}} {{.Status}}' | tr '\n' ';'
