#!/usr/bin/env bash
# Layer 8: hyper-tps Integration — Swarm Join + Host Election + RPC Round-Trip
# Tests the exact flow hyper-tps will use after sidecar elimination.
# 3 peers: swarm_join auto-connect → host election → game RPCs
set -euo pipefail
cd "$(dirname "$0")"
echo "=== Layer 8: hyper-tps Integration ==="
# Cleanup
rm -f /tmp/layer8_peer_*.txt /tmp/layer_bootstrap.txt
# Process tracking
PIDS=()
TESTNET_PID=""
cleanup() {
for pid in "${PIDS[@]}" "$TESTNET_PID"; do
[ -n "$pid" ] && kill "$pid" 2>/dev/null || true
[ -n "$pid" ] && pkill -P "$pid" 2>/dev/null || true
done
sleep 0.5
for pid in "${PIDS[@]}" "$TESTNET_PID"; do
[ -n "$pid" ] && kill -9 "$pid" 2>/dev/null || true
[ -n "$pid" ] && pkill -9 -P "$pid" 2>/dev/null || true
done
wait 2>/dev/null || true
rm -f /tmp/layer8_*.txt /tmp/layer_bootstrap.txt
}
trap cleanup EXIT
# Start testnet
echo "[orchestrator] starting DHT testnet..."
node layer2_testnet.js &
TESTNET_PID=$!
# Wait for bootstrap
for i in $(seq 1 30); do
[ -f /tmp/layer_bootstrap.txt ] && break
sleep 0.2
done
[ -f /tmp/layer_bootstrap.txt ] || { echo "FAIL: testnet timeout"; exit 1; }
echo "[orchestrator] testnet ready"
# Project dirs for each peer
DIRS=(project project_b project_c)
# Start 3 peers
for i in 0 1 2; do
echo "[orchestrator] starting peer $i (${DIRS[$i]})..."
timeout -k 10 90 godot4 --headless --path "${DIRS[$i]}" --script res://layer8_hypertps.gd -- --peer-index $i 2>&1 | sed "s/^/ /" &
PIDS+=($!)
sleep 0.5
done
# Wait for all peers to complete (PASS status)
echo "[orchestrator] waiting for all peers to complete (max 60s)..."
ELAPSED=0
while [ $ELAPSED -lt 60 ]; do
ALL_PASS=true
ANY_FAIL=false
for i in 0 1 2; do
STATUS=$(cat /tmp/layer8_peer_${i}_status.txt 2>/dev/null || echo "")
if echo "$STATUS" | grep -q "^FAIL"; then
ANY_FAIL=true
echo "[orchestrator] Peer $i FAILED: $STATUS"
fi
if [ "$STATUS" != "PASS" ] && ! echo "$STATUS" | grep -q "^FAIL"; then
ALL_PASS=false
fi
done
if $ANY_FAIL; then
echo ""
for i in 0 1 2; do
echo "Peer $i: $(cat /tmp/layer8_peer_${i}_status.txt 2>/dev/null || echo 'no status')"
done
echo "=== Layer 8: FAILED ==="
for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null || true; done
exit 1
fi
if $ALL_PASS; then
break
fi
sleep 1
ELAPSED=$((ELAPSED + 1))
done
# Report results
echo ""
for i in 0 1 2; do
echo "Peer $i: $(cat /tmp/layer8_peer_${i}_status.txt 2>/dev/null || echo 'no status')"
done
# Check election consistency
HOST0=$(cat /tmp/layer8_peer_0_host.txt 2>/dev/null || echo "?")
HOST1=$(cat /tmp/layer8_peer_1_host.txt 2>/dev/null || echo "?")
HOST2=$(cat /tmp/layer8_peer_2_host.txt 2>/dev/null || echo "?")
if [ "$HOST0" = "$HOST1" ] && [ "$HOST1" = "$HOST2" ]; then
echo "Election: consistent (host=${HOST0:0:12}...)"
else
echo "Election: INCONSISTENT (${HOST0:0:12} vs ${HOST1:0:12} vs ${HOST2:0:12})"
fi
# Final verdict
if $ALL_PASS; then
echo "=== Layer 8: PASS ==="
else
echo "=== Layer 8: TIMEOUT ==="
fi
if $ALL_PASS; then
exit 0
else
exit 1
fi