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
+208
View File
@@ -0,0 +1,208 @@
package worker
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/noderunners/dlbot/internal/workerproto"
)
// HTTPCoordinator talks to the core's worker API. It is the Coordinator
// of the standalone worker binary.
type HTTPCoordinator struct {
base string
token string
// api is for the small JSON calls, files for uploads and downloads,
// which have no overall timeout and rely on the context instead.
api *http.Client
files *http.Client
}
var _ Coordinator = (*HTTPCoordinator)(nil)
// NewHTTPCoordinator creates a client for the core at baseURL.
func NewHTTPCoordinator(baseURL, token string) *HTTPCoordinator {
return &HTTPCoordinator{
base: strings.TrimRight(baseURL, "/"),
token: token,
api: &http.Client{Timeout: 90 * time.Second},
files: &http.Client{},
}
}
// StatusError is a non-2xx answer from the core.
type StatusError struct {
Code int
Msg string
}
func (e *StatusError) Error() string { return fmt.Sprintf("core answered %d: %s", e.Code, e.Msg) }
// LeaseLost reports that the core no longer considers the job ours.
func (e *StatusError) LeaseLost() bool { return e.Code == http.StatusConflict }
// Unauthorized reports that the core rejected the worker's token.
func (e *StatusError) Unauthorized() bool { return e.Code == http.StatusUnauthorized }
// IsUnauthorized reports whether err means the token was rejected, which
// no amount of retrying fixes.
func IsUnauthorized(err error) bool {
var se *StatusError
return errors.As(err, &se) && se.Unauthorized()
}
func (c *HTTPCoordinator) call(ctx context.Context, path string, in, out any) error {
body, err := json.Marshal(in)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+path, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
resp, err := c.api.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return decode(resp, out)
}
func decode(resp *http.Response, out any) error {
data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
var e struct {
Error string `json:"error"`
}
_ = json.Unmarshal(data, &e)
if e.Error == "" {
e.Error = http.StatusText(resp.StatusCode)
}
return &StatusError{Code: resp.StatusCode, Msg: e.Error}
}
if out == nil || len(data) == 0 {
return nil
}
return json.Unmarshal(data, out)
}
// ClaimAny asks for work and returns the whole response: a job, a probe
// task, and any commands for the worker.
func (c *HTTPCoordinator) ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) {
var resp workerproto.ClaimResponse
if err := c.call(ctx, "/worker/v1/claim", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// Claim implements Coordinator.
func (c *HTTPCoordinator) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) {
resp, err := c.ClaimAny(ctx, req)
if err != nil {
return nil, err
}
return resp.Job, nil
}
// Heartbeat implements Coordinator.
func (c *HTTPCoordinator) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) {
var resp workerproto.HeartbeatResponse
err := c.call(ctx, "/worker/v1/heartbeat", req, &resp)
return resp, err
}
// Complete implements Coordinator.
func (c *HTTPCoordinator) Complete(ctx context.Context, req workerproto.CompleteRequest) error {
return c.call(ctx, "/worker/v1/complete", req, nil)
}
// Fail implements Coordinator.
func (c *HTTPCoordinator) Fail(ctx context.Context, req workerproto.FailRequest) error {
return c.call(ctx, "/worker/v1/fail", req, nil)
}
// ProbeResult answers a probe task.
func (c *HTTPCoordinator) ProbeResult(ctx context.Context, res workerproto.ProbeResult) error {
return c.call(ctx, "/worker/v1/probe", res, nil)
}
// Upload implements Coordinator. With a presigned URL the file goes
// straight to storage; otherwise it is streamed to the core. Either way
// it is never read into memory.
func (c *HTTPCoordinator) Upload(ctx context.Context, job *workerproto.Job, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return err
}
url, direct := job.UploadURL, job.UploadURL != ""
if !direct {
url = c.base + "/worker/v1/upload/" + job.ID
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, f)
if err != nil {
return err
}
req.ContentLength = st.Size()
req.Header.Set("Content-Type", "application/octet-stream")
if !direct {
// The bearer token is only ever sent to the core, never to storage.
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.files.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return decode(resp, nil)
}
// Fetch implements Coordinator.
func (c *HTTPCoordinator) Fetch(ctx context.Context, job *workerproto.Job, path string) error {
url, direct := job.SourceURL, job.SourceURL != ""
if !direct {
url = c.base + "/worker/v1/source/" + job.ID
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
if !direct {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.files.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return decode(resp, nil)
}
out, err := os.Create(path)
if err != nil {
return err
}
if _, err := io.Copy(out, resp.Body); err != nil {
out.Close()
return err
}
return out.Close()
}
+132 -8
View File
@@ -5,6 +5,7 @@ package worker
import (
"context"
"encoding/json"
"errors"
"log/slog"
"math"
@@ -45,6 +46,21 @@ type Config struct {
Heartbeat time.Duration
// ClaimWait is how long one claim call may wait for work.
ClaimWait time.Duration
// ProbeSlots is the number of extra claim loops that only take
// metadata lookups. They need a Prober coordinator and are 0 for the
// embedded worker, whose core runs lookups itself.
ProbeSlots int
// Version returns the yt-dlp version to report. It may be nil.
Version func() string
// OnCommand is called for instructions from the core. It may be nil.
OnCommand func(cmd string)
}
// Prober is the part of a coordinator that hands out metadata lookups.
// Only the HTTP coordinator implements it.
type Prober interface {
ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error)
ProbeResult(ctx context.Context, res workerproto.ProbeResult) error
}
// Worker runs download jobs.
@@ -55,6 +71,16 @@ type Worker struct {
trans ffmpeg.Transcoder
log *slog.Logger
active atomic.Int32
// lastOK is the unix time of the last call the core answered.
lastOK atomic.Int64
// authFailed is set when the core rejected the token.
authFailed atomic.Bool
}
// LastContact returns when the core last answered a claim, and whether
// the worker's token was rejected.
func (w *Worker) LastContact() (time.Time, bool) {
return time.Unix(w.lastOK.Load(), 0), w.authFailed.Load()
}
// SetTranscoder gives the worker the means to run derive jobs. Without it
@@ -88,6 +114,7 @@ func (w *Worker) Run(ctx context.Context) {
w.log.Error("cannot create temp dir", "dir", w.cfg.TempDir, "err", err)
}
w.sweepOrphans()
w.lastOK.Store(time.Now().Unix())
var wg sync.WaitGroup
for i := 0; i < w.cfg.Concurrency; i++ {
wg.Add(1)
@@ -96,9 +123,99 @@ func (w *Worker) Run(ctx context.Context) {
w.slot(ctx)
}()
}
if prober, ok := w.coord.(Prober); ok {
for i := 0; i < w.cfg.ProbeSlots; i++ {
wg.Add(1)
go func() {
defer wg.Done()
w.probeSlot(ctx, prober)
}()
}
}
wg.Wait()
}
func (w *Worker) claimRequest(probeOnly bool) workerproto.ClaimRequest {
req := workerproto.ClaimRequest{
WorkerID: w.cfg.ID,
Tags: w.cfg.Tags,
Capacity: w.cfg.Concurrency,
Active: w.Active(),
WaitSeconds: int(math.Ceil(w.cfg.ClaimWait.Seconds())),
ProbeOnly: probeOnly,
}
if w.cfg.Version != nil {
req.Version = w.cfg.Version()
}
return req
}
// noteClaim records the outcome of a claim for the health endpoint and
// returns how long to wait before the next one after an error.
func (w *Worker) noteClaim(err error, backoff *time.Duration) {
if err == nil {
w.lastOK.Store(time.Now().Unix())
w.authFailed.Store(false)
*backoff = time.Second
return
}
if IsUnauthorized(err) {
// A revoked or wrong token will not start working by itself. Keep
// asking, slowly, in case the owner issues the token again.
w.authFailed.Store(true)
*backoff = time.Minute
}
}
// probeSlot takes metadata lookups from the core, one at a time.
func (w *Worker) probeSlot(ctx context.Context, prober Prober) {
backoff := time.Second
for ctx.Err() == nil {
resp, err := prober.ClaimAny(ctx, w.claimRequest(true))
w.noteClaim(err, &backoff)
if err != nil {
if ctx.Err() != nil {
return
}
w.log.Warn("probe claim failed", "err", err, "retry_in", backoff.String())
sleep(ctx, backoff)
if backoff < 30*time.Second {
backoff *= 2
}
continue
}
w.runCommands(resp.Commands)
if resp.Probe == nil {
continue
}
res := workerproto.ProbeResult{WorkerID: w.cfg.ID, ID: resp.Probe.ID}
info, perr := w.runner.Probe(ctx, resp.Probe.URL)
if perr != nil {
var ye *ytdlp.Error
if !errors.As(perr, &ye) {
ye = &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: perr.Error()}
}
res.Code, res.Retryable, res.Detail = string(ye.Code), ye.Retryable, ye.Raw
} else if res.Info, err = json.Marshal(info); err != nil {
res.Code, res.Detail = string(ytdlp.CodeInternal), err.Error()
}
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
if err := prober.ProbeResult(rctx, res); err != nil {
w.log.Debug("probe result not accepted", "err", err)
}
cancel()
}
}
func (w *Worker) runCommands(cmds []string) {
if w.cfg.OnCommand == nil {
return
}
for _, c := range cmds {
w.cfg.OnCommand(c)
}
}
// sweepOrphans removes job directories left behind by a crash. A worker is
// stateless, so nothing in its temp dir is valid at startup. Only names
// that look like job IDs are touched, and every worker process must have
@@ -123,13 +240,20 @@ func (w *Worker) sweepOrphans() {
func (w *Worker) slot(ctx context.Context) {
backoff := time.Second
for ctx.Err() == nil {
job, err := w.coord.Claim(ctx, workerproto.ClaimRequest{
WorkerID: w.cfg.ID,
Tags: w.cfg.Tags,
Capacity: w.cfg.Concurrency,
Active: w.Active(),
WaitSeconds: int(math.Ceil(w.cfg.ClaimWait.Seconds())),
})
var (
job *workerproto.Job
err error
)
if prober, ok := w.coord.(Prober); ok {
var resp *workerproto.ClaimResponse
if resp, err = prober.ClaimAny(ctx, w.claimRequest(false)); err == nil {
job = resp.Job
w.runCommands(resp.Commands)
}
} else {
job, err = w.coord.Claim(ctx, w.claimRequest(false))
}
w.noteClaim(err, &backoff)
if err != nil {
if ctx.Err() != nil {
return
@@ -141,7 +265,6 @@ func (w *Worker) slot(ctx context.Context) {
}
continue
}
backoff = time.Second
if job == nil {
continue // the coordinator already waited for ClaimWait
}
@@ -163,6 +286,7 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
jobCtx, cancel := context.WithCancel(ctx)
defer cancel()
log.Info("job started", "kind", job.Kind, "profile", job.Profile)
var (
mu sync.Mutex