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
+5
View File
@@ -143,6 +143,11 @@ func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error {
return tx.Commit()
}
// Rebind turns "?" placeholders into the form the database expects. Code
// outside this package that runs its own SQL, mostly tests, uses it to stay
// portable.
func (d *DB) Rebind(query string) string { return (&Store{db: d}).rebind(query) }
// rebind turns "?" placeholders into "$1, $2, ..." for Postgres.
func (s *Store) rebind(query string) string {
if s.db.Dialect != Postgres {
+57 -1
View File
@@ -1,19 +1,75 @@
// Package dbtest opens throwaway databases for tests.
//
// By default every test gets its own SQLite file. To run the same tests
// against Postgres, point them at a server:
//
// DLBOT_TEST_DB=postgres \
// DLBOT_TEST_PG_DSN=postgres://user@127.0.0.1:5432/dlbot_test \
// go test ./...
//
// Each test then gets its own schema, which is dropped afterwards.
package dbtest
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"net/url"
"os"
"path/filepath"
"testing"
_ "github.com/jackc/pgx/v5/stdlib" // for schema setup
"github.com/noderunners/dlbot/internal/db"
)
// Postgres reports whether tests run against Postgres.
func Postgres() bool { return os.Getenv("DLBOT_TEST_DB") == "postgres" }
// NewDSN returns the driver and DSN of a fresh, empty database for one
// test. It is removed when the test ends.
func NewDSN(t testing.TB) (driver, dsn string) {
t.Helper()
if !Postgres() {
return "sqlite", filepath.Join(t.TempDir(), "test.db")
}
base := os.Getenv("DLBOT_TEST_PG_DSN")
if base == "" {
t.Fatal("DLBOT_TEST_DB=postgres needs DLBOT_TEST_PG_DSN")
}
var raw [6]byte
_, _ = rand.Read(raw[:])
schema := "t_" + hex.EncodeToString(raw[:])
admin, err := sql.Open("pgx", base)
if err != nil {
t.Fatalf("open postgres: %v", err)
}
if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil {
admin.Close()
t.Fatalf("create schema: %v", err)
}
t.Cleanup(func() {
_, _ = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
admin.Close()
})
u, err := url.Parse(base)
if err != nil {
t.Fatalf("bad DLBOT_TEST_PG_DSN: %v", err)
}
q := u.Query()
q.Set("search_path", schema)
u.RawQuery = q.Encode()
return "postgres", u.String()
}
// Open returns a migrated database that is removed when the test ends.
func Open(t testing.TB) *db.DB {
t.Helper()
ctx := context.Background()
d, err := db.Open(ctx, "sqlite", filepath.Join(t.TempDir(), "test.db"))
driver, dsn := NewDSN(t)
d, err := db.Open(ctx, driver, dsn)
if err != nil {
t.Fatalf("open db: %v", err)
}
+51 -7
View File
@@ -4,6 +4,8 @@ import (
"context"
"database/sql"
"errors"
"strconv"
"strings"
)
const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, lane, priority,
@@ -66,21 +68,63 @@ const laneRank = `CASE lane WHEN 'paid' THEN 0 ELSE 1 END`
// queueOrder is the one ordering used for claiming and for positions.
const queueOrder = laneRank + ` ASC, priority DESC, queued_at ASC, id ASC`
// NextQueuedJob returns the first queued job in the given lanes, locking it
// against other claimers. It must run inside a transaction. On Postgres the
// lock is FOR UPDATE SKIP LOCKED; on SQLite the immediate transaction
// already serializes writers.
func (s *Store) NextQueuedJob(ctx context.Context, lanes []string) (*Job, error) {
// claimWindow is how many queued jobs a claim looks at to find one whose
// required tags the worker has.
const claimWindow = 25
// NextQueuedJob returns the first queued job in the given lanes that the
// worker's tags qualify for, locking it against other claimers. It must
// run inside a transaction. On Postgres the lock is FOR UPDATE SKIP
// LOCKED; on SQLite the immediate transaction already serializes writers.
//
// A job with required tags is skipped by workers that lack one of them.
// The claim looks at the head of the queue, so a job that needs a rare tag
// waits its turn there without blocking the jobs behind it.
func (s *Store) NextQueuedJob(ctx context.Context, lanes []string, tags []string) (*Job, error) {
if !s.inTx {
return nil, errors.New("db: NextQueuedJob needs a transaction")
}
ph, args := in(lanes)
q := `SELECT ` + jobCols + ` FROM jobs WHERE status = 'queued' AND lane IN (` + ph + `)
ORDER BY ` + queueOrder + ` LIMIT 1`
ORDER BY ` + queueOrder + ` LIMIT ` + strconv.Itoa(claimWindow)
if s.db.Dialect == Postgres {
q += ` FOR UPDATE SKIP LOCKED`
}
return scanJob(s.row(ctx, q, args...))
jobs, err := scanJobs(s.rows(ctx, q, args...))
if err != nil {
return nil, err
}
for _, j := range jobs {
if HasTags(tags, j.RequiredTags) {
return j, nil
}
}
return nil, ErrNotFound
}
// HasTags reports whether a worker's tags include every required tag.
// required is a comma separated list; empty means "any worker".
func HasTags(have []string, required string) bool {
if required == "" {
return true
}
for _, need := range strings.Split(required, ",") {
need = strings.TrimSpace(need)
if need == "" {
continue
}
found := false
for _, h := range have {
if h == need {
found = true
break
}
}
if !found {
return false
}
}
return true
}
// MarkJobRunning hands a queued job to a worker.
+18
View File
@@ -0,0 +1,18 @@
-- +goose Up
-- Remote download workers. A worker authenticates with a bearer token of
-- which only the SHA-256 hash is stored. Tokens are per worker and can be
-- revoked without touching the others.
CREATE TABLE workers (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
tags TEXT NOT NULL DEFAULT '',
capacity INTEGER NOT NULL DEFAULT 0,
draining BOOLEAN NOT NULL DEFAULT FALSE,
revoked BOOLEAN NOT NULL DEFAULT FALSE,
version TEXT NOT NULL DEFAULT '',
last_seen_at BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL
);
-- +goose Down
DROP TABLE workers;
+64 -4
View File
@@ -2,11 +2,71 @@ package db
import (
"context"
"database/sql"
"errors"
"fmt"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
// openPostgres is replaced by the real implementation in Phase 4. Keeping
// the entry point here means the driver switch in Open never changes.
func openPostgres(_ context.Context, _ string) (*DB, error) {
return nil, errors.New("db: the postgres backend is not built into this version yet")
// openPostgres connects with pgx. The DSN is a connection URL such as
// postgres://user:pass@host:5432/dbname?sslmode=require.
func openPostgres(ctx context.Context, dsn string) (*DB, error) {
if dsn == "" {
return nil, errors.New("db: postgres needs a connection URL")
}
sqldb, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
sqldb.SetMaxOpenConns(20)
sqldb.SetMaxIdleConns(10)
if err := sqldb.PingContext(ctx); err != nil {
sqldb.Close()
// The driver's error can quote the DSN, which holds the password.
return nil, fmt.Errorf("db: cannot connect to postgres: %s", redactDSN(err.Error(), dsn))
}
return &DB{SQL: sqldb, Dialect: Postgres}, nil
}
// redactDSN removes the connection string from an error message.
func redactDSN(msg, dsn string) string {
out := msg
for i := 0; i+len(dsn) <= len(out); {
if out[i:i+len(dsn)] == dsn {
out = out[:i] + "[dsn]" + out[i+len(dsn):]
continue
}
i++
}
return out
}
// LockUser serializes transactions that check and then change a user's
// rows, such as "count active jobs, then insert one". SQLite does this by
// itself, because every transaction holds the write lock. Postgres runs
// transactions side by side, so two fast requests could both pass the
// check. The advisory lock is held until the transaction ends.
func (s *Store) LockUser(ctx context.Context, userID int64) error {
if s.db.Dialect != Postgres || !s.inTx {
return nil
}
_, err := s.q.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, userID)
return err
}
// LockJob takes a row lock on a job until the transaction ends, so that
// its status cannot change between reading it and acting on it. Without
// it Postgres lets, for example, a worker claim a job in the moment a
// requester cancels it. SQLite needs nothing: its transactions are serial.
func (s *Store) LockJob(ctx context.Context, jobID string) error {
if s.db.Dialect != Postgres || !s.inTx {
return nil
}
var id string
err := s.q.QueryRowContext(ctx, `SELECT id FROM jobs WHERE id = $1 FOR UPDATE`, jobID).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}
+140
View File
@@ -0,0 +1,140 @@
package db
import (
"context"
"database/sql"
)
// Worker is a registered download worker.
type Worker struct {
ID string
TokenHash string
Tags string // comma separated, as last advertised
Capacity int
Draining bool
Revoked bool
Version string // yt-dlp version, as last reported
LastSeenAt int64
CreatedAt int64
}
const workerCols = `id, token_hash, tags, capacity, draining, revoked, version, last_seen_at, created_at`
func scanWorker(sc interface{ Scan(...any) error }) (*Worker, error) {
var w Worker
err := sc.Scan(&w.ID, &w.TokenHash, &w.Tags, &w.Capacity, &w.Draining, &w.Revoked, &w.Version,
&w.LastSeenAt, &w.CreatedAt)
if err != nil {
return nil, notFound(err)
}
return &w, nil
}
// UpsertWorker registers a worker or replaces its token. Replacing the
// token also lifts a revocation: issuing a new token is how a worker is
// brought back.
func (s *Store) UpsertWorker(ctx context.Context, id, tokenHash string) error {
_, err := s.exec(ctx, `INSERT INTO workers (id, token_hash, created_at) VALUES (?, ?, ?)
ON CONFLICT (id) DO UPDATE SET token_hash = excluded.token_hash, revoked = ?`,
id, tokenHash, NowMilli(), false)
if isUniqueViolation(err) {
return ErrDuplicate
}
return err
}
// WorkerByToken finds the worker a token hash belongs to.
func (s *Store) WorkerByToken(ctx context.Context, tokenHash string) (*Worker, error) {
return scanWorker(s.row(ctx, `SELECT `+workerCols+` FROM workers WHERE token_hash = ?`, tokenHash))
}
// GetWorker loads a worker by ID.
func (s *Store) GetWorker(ctx context.Context, id string) (*Worker, error) {
return scanWorker(s.row(ctx, `SELECT `+workerCols+` FROM workers WHERE id = ?`, id))
}
// ListWorkers returns all workers, most recently seen first.
func (s *Store) ListWorkers(ctx context.Context) ([]*Worker, error) {
rows, err := s.rows(ctx, `SELECT `+workerCols+` FROM workers ORDER BY last_seen_at DESC, id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Worker
for rows.Next() {
w, err := scanWorker(rows)
if err != nil {
return nil, err
}
out = append(out, w)
}
return out, rows.Err()
}
// TouchWorker records what a worker advertised in its latest call.
func (s *Store) TouchWorker(ctx context.Context, id, tags string, capacity int, version string, now int64) error {
_, err := s.exec(ctx, `UPDATE workers SET tags = ?, capacity = ?,
version = CASE WHEN ? <> '' THEN ? ELSE version END, last_seen_at = ? WHERE id = ?`,
tags, capacity, version, version, now, id)
return err
}
// SetWorkerDraining turns draining on or off and reports whether the
// worker exists.
func (s *Store) SetWorkerDraining(ctx context.Context, id string, draining bool) (bool, error) {
n, err := s.exec(ctx, `UPDATE workers SET draining = ? WHERE id = ?`, draining, id)
return n == 1, err
}
// RevokeWorker makes a worker's token useless and reports whether the
// worker exists.
func (s *Store) RevokeWorker(ctx context.Context, id string) (bool, error) {
n, err := s.exec(ctx, `UPDATE workers SET revoked = ? WHERE id = ?`, true, id)
return n == 1, err
}
// RunningByWorker counts running jobs per worker.
func (s *Store) RunningByWorker(ctx context.Context) (map[string]int, error) {
rows, err := s.rows(ctx, `SELECT worker_id, COUNT(*) FROM jobs WHERE status = 'running' GROUP BY worker_id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]int{}
for rows.Next() {
var id string
var n int
if err := rows.Scan(&id, &n); err != nil {
return nil, err
}
out[id] = n
}
return out, rows.Err()
}
// QueueDepth counts queued jobs per lane and returns the age in
// milliseconds of the oldest one.
func (s *Store) QueueDepth(ctx context.Context, now int64) (paid, free int, oldestMS int64, err error) {
rows, err := s.rows(ctx, `SELECT lane, COUNT(*), MIN(queued_at) FROM jobs WHERE status = 'queued' GROUP BY lane`)
if err != nil {
return 0, 0, 0, err
}
defer rows.Close()
for rows.Next() {
var lane string
var n int
var oldest sql.NullInt64
if err := rows.Scan(&lane, &n, &oldest); err != nil {
return 0, 0, 0, err
}
if lane == LanePaid {
paid = n
} else {
free += n
}
if oldest.Valid && now-oldest.Int64 > oldestMS {
oldestMS = now - oldest.Int64
}
}
return paid, free, oldestMS, rows.Err()
}