Phase 3: cache

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>
This commit is contained in:
Michilis
2026-11-18 08:38:38 +00:00
co-authored by Claude Fable 5.2
parent 0d50f453a0
commit 9c9d641eda
39 changed files with 4121 additions and 121 deletions
+77 -8
View File
@@ -10,7 +10,7 @@ const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status,
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`
started_at, finished_at, source_key, tg_file_id, cacheable, cache_hit`
func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
var j Job
@@ -18,7 +18,8 @@ func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
&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.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)
}
@@ -44,12 +45,13 @@ func scanJobs(rows *sql.Rows, err error) ([]*Job, error) {
// 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.StartedAt, j.FinishedAt, j.SourceKey, j.TgFileID, j.Cacheable, j.CacheHit)
return err
}
@@ -111,18 +113,20 @@ type JobResult struct {
VideoID string
}
// CompleteJob stores the result and moves the job to delivering.
// 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 ? <> '' THEN ? ELSE extractor END,
video_id = CASE WHEN ? <> '' THEN ? ELSE video_id 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.Extractor, r.VideoID, r.VideoID,
r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.VideoID,
now, id, workerID)
return n == 1, err
}
@@ -240,3 +244,68 @@ 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()
}