Files
Media-download-telegram-bot/internal/db/jobs.go
T
MichilisandClaude Fable 5.2 7d4893bc3f 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>
2026-11-18 09:27:11 +00:00

356 lines
14 KiB
Go

package db
import (
"context"
"database/sql"
"errors"
"strconv"
"strings"
)
const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, lane, priority,
required_tags, max_size, max_duration, attempts, max_attempts, worker_id, lease_expires_at,
cancel_requested, stage, progress_bytes, total_bytes, error_code, error_detail, storage_key,
file_ext, file_size, duration, width, height, title, uploader, created_at, queued_at,
started_at, finished_at, source_key, tg_file_id, cacheable, cache_hit`
func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
var j Job
err := sc.Scan(&j.ID, &j.Kind, &j.URL, &j.Extractor, &j.VideoID, &j.Profile, &j.CacheKey, &j.Status,
&j.Lane, &j.Priority, &j.RequiredTags, &j.MaxSize, &j.MaxDuration, &j.Attempts, &j.MaxAttempts,
&j.WorkerID, &j.LeaseExpiresAt, &j.CancelRequested, &j.Stage, &j.ProgressBytes, &j.TotalBytes,
&j.ErrorCode, &j.ErrorDetail, &j.StorageKey, &j.FileExt, &j.FileSize, &j.Duration, &j.Width,
&j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt,
&j.SourceKey, &j.TgFileID, &j.Cacheable, &j.CacheHit)
if err != nil {
return nil, notFound(err)
}
return &j, nil
}
func scanJobs(rows *sql.Rows, err error) ([]*Job, error) {
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Job
for rows.Next() {
j, err := scanJob(rows)
if err != nil {
return nil, err
}
out = append(out, j)
}
return out, rows.Err()
}
// InsertJob stores a new job.
func (s *Store) InsertJob(ctx context.Context, j *Job) error {
_, err := s.exec(ctx, `INSERT INTO jobs (`+jobCols+`) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?)`,
j.ID, j.Kind, j.URL, j.Extractor, j.VideoID, j.Profile, j.CacheKey, j.Status, j.Lane, j.Priority,
j.RequiredTags, j.MaxSize, j.MaxDuration, j.Attempts, j.MaxAttempts, j.WorkerID, j.LeaseExpiresAt,
j.CancelRequested, j.Stage, j.ProgressBytes, j.TotalBytes, j.ErrorCode, j.ErrorDetail, j.StorageKey,
j.FileExt, j.FileSize, j.Duration, j.Width, j.Height, j.Title, j.Uploader, j.CreatedAt, j.QueuedAt,
j.StartedAt, j.FinishedAt, j.SourceKey, j.TgFileID, j.Cacheable, j.CacheHit)
return err
}
// GetJob loads a job.
func (s *Store) GetJob(ctx context.Context, id string) (*Job, error) {
return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs WHERE id = ?`, id))
}
// laneRank is the SQL expression that orders lanes: paid before free.
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`
// 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 ` + strconv.Itoa(claimWindow)
if s.db.Dialect == Postgres {
q += ` FOR UPDATE SKIP LOCKED`
}
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.
func (s *Store) MarkJobRunning(ctx context.Context, id, workerID string, leaseUntil, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET status = 'running', worker_id = ?, lease_expires_at = ?,
attempts = attempts + 1, started_at = ?, stage = '', progress_bytes = 0, total_bytes = 0
WHERE id = ? AND status = 'queued'`, workerID, leaseUntil, now, id)
return n == 1, err
}
// HeartbeatJob extends the lease and stores progress. It reports false when
// the job is no longer owned by the worker.
func (s *Store) HeartbeatJob(ctx context.Context, id, workerID string, leaseUntil int64, stage string, done, total int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET lease_expires_at = ?, stage = ?, progress_bytes = ?, total_bytes = ?
WHERE id = ? AND worker_id = ? AND status = 'running'`, leaseUntil, stage, done, total, id, workerID)
return n == 1, err
}
// JobResult is what a worker reports on success.
type JobResult struct {
StorageKey string
FileExt string
FileSize int64
Duration int64
Width int
Height int
Title string
Uploader string
Extractor string
VideoID string
}
// CompleteJob stores the result and moves the job to delivering. The
// extractor and video ID a job was queued with are its cache key and are
// kept; the worker's values only fill them in when they were empty.
func (s *Store) CompleteJob(ctx context.Context, id, workerID string, r JobResult, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET status = 'delivering', storage_key = ?, file_ext = ?, file_size = ?,
duration = ?, width = ?, height = ?,
title = CASE WHEN ? <> '' THEN ? ELSE title END,
uploader = CASE WHEN ? <> '' THEN ? ELSE uploader END,
extractor = CASE WHEN extractor = '' THEN ? ELSE extractor END,
video_id = CASE WHEN video_id = '' THEN ? ELSE video_id END,
lease_expires_at = 0, stage = 'uploading', finished_at = ?
WHERE id = ? AND worker_id = ? AND status = 'running'`,
r.StorageKey, r.FileExt, r.FileSize, r.Duration, r.Width, r.Height,
r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.VideoID,
now, id, workerID)
return n == 1, err
}
// RequeueJob puts a running job back in the queue. The original queued_at is
// kept so a retried job does not lose its place. refundAttempt gives the
// attempt back, for interruptions that were not the job's fault.
func (s *Store) RequeueJob(ctx context.Context, id, errorCode, detail string, refundAttempt bool) (bool, error) {
refund := 0
if refundAttempt {
refund = 1
}
n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', worker_id = '', lease_expires_at = 0,
stage = '', progress_bytes = 0, total_bytes = 0, error_code = ?, error_detail = ?,
attempts = attempts - ?
WHERE id = ? AND status = 'running'`, errorCode, detail, refund, id)
return n == 1, err
}
// FinishJob moves a job to a terminal status from any of the given statuses.
func (s *Store) FinishJob(ctx context.Context, id, status, errorCode, detail string, from []string, now int64) (bool, error) {
ph, args := in(from)
all := append([]any{status, errorCode, detail, now, id}, args...)
n, err := s.exec(ctx, `UPDATE jobs SET status = ?, error_code = ?, error_detail = ?, lease_expires_at = 0,
finished_at = ? WHERE id = ? AND status IN (`+ph+`)`, all...)
return n == 1, err
}
// RequestJobCancel flags a running job so the worker stops at its next
// heartbeat.
func (s *Store) RequestJobCancel(ctx context.Context, id string) error {
_, err := s.exec(ctx, `UPDATE jobs SET cancel_requested = ? WHERE id = ? AND status = 'running'`, true, id)
return err
}
// ExpiredJobs lists running jobs whose lease ran out.
func (s *Store) ExpiredJobs(ctx context.Context, now int64) ([]*Job, error) {
return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs
WHERE status = 'running' AND lease_expires_at < ? ORDER BY id`, now))
}
// JobsByStatus lists jobs in a status, oldest first.
func (s *Store) JobsByStatus(ctx context.Context, status string, limit int) ([]*Job, error) {
return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status = ? ORDER BY `+queueOrder+` LIMIT ?`,
status, limit))
}
// CountQueued counts queued jobs in a lane.
func (s *Store) CountQueued(ctx context.Context, lane string) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND lane = ?`, lane).Scan(&n)
return n, err
}
// QueuePosition returns how many queued jobs are ahead of j in claim order.
// Zero means j is next.
func (s *Store) QueuePosition(ctx context.Context, j *Job) (int, error) {
rank := 1
if j.Lane == LanePaid {
rank = 0
}
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND id <> ? AND (
`+laneRank+` < ?
OR (`+laneRank+` = ? AND (
priority > ?
OR (priority = ? AND (queued_at < ? OR (queued_at = ? AND id < ?)))
))
)`, j.ID, rank, rank, j.Priority, j.Priority, j.QueuedAt, j.QueuedAt, j.ID).Scan(&n)
return n, err
}
// AvgJobSeconds returns the average run time of the most recent finished
// jobs, or 0 when there is no history.
func (s *Store) AvgJobSeconds(ctx context.Context, sample int) (float64, error) {
var avg sql.NullFloat64
err := s.row(ctx, `SELECT AVG(d) FROM (
SELECT (finished_at - started_at) / 1000.0 AS d FROM jobs
WHERE status IN ('done', 'delivering') AND started_at > 0 AND finished_at >= started_at
ORDER BY finished_at DESC LIMIT ?
) recent`, sample).Scan(&avg)
return avg.Float64, err
}
// CountRunning counts jobs currently held by workers.
func (s *Store) CountRunning(ctx context.Context) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'running'`).Scan(&n)
return n, err
}
// CountRunningByLane counts running jobs, in total and in the free lane.
func (s *Store) CountRunningByLane(ctx context.Context) (total, free int, err error) {
rows, err := s.rows(ctx, `SELECT lane, COUNT(*) FROM jobs WHERE status = 'running' GROUP BY lane`)
if err != nil {
return 0, 0, err
}
defer rows.Close()
for rows.Next() {
var lane string
var n int
if err := rows.Scan(&lane, &n); err != nil {
return 0, 0, err
}
total += n
if lane == LaneFree {
free += n
}
}
return total, free, rows.Err()
}
// PromoteJob moves a queued free job to the paid lane.
func (s *Store) PromoteJob(ctx context.Context, id string) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET lane = 'paid' WHERE id = ? AND status = 'queued' AND lane = 'free'`, id)
return n == 1, err
}
// ActiveJobForKey returns the newest queued or running job for a cache
// key, which a second requester can share, or ErrNotFound.
func (s *Store) ActiveJobForKey(ctx context.Context, cacheKey string) (*Job, error) {
return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs
WHERE cache_key = ? AND status IN ('queued', 'running') ORDER BY id DESC LIMIT 1`, cacheKey))
}
// RaiseJob lifts a queued job to cover another requester: the caps become
// the looser of the two (0 means no cap) and the lane becomes paid when
// the newcomer pays.
func (s *Store) RaiseJob(ctx context.Context, id string, maxSize, maxDuration int64, lane string) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET
max_size = CASE WHEN max_size = 0 OR ? = 0 THEN 0 WHEN ? > max_size THEN ? ELSE max_size END,
max_duration = CASE WHEN max_duration = 0 OR ? = 0 THEN 0 WHEN ? > max_duration THEN ? ELSE max_duration END,
lane = CASE WHEN ? = 'paid' THEN 'paid' ELSE lane END
WHERE id = ? AND status = 'queued'`,
maxSize, maxSize, maxSize, maxDuration, maxDuration, maxDuration, lane, id)
return n == 1, err
}
// RedownloadJob turns a job that could not be served from the cache or
// derived from a stored copy into a plain download and queues it. The
// attempt counter starts over: nothing was the job's fault.
func (s *Store) RedownloadJob(ctx context.Context, id string, from []string, now int64) (bool, error) {
ph, args := in(from)
all := append([]any{KindDownload, false, now, id}, args...)
n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', kind = ?, cache_hit = ?, source_key = '',
tg_file_id = '', storage_key = '', worker_id = '', lease_expires_at = 0, attempts = 0, stage = '',
progress_bytes = 0, total_bytes = 0, queued_at = ?, error_code = '', error_detail = ''
WHERE id = ? AND status IN (`+ph+`)`, all...)
return n == 1, err
}
// SetJobFileID records the Telegram file_id a job's file got.
func (s *Store) SetJobFileID(ctx context.Context, id, fileID string) error {
_, err := s.exec(ctx, `UPDATE jobs SET tg_file_id = ? WHERE id = ?`, fileID, id)
return err
}
// JobStorageKeys lists the storage keys still referenced by jobs that are
// not finished, so the orphan sweeper leaves them alone.
func (s *Store) JobStorageKeys(ctx context.Context) (map[string]bool, error) {
rows, err := s.rows(ctx, `SELECT id, storage_key, source_key FROM jobs
WHERE status IN ('queued', 'running', 'delivering')`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]bool{}
for rows.Next() {
var id, key, src string
if err := rows.Scan(&id, &key, &src); err != nil {
return nil, err
}
out["jobs/"+id+"/media"] = true
if key != "" {
out[key] = true
}
if src != "" {
out[src] = true
}
}
return out, rows.Err()
}