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
+104 -22
View File
@@ -72,6 +72,8 @@ type Scheduler struct {
type workerSeen struct {
capacity int
at time.Time
// commands are pending instructions, delivered with the next claim.
commands []string
}
// workerTTL is how long a worker counts toward capacity after its last
@@ -181,6 +183,9 @@ type EnqueueParams struct {
// Hit, when set, makes the job a cache hit: it is created already
// finished and never waits for a worker.
Hit *CacheHit
// RequiredTags is a comma separated list of tags a worker must have to
// take the job, for example "residential".
RequiredTags string
}
// CacheHit describes a cached result a job is served from.
@@ -228,25 +233,26 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams
p.Kind = db.KindDownload
}
job := &db.Job{
ID: ids.New(),
Kind: p.Kind,
URL: p.URL,
Extractor: p.Extractor,
VideoID: p.VideoID,
Profile: p.Profile,
CacheKey: p.CacheKey,
Cacheable: p.Cacheable,
SourceKey: p.SourceKey,
Status: db.JobQueued,
Lane: p.Lane,
Priority: p.Priority,
MaxSize: p.MaxSize,
MaxDuration: p.MaxDuration,
MaxAttempts: s.cfg.MaxAttempts,
Title: p.Title,
Uploader: p.Uploader,
CreatedAt: now,
QueuedAt: now,
ID: ids.New(),
Kind: p.Kind,
URL: p.URL,
Extractor: p.Extractor,
VideoID: p.VideoID,
Profile: p.Profile,
CacheKey: p.CacheKey,
Cacheable: p.Cacheable,
SourceKey: p.SourceKey,
RequiredTags: p.RequiredTags,
Status: db.JobQueued,
Lane: p.Lane,
Priority: p.Priority,
MaxSize: p.MaxSize,
MaxDuration: p.MaxDuration,
MaxAttempts: s.cfg.MaxAttempts,
Title: p.Title,
Uploader: p.Uploader,
CreatedAt: now,
QueuedAt: now,
}
if h := p.Hit; h != nil {
// Served from the cache: the result exists, so the job starts in
@@ -265,6 +271,11 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams
}
del := s.newDelivery(job.ID, p, now)
if p.ActiveLimit > 0 {
// Count and insert must not interleave with another request of
// the same user.
if err := tx.LockUser(ctx, p.UserID); err != nil {
return nil, nil, err
}
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return nil, nil, err
@@ -331,6 +342,9 @@ func covers(jobCap, myCap int64) bool {
// it up for whoever asked first.
func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p EnqueueParams) (*db.Delivery, bool, error) {
if p.ActiveLimit > 0 {
if err := tx.LockUser(ctx, p.UserID); err != nil {
return nil, false, err
}
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return nil, false, err
@@ -339,6 +353,19 @@ func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p E
return nil, false, ErrTooManyActive
}
}
// The job was found a moment ago. Lock it and look again: it may have
// been claimed, finished or cancelled since.
if err := tx.LockJob(ctx, job.ID); err != nil {
return nil, false, err
}
cur, err := tx.GetJob(ctx, job.ID)
if err != nil {
return nil, false, err
}
if cur.Status != db.JobQueued && cur.Status != db.JobRunning {
return nil, false, nil
}
*job = *cur
shared := covers(job.MaxSize, p.MaxSize) && covers(job.MaxDuration, p.MaxDuration)
if job.Status == db.JobQueued {
raised, err := tx.RaiseJob(ctx, job.ID, p.MaxSize, p.MaxDuration, p.Lane)
@@ -404,7 +431,8 @@ func (s *Scheduler) seen(workerID string, capacity int) (total int) {
now := s.cfg.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.workers[workerID] = workerSeen{capacity: capacity, at: now}
prev := s.workers[workerID]
s.workers[workerID] = workerSeen{capacity: capacity, at: now, commands: prev.commands}
for id, w := range s.workers {
if now.Sub(w.at) > workerTTL {
delete(s.workers, id)
@@ -415,6 +443,46 @@ func (s *Scheduler) seen(workerID string, capacity int) (total int) {
return total
}
// Command queues an instruction for every live worker. Each worker gets
// it with its next claim. It returns how many workers were addressed.
func (s *Scheduler) Command(cmd string) int {
now := s.cfg.Now()
s.mu.Lock()
defer s.mu.Unlock()
n := 0
for id, w := range s.workers {
if now.Sub(w.at) > workerTTL {
continue
}
w.commands = append(w.commands, cmd)
s.workers[id] = w
n++
}
return n
}
// TakeCommands returns and clears the pending instructions of a worker.
func (s *Scheduler) TakeCommands(workerID string) []string {
s.mu.Lock()
defer s.mu.Unlock()
w, ok := s.workers[workerID]
if !ok || len(w.commands) == 0 {
return nil
}
cmds := w.commands
w.commands = nil
s.workers[workerID] = w
return cmds
}
// Seen records that a worker is alive without claiming anything, so that
// a worker which only polls for probes still counts toward capacity.
func (s *Scheduler) Seen(workerID string, capacity int) { s.seen(workerID, capacity) }
// NotifyWork wakes claimers that are waiting, for work that arrives
// outside the job queue, such as a probe request.
func (s *Scheduler) NotifyWork() { s.notifyWork() }
// Capacity returns the number of download slots of all live workers.
func (s *Scheduler) Capacity() int {
now := s.cfg.Now()
@@ -451,7 +519,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w
return err
}
if idle := capacity - total; idle <= 1 && free == 0 {
j, err = tx.NextQueuedJob(ctx, freeOnly)
j, err = tx.NextQueuedJob(ctx, freeOnly, req.Tags)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return err
}
@@ -459,7 +527,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w
}
if j == nil {
var err error
j, err = tx.NextQueuedJob(ctx, allLanes)
j, err = tx.NextQueuedJob(ctx, allLanes, req.Tags)
if errors.Is(err, db.ErrNotFound) {
return nil
}
@@ -534,6 +602,9 @@ func (s *Scheduler) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequ
func (s *Scheduler) Complete(ctx context.Context, req workerproto.CompleteRequest) error {
var cancelled bool
err := s.store.InTx(ctx, func(tx *db.Store) error {
if err := tx.LockJob(ctx, req.JobID); err != nil {
return err
}
job, err := tx.GetJob(ctx, req.JobID)
if err != nil {
return err
@@ -583,6 +654,9 @@ func (s *Scheduler) Complete(ctx context.Context, req workerproto.CompleteReques
func (s *Scheduler) Fail(ctx context.Context, req workerproto.FailRequest) error {
var ev EventType
err := s.store.InTx(ctx, func(tx *db.Store) error {
if err := tx.LockJob(ctx, req.JobID); err != nil {
return err
}
job, err := tx.GetJob(ctx, req.JobID)
if err != nil {
return err
@@ -639,6 +713,9 @@ func (s *Scheduler) RequeueExpired(ctx context.Context) (int, error) {
for _, j := range expired {
var ev EventType
err := s.store.InTx(ctx, func(tx *db.Store) error {
if err := tx.LockJob(ctx, j.ID); err != nil {
return err
}
cur, err := tx.GetJob(ctx, j.ID)
if err != nil {
return err
@@ -700,6 +777,11 @@ func (s *Scheduler) CancelDelivery(ctx context.Context, deliveryID string, userI
}
d.Status = db.DeliveryCancelled
del = d
// Lock the job before looking at it: a worker may be claiming it
// right now, and the decision below depends on its status.
if err := tx.LockJob(ctx, d.JobID); err != nil {
return err
}
left, err := tx.CountDeliveriesInStatus(ctx, d.JobID, db.DeliveryPending, db.DeliverySending)
if err != nil || left > 0 {
return err