#!/bin/sh
# Simulates a Lambda freeze with `docker pause` and checks whether the first invocations after thaw
# see a flag change made while the function was frozen. The function runs in the official Lambda
# Node.js 22 image (Runtime Interface Emulator) with the GO Feature Flag OpenFeature provider in
# in-process mode, polling the relay proxy every 5 seconds, behind a proxy that adds DELAY_MS latency.
# Usage: sh benchmarks/serverless/freeze-test.sh [DELAY_MS] [RUNS]
set -e
DIR=$(cd "$(dirname "$0")" && pwd)
DELAY_MS=${1:-300}
RUNS=${2:-5}
LAMBDA_IMAGE=public.ecr.aws/lambda/nodejs:22
GOFF_IMAGE=gofeatureflag/go-feature-flag:v1.58.1
WORK="$DIR/.work"
mkdir -p "$WORK/goff"
cp "$DIR/goff/goff-proxy.yaml" "$WORK/goff/"
cp "$DIR/goff/flags.template.yaml" "$WORK/goff/flags.yaml"
(cd "$DIR/fn-goff" && npm ci --silent)

cleanup() { docker rm -f -v ff-goff ff-delay ff-fn >/dev/null 2>&1 || true; docker network rm ff-net >/dev/null 2>&1 || true; }
trap cleanup EXIT
cleanup
docker network create ff-net >/dev/null
docker run -d --name ff-goff --network ff-net -v "$WORK/goff:/goff" "$GOFF_IMAGE" >/dev/null
docker run -d --name ff-delay --network ff-net -e TARGET=http://ff-goff:1031 -e DELAY_MS="$DELAY_MS" \
  -v "$DIR/delay:/p" --entrypoint node "$LAMBDA_IMAGE" /p/proxy.mjs >/dev/null
docker run -d --name ff-fn --network ff-net -p 19001:8080 -e GOFF_ENDPOINT=http://ff-delay:8000 \
  -v "$DIR/fn-goff:/var/task" "$LAMBDA_IMAGE" index.handler >/dev/null
sleep 3

inv() { curl -s -XPOST localhost:19001/2015-03-31/functions/function/invocations -d '{"userId":"u1"}' | sed 's/.*"checkout":"\([a-z]*\)".*/\1/'; }
set_variation() { sed -i.bak "s/variation: .*/variation: $1/" "$WORK/goff/flags.yaml"; }

echo "delay_ms=$DELAY_MS runs=$RUNS date=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "run before_freeze sent_while_frozen next+0.2s next+1.2s"
i=1
while [ "$i" -le "$RUNS" ]; do
  set_variation disabled; sleep 8; before=$(inv)
  docker pause ff-fn >/dev/null
  set_variation enabled; sleep 12
  # Send the invocation while frozen, so it is handled as soon as the environment thaws (as in Lambda)
  inv > "$WORK/a0" &
  sleep 0.5
  docker unpause ff-fn >/dev/null
  wait
  a0=$(cat "$WORK/a0"); sleep 0.2; a1=$(inv); sleep 1; a2=$(inv)
  echo "$i $before $a0 $a1 $a2"
  i=$((i + 1))
done
