Files
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:27:11 +00:00

203 lines
7.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Acceptance check for scale-out: kill a worker in the middle of a job and
# watch the job go back to the queue and get finished by the other worker.
#
# deploy/acceptance/kill-worker.sh # plain processes
# MODE=compose deploy/acceptance/kill-worker.sh # docker compose
#
# Both modes run the real core and two real workers, talking over the HTTP
# worker protocol, with the real yt-dlp downloading a small public test
# file slowly enough to be interrupted. Telegram is replaced by the fake
# server in cmd/faketelegram, so no bot token is needed.
#
# Needs: bash, curl, python3. Process mode also needs go, yt-dlp, ffmpeg.
# Compose mode needs docker compose. Both need internet access for URL.
set -euo pipefail
MODE=${MODE:-process}
URL=${URL:-https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4}
RATE=${RATE:-50K} # download speed limit, so the job lasts a while
FAKE_PORT=${FAKE_PORT:-18090}
CORE_PORT=${CORE_PORT:-18080}
CHAT=4242
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
WORK=$(mktemp -d "${TMPDIR:-/tmp}/dlbot-accept.XXXXXX")
TOKEN_A=dlw_acceptance_token_for_worker_a_000000
TOKEN_B=dlw_acceptance_token_for_worker_b_000000
FAKE="http://127.0.0.1:$FAKE_PORT"
PIDS=()
say() { printf '\n==> %s\n' "$*"; }
fail() { printf '\nFAIL: %s\n' "$*" >&2; dump; exit 1; }
dump() {
if [ "$MODE" = compose ]; then
compose logs --no-color --tail 40 core worker-a worker-b 2>/dev/null || true
else
for f in core worker-a worker-b; do
[ -f "$WORK/$f.log" ] && { echo "--- $f.log (tail)"; tail -n 15 "$WORK/$f.log"; }
done
fi
}
compose() {
WORKER_A_TOKEN=$TOKEN_A WORKER_B_TOKEN=$TOKEN_B RATE=$RATE FAKE_PORT=$FAKE_PORT CORE_PORT=$CORE_PORT \
docker compose -p dlbot-accept --env-file /dev/null \
-f "$ROOT/docker-compose.yml" -f "$ROOT/deploy/acceptance/compose.yml" "$@"
}
cleanup() {
if [ "$MODE" = compose ]; then
compose down -v --remove-orphans >/dev/null 2>&1 || true
else
for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done
wait 2>/dev/null || true
fi
if [ -n "${KEEP:-}" ]; then echo "logs kept in $WORK"; else rm -rf "$WORK"; fi
}
trap cleanup EXIT
# calls <method> prints the fake server's recorded calls as JSON.
calls() { curl -fsS "$FAKE/control/calls?method=$1"; }
# wait_for <seconds> <description> <command...> polls until the command
# prints something, and prints that.
wait_for() {
local secs=$1 what=$2; shift 2
local deadline=$((SECONDS + secs)) out
while [ $SECONDS -lt $deadline ]; do
out=$("$@" 2>/dev/null || true)
if [ -n "$out" ]; then printf '%s' "$out"; return 0; fi
sleep 1
done
fail "timed out after ${secs}s waiting for $what"
}
card_button() { # the "best" button of the newest card
{ calls sendPhoto; calls editMessageText; } | python3 -I -c '
import json, sys
best = None
for line in sys.stdin:
for c in json.loads(line):
for b in c.get("buttons") or []:
if b.startswith("dl:") and b.endswith(":best"):
best = (c["seq"], c["message_id"], b)
if best: print(best[1], best[2])'
}
delivered() { # size of the file the bot sent, if it did
{ calls sendVideo; calls sendDocument; } | python3 -I -c '
import json, sys
for line in sys.stdin:
for c in json.loads(line):
if not c.get("failed") and c.get("files"):
print(list(c["files"].values())[0]); sys.exit()'
}
# busy_worker prints a or b once that worker has started the job.
busy_worker() {
for w in a b; do
if [ "$MODE" = compose ]; then
compose logs --no-color "worker-$w" 2>/dev/null | grep -q 'msg="job started"' && { echo "$w"; return; }
else
grep -q 'msg="job started"' "$WORK/worker-$w.log" 2>/dev/null && { echo "$w"; return; }
fi
done
}
started_count() { # how many times worker $1 started a job
if [ "$MODE" = compose ]; then
compose logs --no-color "worker-$1" 2>/dev/null | grep -c 'msg="job started"' || true
else
grep -c 'msg="job started"' "$WORK/worker-$1.log" 2>/dev/null || true
fi
}
say "mode: $MODE, download: $URL at $RATE/s"
if [ "$MODE" = compose ]; then
say "building and starting core, worker-a, worker-b and the fake Telegram"
compose up -d --build
else
say "building binaries"
(cd "$ROOT" && go build -o "$WORK/bin/" ./cmd/core ./cmd/worker ./cmd/faketelegram)
say "starting the fake Telegram, the core and two workers"
"$WORK/bin/faketelegram" -listen "127.0.0.1:$FAKE_PORT" >"$WORK/fake.log" 2>&1 &
PIDS+=($!)
(cd "$WORK" && exec env -i PATH="$PATH" HOME="$WORK" \
BOT_TOKEN="123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" TELEGRAM_API_URL="$FAKE" \
HTTP_LISTEN="127.0.0.1:$CORE_PORT" DB_DSN="$WORK/core.db" STORAGE_LOCAL_DIR="$WORK/files" \
WORKER_EMBEDDED=false WORKER_TOKENS="worker-a:$TOKEN_A,worker-b:$TOKEN_B" \
QUEUE_LEASE=12s QUEUE_HEARTBEAT=4s LOG_FORMAT=text \
"$WORK/bin/core" >"$WORK/core.log" 2>&1) &
PIDS+=($!)
start_worker() { # name token
(cd "$WORK" && exec env -i PATH="$PATH" HOME="$WORK" \
CORE_URL="http://127.0.0.1:$CORE_PORT" WORKER_TOKEN="$2" WORKER_CONCURRENCY=1 \
WORKER_TEMP_DIR="$WORK/tmp-$1" WORKER_HEARTBEAT=4s WORKER_HEALTH_LISTEN=off \
YTDLP_PATH="${YTDLP_PATH:-yt-dlp}" YTDLP_EXTRA_ARGS="--limit-rate $RATE" YTDLP_AUTO_UPDATE=0 \
LOG_FORMAT=text "$WORK/bin/worker" >"$WORK/worker-$1.log" 2>&1) &
echo $! >"$WORK/worker-$1.pid"
PIDS+=($!)
}
fi
# Fail early when something else already listens on our ports.
if [ "$MODE" != compose ]; then
sleep 1
for pid in "${PIDS[@]}"; do
kill -0 "$pid" 2>/dev/null || fail "a process exited right after start (are ports $FAKE_PORT and $CORE_PORT free?)"
done
fi
wait_for 60 "the fake Telegram" curl -fsS "$FAKE/control/calls?method=getMe" >/dev/null
wait_for 90 "the core to become healthy" curl -fsS "http://127.0.0.1:$CORE_PORT/healthz" >/dev/null
if [ "$MODE" != compose ]; then
start_worker a "$TOKEN_A"
start_worker b "$TOKEN_B"
fi
say "a user sends the link"
curl -fsS -X POST "$FAKE/control/message" -H 'Content-Type: application/json' \
-d "{\"chat_id\": $CHAT, \"user_id\": $CHAT, \"text\": \"$URL\"}" >/dev/null
CARD=$(wait_for 120 "the card (a worker has to look the link up)" card_button)
read -r MSG_ID BUTTON <<<"$CARD"
echo "card is message $MSG_ID, pressing $BUTTON"
say "the user picks Best"
curl -fsS -X POST "$FAKE/control/callback" -H 'Content-Type: application/json' \
-d "{\"chat_id\": $CHAT, \"user_id\": $CHAT, \"message_id\": $MSG_ID, \"data\": \"$BUTTON\"}" >/dev/null
VICTIM=$(wait_for 60 "a worker to start the job" busy_worker)
if [ "$VICTIM" = a ]; then SURVIVOR=b; else SURVIVOR=a; fi
echo "worker-$VICTIM has the job"
sleep 4 # let it get well into the download
say "killing worker-$VICTIM with SIGKILL, mid-download"
if [ "$MODE" = compose ]; then
compose kill -s SIGKILL "worker-$VICTIM"
else
# The worker and the yt-dlp it started: a machine that dies takes both.
WPID=$(cat "$WORK/worker-$VICTIM.pid")
pkill -KILL -P "$WPID" 2>/dev/null || true
kill -KILL "$WPID" 2>/dev/null || true
pkill -KILL -f "$WORK/tmp-$VICTIM" 2>/dev/null || true
fi
[ -z "$(delivered)" ] || fail "the file was delivered before the kill; lower RATE to make the job last longer"
say "waiting for the core to notice, requeue, and for worker-$SURVIVOR to finish the job"
SIZE=$(wait_for 240 "the file to be delivered" delivered)
[ "$(started_count "$SURVIVOR")" -ge 1 ] || fail "worker-$SURVIVOR never started the job"
if [ "$MODE" = compose ]; then
compose logs --no-color core | grep -q 'msg="lease expired"' || fail "the core did not log an expired lease"
else
grep -q 'msg="lease expired"' "$WORK/core.log" || fail "the core did not log an expired lease"
echo
grep -E 'msg="(job queued|job claimed|lease expired|job stored|file delivered)"' "$WORK/core.log" \
| sed -E 's/^time=[^ ]+ //; s/ delivery_id=[^ ]+//; s/ user_id=[^ ]+//' | sed 's/^/ core: /'
fi
say "PASS: worker-$VICTIM was killed mid-job, the job was re-queued and worker-$SURVIVOR delivered the file ($SIZE bytes)"