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:
co-authored by
Claude Fable 5.2
parent
9c9d641eda
commit
7d4893bc3f
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user