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>
This commit is contained in:
Michilis
2026-11-18 09:27:11 +00:00
co-authored by Claude Fable 5.2
parent 9c9d641eda
commit 7d4893bc3f
51 changed files with 4732 additions and 108 deletions
+85
View File
@@ -0,0 +1,85 @@
# syntax=docker/dockerfile:1
#
# One Dockerfile, three targets:
#
# docker build -f deploy/Dockerfile --target core -t dlbot-core .
# docker build -f deploy/Dockerfile --target worker -t dlbot-worker .
# docker build -f deploy/Dockerfile --target faketelegram -t dlbot-faketelegram .
#
# docker-compose.yml builds core and worker for you.
ARG GO_VERSION=1.26
ARG DEBIAN_VERSION=bookworm
# --- build -------------------------------------------------------------------
FROM golang:${GO_VERSION}-${DEBIAN_VERSION} AS build
WORKDIR /src
# go.mod asks for a specific Go patch release. Let the toolchain fetch it
# when the image is a little older.
ENV GOTOOLCHAIN=auto CGO_ENABLED=0
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -trimpath -ldflags "-s -w" -o /out/core ./cmd/core \
&& go build -trimpath -ldflags "-s -w" -o /out/worker ./cmd/worker \
&& go build -trimpath -ldflags "-s -w" -o /out/faketelegram ./cmd/faketelegram
# --- runtime base: ffmpeg and yt-dlp -----------------------------------------
FROM debian:${DEBIAN_VERSION}-slim AS runtime
ARG TARGETARCH
# "latest", or a release tag such as 2026.10.26 to pin the version.
ARG YTDLP_VERSION=latest
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl ffmpeg tini \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --uid 10001 --home-dir /data --shell /usr/sbin/nologin dlbot \
&& mkdir -p /data /opt/dlbot/bin \
&& case "${TARGETARCH:-amd64}" in \
arm64) asset=yt-dlp_linux_aarch64 ;; \
*) asset=yt-dlp_linux ;; \
esac \
&& if [ "$YTDLP_VERSION" = "latest" ]; then \
url="https://github.com/yt-dlp/yt-dlp/releases/latest/download/$asset"; \
else \
url="https://github.com/yt-dlp/yt-dlp/releases/download/$YTDLP_VERSION/$asset"; \
fi \
&& curl -fsSL -o /opt/dlbot/bin/yt-dlp "$url" \
&& chmod 0755 /opt/dlbot/bin/yt-dlp \
# yt-dlp updates itself in place, so its directory belongs to the service user.
&& chown -R dlbot:dlbot /data /opt/dlbot
ENV PATH="/opt/dlbot/bin:${PATH}" \
YTDLP_PATH=/opt/dlbot/bin/yt-dlp \
FFMPEG_PATH=ffmpeg
USER dlbot
WORKDIR /data
ENTRYPOINT ["/usr/bin/tini", "--"]
# --- core --------------------------------------------------------------------
FROM runtime AS core
COPY --from=build /out/core /usr/local/bin/core
ENV HTTP_LISTEN=:8080 \
DB_DSN=/data/dlbot.db \
STORAGE_LOCAL_DIR=/data/files \
WORKER_TEMP_DIR=/data/tmp
VOLUME ["/data"]
EXPOSE 8080
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \
CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1
CMD ["core"]
# --- worker ------------------------------------------------------------------
FROM runtime AS worker
COPY --from=build /out/worker /usr/local/bin/worker
ENV WORKER_TEMP_DIR=/data/tmp \
WORKER_HEALTH_LISTEN=:8081
VOLUME ["/data"]
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \
CMD curl -fsS http://127.0.0.1:8081/healthz || exit 1
CMD ["worker"]
# --- fake Telegram, for trying the bot without a token -----------------------
FROM debian:${DEBIAN_VERSION}-slim AS faketelegram
COPY --from=build /out/faketelegram /usr/local/bin/faketelegram
USER 10001
EXPOSE 8090
CMD ["faketelegram", "-listen", ":8090"]
+46
View File
@@ -0,0 +1,46 @@
# Overlay for the kill-a-worker acceptance run. It swaps the real Telegram
# for the fake one, so no bot token is needed, and slows downloads down so
# there is time to kill a worker in the middle of one.
#
# deploy/acceptance/kill-worker.sh # MODE=compose uses this file
#
# Never expose this setup to the internet: the fake Telegram accepts
# anything from anyone.
services:
faketelegram:
build:
# Paths in an overlay are relative to the first compose file, which
# is the one in the repository root.
context: .
dockerfile: deploy/Dockerfile
target: faketelegram
image: dlbot-faketelegram:local
ports:
- "127.0.0.1:${FAKE_PORT:-8090}:8090"
core:
depends_on:
- faketelegram
environment:
BOT_TOKEN: "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01"
TELEGRAM_API_URL: http://faketelegram:8090
QUEUE_LEASE: 12s
QUEUE_HEARTBEAT: 4s
LOG_FORMAT: text
worker-a:
environment:
WORKER_CONCURRENCY: "1"
WORKER_HEARTBEAT: 4s
YTDLP_EXTRA_ARGS: "--limit-rate ${RATE:-50K}"
YTDLP_AUTO_UPDATE: "0"
LOG_FORMAT: text
worker-b:
environment:
WORKER_CONCURRENCY: "1"
WORKER_HEARTBEAT: 4s
YTDLP_EXTRA_ARGS: "--limit-rate ${RATE:-50K}"
YTDLP_AUTO_UPDATE: "0"
LOG_FORMAT: text
+202
View File
@@ -0,0 +1,202 @@
#!/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)"
+48
View File
@@ -0,0 +1,48 @@
# The Noderunners Download Bot: core.
#
# install -m 0755 bin/core /usr/local/bin/dlbot-core
# useradd --system --home-dir /var/lib/dlbot --create-home dlbot
# install -d -m 0750 -o dlbot -g dlbot /etc/dlbot
# install -m 0640 -o dlbot -g dlbot .env /etc/dlbot/core.env
# systemctl enable --now dlbot-core
#
# Paths in core.env should be absolute, for example
# DB_DSN=/var/lib/dlbot/dlbot.db
# STORAGE_LOCAL_DIR=/var/lib/dlbot/files
# WORKER_TEMP_DIR=/var/lib/dlbot/tmp
[Unit]
Description=The Noderunners Download Bot (core)
Documentation=https://github.com/noderunners/dlbot
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=dlbot
Group=dlbot
WorkingDirectory=/var/lib/dlbot
EnvironmentFile=/etc/dlbot/core.env
ExecStart=/usr/local/bin/dlbot-core
Restart=on-failure
RestartSec=5
# The core hands running jobs back to the queue on SIGTERM.
TimeoutStopSec=30
KillSignal=SIGTERM
# Hardening. The core only writes below /var/lib/dlbot.
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
ReadWritePaths=/var/lib/dlbot
UMask=0027
[Install]
WantedBy=multi-user.target
+51
View File
@@ -0,0 +1,51 @@
# The Noderunners Download Bot: download worker.
#
# A worker needs outbound access to the core and to the sites it downloads
# from. It needs no inbound port and no secrets other than its own token.
#
# install -m 0755 bin/worker /usr/local/bin/dlbot-worker
# useradd --system --home-dir /var/lib/dlbot-worker --create-home dlbot
# install -d -m 0750 -o dlbot -g dlbot /etc/dlbot
# printf 'CORE_URL=https://bot.example.com\nWORKER_TOKEN=dlw_...\nWORKER_TEMP_DIR=/var/lib/dlbot-worker/tmp\n' \
# > /etc/dlbot/worker.env && chmod 0640 /etc/dlbot/worker.env && chown dlbot:dlbot /etc/dlbot/worker.env
# systemctl enable --now dlbot-worker
#
# yt-dlp updates itself, so install it somewhere the service user can
# write, for example /var/lib/dlbot-worker/bin/yt-dlp, and set YTDLP_PATH.
# To run several workers on one machine, copy this unit and give each its
# own token and its own WORKER_TEMP_DIR.
[Unit]
Description=The Noderunners Download Bot (worker)
Documentation=https://github.com/noderunners/dlbot
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=dlbot
Group=dlbot
WorkingDirectory=/var/lib/dlbot-worker
EnvironmentFile=/etc/dlbot/worker.env
ExecStart=/usr/local/bin/dlbot-worker
Restart=on-failure
RestartSec=5
# On SIGTERM the worker stops its downloads and hands the jobs back.
TimeoutStopSec=30
KillSignal=SIGTERM
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
ReadWritePaths=/var/lib/dlbot-worker
UMask=0027
[Install]
WantedBy=multi-user.target