1# The events server holds only so many streams open: at most2# FORGE_EVENTS_PER_IP from one address and FORGE_EVENTS_MAX in all for3# anyone not signed in (here 2 and 3); past either, a 503 with4# Retry-After. A stream that closes frees its place.5. "$(dirname "$0")/../lib.sh"6user dami7repo dami/open8: >"$FORGE_ROOT/.forge/events.jsonl"9# Another scenario may take the free port first: then try another.10tries=011while :; do12 port=$(free_port)13 FORGE_STATE=$FORGE_ROOT/.forge FORGE_EVENTS_PORT=$port FORGE_EVENTS_PER_IP=2 FORGE_EVENTS_MAX=3 node "$T_HOME/lib/events-server.ts" >"$T/events.log" 2>&1 &14 pid=$!15 n=016 until grep -q "^events on 127.0.0.1:$port" "$T/events.log" || ! kill -0 "$pid" 2>/dev/null || [ "$n" -ge 100 ]; do sleep 0.1; n=$((n + 1)); done17 if kill -0 "$pid" 2>/dev/null && grep -q '^events on' "$T/events.log"; then break; fi18 kill "$pid" 2>/dev/null || true19 tries=$((tries + 1))20 [ "$tries" -lt 5 ] || fail "the events server did not start"21done22T_PIDS="$T_PIDS $pid"23es=http://127.0.0.1:$port/events24# Streams from an address, held open for a few seconds.25hold() { http -sN --max-time 4 -H "X-Forge-Client-IP: $1" "$es/" >/dev/null & T_PIDS="$T_PIDS $!"; }26code() { http -s -o /dev/null -w '%{http_code}' --max-time 1 -H "X-Forge-Client-IP: $1" "$es/" || true; }27hold 192.0.2.128hold 192.0.2.129sleep 130eq "$(code 192.0.2.1)" 50331hold 192.0.2.232sleep 133# Three open: no more for anyone not signed in.34eq "$(code 192.0.2.3)" 50335http -s -i --max-time 1 -H 'X-Forge-Client-IP: 192.0.2.3' "$es/" | tr -d '\r' >"$T/res" || true36has "$T/res" '^Retry-After: 60$'37# Once they close, there is room again.38sleep 439eq "$(code 192.0.2.1)" 200