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
+141 -8
View File
@@ -11,6 +11,7 @@ import (
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
@@ -49,6 +50,27 @@ type Config struct {
Rate Rate `toml:"rate"`
Log Log `toml:"log"`
// SiteTags says which worker tags a site requires. A job for a listed
// site is only given to workers that advertise all of its tags. The
// usual case is a site that refuses datacenter addresses:
//
// [site_tags]
// "youtube.com" = ["residential"]
//
// A host also covers its subdomains. In the environment the same map
// is SITE_TAGS="youtube.com=residential;example.com=eu,residential".
SiteTags map[string][]string `toml:"site_tags"`
// WorkerTokens registers remote workers at startup, as "name:token"
// pairs. It is the simple way for a fixed setup such as docker
// compose. "core worker add" creates tokens without a restart.
WorkerTokens []string `toml:"worker_tokens" env:"WORKER_TOKENS"`
// ProbeMode says who runs metadata lookups: "local" (the core runs
// yt-dlp), "worker" (remote workers do), or "auto", which is local
// when the embedded worker is on and worker otherwise.
ProbeMode string `toml:"probe_mode" env:"PROBE_MODE"`
// PublicURL is the HTTPS base URL this server is reachable at from the
// internet, without a trailing slash. It is used for payment webhooks,
// "open in wallet" links and the Mini App.
@@ -93,16 +115,40 @@ type Storage struct {
// Backend is "local" or "s3".
Backend string `toml:"backend" env:"STORAGE_BACKEND"`
LocalDir string `toml:"local_dir" env:"STORAGE_LOCAL_DIR"`
S3 S3 `toml:"s3"`
}
// S3 holds the settings of an S3 compatible bucket (AWS, Garage, MinIO).
type S3 struct {
// Endpoint is host:port or a URL, for example https://s3.example.com.
Endpoint string `toml:"endpoint" env:"S3_ENDPOINT"`
Region string `toml:"region" env:"S3_REGION"`
Bucket string `toml:"bucket" env:"S3_BUCKET"`
AccessKey string `toml:"access_key" env:"S3_ACCESS_KEY"`
SecretKey string `toml:"secret_key" env:"S3_SECRET_KEY"`
UseSSL bool `toml:"use_ssl" env:"S3_USE_SSL"`
// PathStyle addresses the bucket as /bucket/key. Garage and MinIO need
// it; AWS prefers it off.
PathStyle bool `toml:"path_style" env:"S3_PATH_STYLE"`
Prefix string `toml:"prefix" env:"S3_PREFIX"`
// Presign lets workers upload straight to the bucket with presigned
// URLs. When off, files pass through the core.
Presign bool `toml:"presign" env:"S3_PRESIGN"`
// PresignEndpoint is the address workers reach the bucket at, when it
// is not the one the core uses.
PresignEndpoint string `toml:"presign_endpoint" env:"S3_PRESIGN_ENDPOINT"`
}
// Worker holds the settings of the download worker.
type Worker struct {
// Embedded runs a worker inside the core process.
Embedded bool `toml:"embedded" env:"WORKER_EMBEDDED"`
Concurrency int `toml:"concurrency" env:"WORKER_CONCURRENCY"`
TempDir string `toml:"temp_dir" env:"WORKER_TEMP_DIR"`
YtDlpPath string `toml:"ytdlp_path" env:"YTDLP_PATH"`
FfmpegPath string `toml:"ffmpeg_path" env:"FFMPEG_PATH"`
Embedded bool `toml:"embedded" env:"WORKER_EMBEDDED"`
Concurrency int `toml:"concurrency" env:"WORKER_CONCURRENCY"`
// Tags are the tags of the embedded worker.
Tags []string `toml:"tags" env:"WORKER_TAGS"`
TempDir string `toml:"temp_dir" env:"WORKER_TEMP_DIR"`
YtDlpPath string `toml:"ytdlp_path" env:"YTDLP_PATH"`
FfmpegPath string `toml:"ffmpeg_path" env:"FFMPEG_PATH"`
// DownloadTimeout is the hard cap for one download attempt.
DownloadTimeout Duration `toml:"download_timeout" env:"DOWNLOAD_TIMEOUT"`
// ProbeTimeout is the cap for one metadata lookup.
@@ -233,9 +279,11 @@ func Default() Config {
MaxUploadMB: 50,
UpdateWorkers: 8,
},
HTTP: HTTP{Listen: ":8080"},
Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"},
Storage: Storage{Backend: "local", LocalDir: "data/files"},
ProbeMode: "auto",
HTTP: HTTP{Listen: ":8080"},
Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"},
Storage: Storage{Backend: "local", LocalDir: "data/files",
S3: S3{Region: "garage", UseSSL: true, PathStyle: true, Presign: true}},
Worker: Worker{
Embedded: true,
Concurrency: 2,
@@ -322,6 +370,13 @@ func Load(path string) (Config, error) {
if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil {
return cfg, err
}
if raw, ok := os.LookupEnv("SITE_TAGS"); ok && raw != "" {
m, err := ParseSiteTags(raw)
if err != nil {
return cfg, err
}
cfg.SiteTags = m
}
cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/")
cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/")
return cfg, cfg.Validate()
@@ -361,6 +416,25 @@ func (c Config) Validate() error {
if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() {
errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE")
}
if c.Storage.Backend == "s3" {
if c.Storage.S3.Endpoint == "" || c.Storage.S3.Bucket == "" {
errs = append(errs, "S3_ENDPOINT and S3_BUCKET are required when STORAGE_BACKEND=s3")
}
if c.Storage.S3.AccessKey == "" || c.Storage.S3.SecretKey == "" {
errs = append(errs, "S3_ACCESS_KEY and S3_SECRET_KEY are required when STORAGE_BACKEND=s3")
}
}
switch c.ProbeMode {
case "auto", "local", "worker":
default:
errs = append(errs, "PROBE_MODE must be auto, local or worker")
}
for _, pair := range c.WorkerTokens {
if name, token, ok := strings.Cut(pair, ":"); !ok || name == "" || len(token) < 16 {
errs = append(errs, "WORKER_TOKENS entries must be name:token with a token of at least 16 characters")
break
}
}
if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") {
errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together")
}
@@ -386,6 +460,65 @@ func (c Config) Validate() error {
return nil
}
// ParseSiteTags reads "host=tag,tag;host=tag".
func ParseSiteTags(raw string) (map[string][]string, error) {
out := map[string][]string{}
for _, part := range strings.Split(raw, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
host, tags, ok := strings.Cut(part, "=")
host = strings.ToLower(strings.TrimSpace(host))
if !ok || host == "" {
return nil, fmt.Errorf("config: SITE_TAGS: %q is not host=tag,tag", part)
}
for _, t := range strings.Split(tags, ",") {
if t = strings.ToLower(strings.TrimSpace(t)); t != "" {
out[host] = append(out[host], t)
}
}
}
return out, nil
}
// RequiredTags returns the worker tags a site requires, sorted and comma
// separated, or "" when any worker will do. A rule for a host also covers
// its subdomains, and the rules of a host and of its parents add up.
func (c Config) RequiredTags(site string) string {
if len(c.SiteTags) == 0 || site == "" {
return ""
}
seen := map[string]bool{}
var tags []string
for host := strings.ToLower(site); host != ""; {
for _, t := range c.SiteTags[host] {
if t = strings.ToLower(strings.TrimSpace(t)); t != "" && !seen[t] {
seen[t] = true
tags = append(tags, t)
}
}
i := strings.IndexByte(host, '.')
if i < 0 {
break
}
host = host[i+1:]
}
sort.Strings(tags)
return strings.Join(tags, ",")
}
// ProbeLocally reports whether the core itself runs metadata lookups.
func (c Config) ProbeLocally() bool {
switch c.ProbeMode {
case "local":
return true
case "worker":
return false
}
return c.Worker.Embedded
}
// MaxUploadBytes is the Telegram upload ceiling in bytes.
func (c Config) MaxUploadBytes() int64 { return c.Telegram.MaxUploadMB << 20 }
+105
View File
@@ -248,3 +248,108 @@ func TestDotEnvDoesNotOverrideRealEnv(t *testing.T) {
t.Errorf("a missing .env is fine, got %v", err)
}
}
func TestSiteTagsAndRequiredTags(t *testing.T) {
m, err := ParseSiteTags(" YouTube.com = residential ; example.com=eu, residential ;; x.com=residential")
if err != nil {
t.Fatal(err)
}
cfg := Default()
cfg.SiteTags = m
tests := map[string]string{
"youtube.com": "residential",
"music.youtube.com": "residential", // a rule covers subdomains
"example.com": "eu,residential",
"cdn.eu.example.com": "eu,residential",
"notyoutube.com": "",
"com": "",
"": "",
"vimeo.com": "",
"YOUTUBE.COM": "residential",
}
for site, want := range tests {
if got := cfg.RequiredTags(site); got != want {
t.Errorf("RequiredTags(%q) = %q, want %q", site, got, want)
}
}
// Rules of a host and of its parent add up.
cfg.SiteTags["eu.example.com"] = []string{"fast"}
if got := cfg.RequiredTags("cdn.eu.example.com"); got != "eu,fast,residential" {
t.Errorf("combined rules = %q", got)
}
if _, err := ParseSiteTags("no-equals-sign"); err == nil {
t.Error("a malformed SITE_TAGS must be rejected")
}
if got := Default().RequiredTags("youtube.com"); got != "" {
t.Errorf("without rules nothing is required, got %q", got)
}
}
func TestProbeModeAndScaleOutValidation(t *testing.T) {
cfg := Default()
cfg.Telegram.Token = "x"
if !cfg.ProbeLocally() {
t.Fatal("with the embedded worker, the core probes by itself")
}
cfg.Worker.Embedded = false
if cfg.ProbeLocally() {
t.Fatal("without the embedded worker, probes go to remote workers")
}
cfg.ProbeMode = "local"
if !cfg.ProbeLocally() {
t.Fatal("PROBE_MODE=local forces local probing")
}
cfg.ProbeMode = "sometimes"
if err := cfg.Validate(); err == nil {
t.Fatal("an unknown PROBE_MODE must be rejected")
}
cfg.ProbeMode = "auto"
cfg.WorkerTokens = []string{"eu-1:short"}
if err := cfg.Validate(); err == nil {
t.Fatal("a short worker token must be rejected")
}
cfg.WorkerTokens = []string{"eu-1:dlw_0123456789abcdef"}
if err := cfg.Validate(); err != nil {
t.Fatalf("a good worker token entry: %v", err)
}
cfg.Storage.Backend = "s3"
if err := cfg.Validate(); err == nil {
t.Fatal("s3 without endpoint, bucket and keys must be rejected")
}
cfg.Storage.S3 = S3{Endpoint: "https://s3.example.com", Bucket: "b", AccessKey: "k", SecretKey: "s"}
if err := cfg.Validate(); err != nil {
t.Fatalf("complete s3 settings: %v", err)
}
}
func TestWorkerConfig(t *testing.T) {
cfg := DefaultWorker()
if err := cfg.Validate(); err == nil {
t.Fatal("a worker needs CORE_URL and WORKER_TOKEN")
}
cfg.CoreURL, cfg.Token = "bot.example.com", "dlw_x"
if err := cfg.Validate(); err == nil {
t.Fatal("CORE_URL needs a scheme")
}
cfg.CoreURL = "https://bot.example.com"
if err := cfg.Validate(); err != nil {
t.Fatalf("a complete worker config: %v", err)
}
if cfg.Heartbeat.D() != 10*time.Second || cfg.Concurrency != 2 || cfg.ProbeSlots != 2 {
t.Fatalf("worker defaults changed: %+v", cfg)
}
env := map[string]string{
"CORE_URL": "https://core.example.com/", "WORKER_TOKEN": "dlw_abc", "WORKER_TAGS": "residential, eu",
"YTDLP_EXTRA_ARGS": "--limit-rate 1M", "WORKER_HEALTH_LISTEN": "off", "YTDLP_AUTO_UPDATE": "0",
}
w := DefaultWorker()
if err := applyEnv(reflect.ValueOf(&w).Elem(), lookup(env)); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(w.Tags, []string{"residential", "eu"}) || !reflect.DeepEqual(w.ExtraArgs, []string{"--limit-rate", "1M"}) ||
w.AutoUpdate.D() != 0 {
t.Fatalf("worker env not applied: %+v", w)
}
}
+105
View File
@@ -0,0 +1,105 @@
package config
import (
"errors"
"os"
"reflect"
"strings"
"time"
)
// WorkerConfig is the configuration of the standalone worker binary. A
// worker knows the core's URL and its own token, and nothing else about
// the system: no bot token, no database, no payment keys.
type WorkerConfig struct {
// CoreURL is the base URL of the core, for example
// https://bot.example.com.
CoreURL string `env:"CORE_URL"`
// Token is this worker's bearer token, created on the core with
// "core worker add <name>".
Token string `env:"WORKER_TOKEN"`
// Tags describe what this worker can do or where it runs, for example
// "residential,eu". Jobs for sites that require a tag only go to
// workers that have it.
Tags []string `env:"WORKER_TAGS"`
Concurrency int `env:"WORKER_CONCURRENCY"`
// TempDir is scratch space. Each worker process needs its own.
TempDir string `env:"WORKER_TEMP_DIR"`
YtDlpPath string `env:"YTDLP_PATH"`
FfmpegPath string `env:"FFMPEG_PATH"`
// ExtraArgs are appended to every yt-dlp call, for example
// "--proxy socks5://127.0.0.1:1080".
ExtraArgs []string `env:"YTDLP_EXTRA_ARGS"`
DownloadTimeout Duration `env:"DOWNLOAD_TIMEOUT"`
ProbeTimeout Duration `env:"PROBE_TIMEOUT"`
// ProbeSlots is how many metadata lookups run next to the downloads.
ProbeSlots int `env:"WORKER_PROBE_SLOTS"`
// Heartbeat must be well under the core's QUEUE_LEASE.
Heartbeat Duration `env:"WORKER_HEARTBEAT"`
// AutoUpdate is how often yt-dlp updates itself. 0 turns it off.
AutoUpdate Duration `env:"YTDLP_AUTO_UPDATE"`
// HealthListen is the address of the health endpoint, or "off". It is
// the only port a worker opens and it is not needed by the core. Several
// workers on one machine need different ports.
HealthListen string `env:"WORKER_HEALTH_LISTEN"`
Log Log
}
// DefaultWorker returns the worker defaults.
func DefaultWorker() WorkerConfig {
return WorkerConfig{
Concurrency: 2,
TempDir: "data/worker-tmp",
YtDlpPath: "yt-dlp",
FfmpegPath: "ffmpeg",
DownloadTimeout: Duration(30 * time.Minute),
ProbeTimeout: Duration(45 * time.Second),
ProbeSlots: 2,
Heartbeat: Duration(10 * time.Second),
AutoUpdate: Duration(24 * time.Hour),
HealthListen: ":8081",
Log: Log{Level: "info", Format: "json"},
}
}
// LoadWorker reads the worker configuration from the environment, after
// loading a .env file from the working directory if there is one.
func LoadWorker() (WorkerConfig, error) {
cfg := DefaultWorker()
if err := loadDotEnv(".env"); err != nil {
return cfg, err
}
if err := applyEnv(reflect.ValueOf(&cfg).Elem(), os.LookupEnv); err != nil {
return cfg, err
}
cfg.CoreURL = strings.TrimRight(cfg.CoreURL, "/")
// An empty variable keeps the default, so "off" is how to say no.
switch strings.ToLower(cfg.HealthListen) {
case "off", "none", "false", "-":
cfg.HealthListen = ""
}
return cfg, cfg.Validate()
}
// Validate reports configuration mistakes.
func (c WorkerConfig) Validate() error {
var errs []string
if c.CoreURL == "" {
errs = append(errs, "CORE_URL is required")
} else if !strings.HasPrefix(c.CoreURL, "http://") && !strings.HasPrefix(c.CoreURL, "https://") {
errs = append(errs, "CORE_URL must start with http:// or https://")
}
if c.Token == "" {
errs = append(errs, "WORKER_TOKEN is required")
}
if c.Concurrency < 1 {
errs = append(errs, "WORKER_CONCURRENCY must be at least 1")
}
if c.Heartbeat.D() <= 0 {
errs = append(errs, "WORKER_HEARTBEAT must be positive")
}
if len(errs) > 0 {
return errors.New("config: " + strings.Join(errs, "; "))
}
return nil
}