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
+132
-8
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user