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
+149
View File
@@ -0,0 +1,149 @@
// Package probe sends metadata lookups to remote workers.
//
// The core needs yt-dlp metadata to show a card, but it may run somewhere
// that sites refuse to answer (a datacenter), or without yt-dlp at all.
// The broker hands such lookups to workers through their claim calls and
// waits for the answer. Requests live in memory only: if the core restarts
// while one is pending, the user just sends the link again.
package probe
import (
"context"
"encoding/json"
"errors"
"sync"
"time"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/ids"
"github.com/noderunners/dlbot/internal/workerproto"
"github.com/noderunners/dlbot/internal/ytdlp"
)
type task struct {
id string
url string
required string
taken bool
done chan *workerproto.ProbeResult
}
// Broker queues probe requests for workers.
type Broker struct {
// Timeout bounds one lookup, including the wait for a free worker.
Timeout time.Duration
// Tags returns the worker tags a URL requires, as a comma separated
// list. It may be nil.
Tags func(url string) string
// Notify wakes workers that wait in a claim call.
Notify func()
mu sync.Mutex
tasks []*task
byID map[string]*task
}
// NewBroker creates a broker.
func NewBroker(timeout time.Duration, tags func(string) string, notify func()) *Broker {
if timeout <= 0 {
timeout = 45 * time.Second
}
return &Broker{Timeout: timeout, Tags: tags, Notify: notify, byID: map[string]*task{}}
}
// Probe asks a worker for the metadata of a URL and waits for the answer.
// It has the same contract as ytdlp.Runner.Probe.
func (b *Broker) Probe(ctx context.Context, url string) (*ytdlp.Info, error) {
t := &task{id: ids.New(), url: url, done: make(chan *workerproto.ProbeResult, 1)}
if b.Tags != nil {
t.required = b.Tags(url)
}
b.mu.Lock()
b.tasks = append(b.tasks, t)
b.byID[t.id] = t
b.mu.Unlock()
defer b.forget(t)
if b.Notify != nil {
b.Notify()
}
timer := time.NewTimer(b.Timeout)
defer timer.Stop()
select {
case <-ctx.Done():
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "probe cancelled"}
case <-timer.C:
// No worker answered in time: none is connected, none has the
// tags, or the lookup itself hung.
return nil, &ytdlp.Error{Code: ytdlp.CodeTimeout, Retryable: true, Raw: "no worker answered the probe"}
case res := <-t.done:
if res.Code != "" {
return nil, &ytdlp.Error{Code: ytdlp.Code(res.Code), Retryable: res.Retryable, Raw: res.Detail}
}
var info ytdlp.Info
if err := json.Unmarshal(res.Info, &info); err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeUnknown, Retryable: true, Raw: "bad probe result: " + err.Error()}
}
if info.Type == "" {
info.Type = "video"
}
return &info, nil
}
}
func (b *Broker) forget(t *task) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.byID, t.id)
for i, x := range b.tasks {
if x == t {
b.tasks = append(b.tasks[:i], b.tasks[i+1:]...)
break
}
}
}
// Take hands the oldest waiting request to a worker with the given tags,
// or returns nil.
func (b *Broker) Take(tags []string) *workerproto.ProbeTask {
b.mu.Lock()
defer b.mu.Unlock()
for _, t := range b.tasks {
if !t.taken && db.HasTags(tags, t.required) {
t.taken = true
return &workerproto.ProbeTask{ID: t.id, URL: t.url}
}
}
return nil
}
// Pending returns how many requests wait for a worker.
func (b *Broker) Pending() int {
b.mu.Lock()
defer b.mu.Unlock()
n := 0
for _, t := range b.tasks {
if !t.taken {
n++
}
}
return n
}
// ErrUnknownProbe is returned for an answer nobody waits for anymore.
var ErrUnknownProbe = errors.New("probe: unknown or expired probe id")
// Resolve delivers a worker's answer to the waiting request.
func (b *Broker) Resolve(res *workerproto.ProbeResult) error {
b.mu.Lock()
t, ok := b.byID[res.ID]
b.mu.Unlock()
if !ok {
return ErrUnknownProbe
}
select {
case t.done <- res:
default: // a second answer for the same request is dropped
}
return nil
}