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
+18
View File
@@ -1,6 +1,11 @@
// Command core is the bot gateway: it talks to Telegram, owns the queue and
// the database, serves the HTTP API and, by default, runs an embedded
// download worker.
//
// core run the bot
// core worker add <name> register a remote worker and print its token
// core worker revoke <name> revoke a worker's token
// core worker list list workers
package main
import (
@@ -29,6 +34,19 @@ func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// "core worker ..." manages worker tokens and exits.
if args := flag.Args(); len(args) > 0 {
if args[0] != "worker" {
fmt.Fprintf(os.Stderr, "unknown command %q\n", args[0])
os.Exit(2)
}
if err := app.WorkerAdmin(ctx, cfg, args[1:], os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
a, err := app.New(ctx, app.Options{Config: cfg, Log: log})
if err != nil {
log.Error("startup failed", "err", err)
+110
View File
@@ -0,0 +1,110 @@
// Command faketelegram is a stand-in for the Telegram Bot API, for trying
// the bot without a real bot token: local development, the acceptance
// scripts and load tests.
//
// It serves the Bot API methods the bot uses on -listen, for the token
// printed at startup, plus a small control API to play the user:
//
// POST /control/message {"chat_id":1,"user_id":1,"text":"https://..."}
// POST /control/callback {"chat_id":1,"user_id":1,"message_id":7,"data":"dl:..."}
// GET /control/calls?method=sendVideo&after=0
//
// It must never face the internet: it accepts anything from anyone.
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"strconv"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
)
func main() {
listen := flag.String("listen", "127.0.0.1:8090", "address to listen on")
flag.Parse()
fake := fakeserver.NewHandler()
mux := http.NewServeMux()
mux.Handle("/bot"+fakeserver.Token+"/", fake)
mux.HandleFunc("POST /control/message", func(w http.ResponseWriter, r *http.Request) {
var in struct {
ChatID int64 `json:"chat_id"`
UserID int64 `json:"user_id"`
Text string `json:"text"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Text == "" {
http.Error(w, "need chat_id, user_id and text", http.StatusBadRequest)
return
}
if in.UserID == 0 {
in.UserID = in.ChatID
}
id := fake.PushMessage(in.ChatID, in.UserID, in.Text)
writeJSON(w, map[string]int{"message_id": id})
})
mux.HandleFunc("POST /control/callback", func(w http.ResponseWriter, r *http.Request) {
var in struct {
ChatID int64 `json:"chat_id"`
UserID int64 `json:"user_id"`
MessageID int `json:"message_id"`
Data string `json:"data"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Data == "" {
http.Error(w, "need chat_id, user_id, message_id and data", http.StatusBadRequest)
return
}
if in.UserID == 0 {
in.UserID = in.ChatID
}
writeJSON(w, map[string]string{"callback_id": fake.PushCallback(in.ChatID, in.UserID, in.MessageID, in.Data)})
})
mux.HandleFunc("GET /control/calls", func(w http.ResponseWriter, r *http.Request) {
after, _ := strconv.Atoi(r.URL.Query().Get("after"))
type call struct {
Seq int `json:"seq"`
Method string `json:"method"`
MessageID int `json:"message_id,omitempty"`
Text string `json:"text,omitempty"`
Params map[string]string `json:"params"`
Files map[string]int64 `json:"files,omitempty"`
Buttons []string `json:"buttons,omitempty"`
Failed bool `json:"failed,omitempty"`
}
out := []call{}
for _, c := range fake.Calls(r.URL.Query().Get("method")) {
if c.Seq <= after {
continue
}
item := call{Seq: c.Seq, Method: c.Method, MessageID: c.MessageID, Text: c.Text(), Params: c.Params, Failed: c.Failed}
if len(c.Files) > 0 {
item.Files = map[string]int64{}
for field, f := range c.Files {
item.Files[field] = f.Size
}
}
for _, b := range c.Buttons() {
if b.Data != "" {
item.Buttons = append(item.Buttons, b.Data)
}
}
out = append(out, item)
}
writeJSON(w, out)
})
fmt.Printf("fake Telegram Bot API on http://%s\n", *listen)
fmt.Printf(" BOT_TOKEN=%s\n TELEGRAM_API_URL=http://%s\n", fakeserver.Token, *listen)
log.Fatal(http.ListenAndServe(*listen, mux))
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
+177
View File
@@ -0,0 +1,177 @@
// Command worker is a stateless download worker. It connects out to the
// core, takes jobs, runs yt-dlp and ffmpeg, uploads the results and
// reports back. It opens no inbound port (apart from an optional local
// health endpoint) and never sees the bot token.
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/app"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/worker"
"github.com/noderunners/dlbot/internal/workerproto"
"github.com/noderunners/dlbot/internal/ytdlp"
)
func main() {
cfg, err := config.LoadWorker()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
log := app.NewLogger(cfg.Log, cfg.Token)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
runner := &ytdlp.Exec{
Path: cfg.YtDlpPath,
FfmpegPath: cfg.FfmpegPath,
ProbeTimeout: cfg.ProbeTimeout.D(),
DownloadTimeout: cfg.DownloadTimeout.D(),
ExtraArgs: cfg.ExtraArgs,
}
up := &updater{runner: runner, log: log}
up.refresh(ctx)
if up.get() == "" {
log.Error("yt-dlp does not run, downloads will fail", "path", cfg.YtDlpPath)
}
w := worker.New(worker.Config{
ID: "remote", // the core takes the identity from the token
Tags: cfg.Tags,
Concurrency: cfg.Concurrency,
TempDir: cfg.TempDir,
Heartbeat: cfg.Heartbeat.D(),
ClaimWait: 20 * time.Second,
ProbeSlots: cfg.ProbeSlots,
Version: up.get,
OnCommand: func(cmd string) {
if cmd == workerproto.CommandUpdateYtDlp {
go up.update(ctx)
}
},
}, worker.NewHTTPCoordinator(cfg.CoreURL, cfg.Token), runner, log)
w.SetTranscoder(&ffmpeg.Exec{Path: cfg.FfmpegPath, Timeout: cfg.DownloadTimeout.D()})
var wg sync.WaitGroup
if cfg.HealthListen != "" {
srv := healthServer(cfg.HealthListen, w)
wg.Add(1)
go func() {
defer wg.Done()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Warn("health endpoint stopped", "err", err)
}
}()
go func() {
<-ctx.Done()
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
}()
}
if every := cfg.AutoUpdate.D(); every > 0 {
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
up.update(ctx)
}
}
}()
}
log.Info("worker started", "core", cfg.CoreURL, "tags", cfg.Tags, "concurrency", cfg.Concurrency,
"ytdlp", up.get(), "probe_slots", cfg.ProbeSlots)
w.Run(ctx) // returns when every running job has been handed back
wg.Wait()
log.Info("worker stopped")
}
// healthServer answers /healthz. The worker is healthy while the core
// keeps answering its claims and accepts its token.
func healthServer(addr string, w *worker.Worker) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(rw http.ResponseWriter, _ *http.Request) {
last, authFailed := w.LastContact()
age := time.Since(last)
status, code := "ok", http.StatusOK
switch {
case authFailed:
status, code = "token rejected by the core", http.StatusServiceUnavailable
case age > 2*time.Minute:
status, code = "core unreachable", http.StatusServiceUnavailable
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]any{
"status": status, "active_jobs": w.Active(), "seconds_since_core_contact": int(age.Seconds()),
})
})
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
}
// updater keeps yt-dlp current and remembers its version.
type updater struct {
runner *ytdlp.Exec
log *slog.Logger
mu sync.Mutex
busy bool
ver string
}
func (u *updater) get() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.ver
}
func (u *updater) refresh(ctx context.Context) {
v, err := u.runner.Version(ctx)
if err != nil {
u.log.Warn("cannot read the yt-dlp version", "err", err)
return
}
u.mu.Lock()
u.ver = v
u.mu.Unlock()
}
func (u *updater) update(ctx context.Context) {
u.mu.Lock()
if u.busy {
u.mu.Unlock()
return
}
u.busy = true
u.mu.Unlock()
defer func() {
u.mu.Lock()
u.busy = false
u.mu.Unlock()
}()
before := u.get()
out, err := u.runner.Update(ctx)
u.refresh(ctx)
if err != nil {
u.log.Warn("yt-dlp update failed", "err", err, "output", out)
return
}
u.log.Info("yt-dlp update done", "before", before, "after", u.get())
}