Repeat downloads are instant, and the cache never bypasses a limit. - internal/cache: canonical key (extractor + video id + profile, URL hash fallback), per-bot file_id layer, stored copy layer, metadata layer, TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan sweeper, takedown that deletes, invalidates and blocks - One admission gate: a cache hit passes the same size, duration, quota, volume, active job and queue checks as a fresh download, is judged by the real cached file, and costs the same. It only skips the worker - Singleflight: a second requester joins the job that is queued or running for the same result. Each keeps their own caps, checked at delivery - Derive: lower profiles and audio are transcoded from a stored copy with ffmpeg; a higher profile that already fits is served as an alias; a failed derive falls back to a download - Self-healing: a rejected file_id falls back to the stored copy, then to a fresh download, and the entry is updated either way - Private or login-gated content and live streams are never cached - Playlists as per-item jobs started in turn, /subs, /history with resend, /fresh, owner /purge and /cache - Worker removes its temp files right after the upload Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
312 lines
12 KiB
Go
312 lines
12 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
)
|
|
|
|
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`
|
|
|
|
// 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) {
|
|
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`
|
|
if s.db.Dialect == Postgres {
|
|
q += ` FOR UPDATE SKIP LOCKED`
|
|
}
|
|
return scanJob(s.row(ctx, q, args...))
|
|
}
|
|
|
|
// 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()
|
|
}
|