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
+19
View File
@@ -3,6 +3,7 @@ package sched
import (
"context"
"errors"
"io"
"os"
"time"
@@ -63,6 +64,24 @@ func (l *Local) Upload(ctx context.Context, job *workerproto.Job, path string) e
return l.Storage.Put(ctx, job.UploadKey, f, st.Size())
}
// Fetch copies a stored source file to a local path, for derive jobs.
func (l *Local) Fetch(ctx context.Context, job *workerproto.Job, path string) error {
rc, _, err := l.Storage.Open(ctx, job.SourceKey)
if err != nil {
return err
}
defer rc.Close()
f, err := os.Create(path)
if err != nil {
return err
}
if _, err := io.Copy(f, rc); err != nil {
f.Close()
return err
}
return f.Close()
}
// leaseError marks ErrLeaseLost for the worker package, which cannot import
// this one.
type leaseError struct{ error }
+145 -19
View File
@@ -168,6 +168,32 @@ type EnqueueParams struct {
WalletID string
ChargeSats int64
QuotaDay int
// Kind is the job kind, download by default.
Kind string
// CacheKey identifies the result, so a second requester for the same
// result can share the job.
CacheKey string
// Cacheable says the result may be kept in the cache.
Cacheable bool
// SourceKey is the stored copy a derive job transcodes from.
SourceKey string
// Hit, when set, makes the job a cache hit: it is created already
// finished and never waits for a worker.
Hit *CacheHit
}
// CacheHit describes a cached result a job is served from.
type CacheHit struct {
StorageKey string
TgFileID string
FileExt string
FileSize int64
Duration int64
Width int
Height int
Title string
Uploader string
}
// Enqueue adds a job with one delivery in its own transaction.
@@ -198,13 +224,19 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams
if p.Lane == "" {
p.Lane = db.LaneFree
}
if p.Kind == "" {
p.Kind = db.KindDownload
}
job := &db.Job{
ID: ids.New(),
Kind: db.KindDownload,
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,
@@ -216,24 +248,22 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams
CreatedAt: now,
QueuedAt: now,
}
del := &db.Delivery{
ID: ids.New(),
JobID: job.ID,
RequestID: p.RequestID,
UserID: p.UserID,
ChatID: p.ChatID,
ChatType: p.ChatType,
ReplyToMessageID: p.ReplyToMessageID,
StatusMessageID: p.StatusMessageID,
StatusIsPhoto: p.StatusIsPhoto,
Lang: p.Lang,
Status: db.DeliveryPending,
CreatedAt: now,
Source: p.Source,
WalletID: p.WalletID,
ChargeSats: p.ChargeSats,
QuotaDay: p.QuotaDay,
if h := p.Hit; h != nil {
// Served from the cache: the result exists, so the job starts in
// the state a worker would have left it in.
job.Status = db.JobDelivering
job.CacheHit = true
job.StorageKey, job.TgFileID, job.FileExt = h.StorageKey, h.TgFileID, h.FileExt
job.FileSize, job.Duration, job.Width, job.Height = h.FileSize, h.Duration, h.Width, h.Height
if h.Title != "" {
job.Title = h.Title
}
if h.Uploader != "" {
job.Uploader = h.Uploader
}
job.StartedAt, job.FinishedAt = now, now
}
del := s.newDelivery(job.ID, p, now)
if p.ActiveLimit > 0 {
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
@@ -261,14 +291,104 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams
return job, del, nil
}
func (s *Scheduler) newDelivery(jobID string, p EnqueueParams, now int64) *db.Delivery {
return &db.Delivery{
ID: ids.New(),
JobID: jobID,
RequestID: p.RequestID,
UserID: p.UserID,
ChatID: p.ChatID,
ChatType: p.ChatType,
ReplyToMessageID: p.ReplyToMessageID,
StatusMessageID: p.StatusMessageID,
StatusIsPhoto: p.StatusIsPhoto,
Lang: p.Lang,
Status: db.DeliveryPending,
CreatedAt: now,
Source: p.Source,
WalletID: p.WalletID,
ChargeSats: p.ChargeSats,
QuotaDay: p.QuotaDay,
MaxSize: p.MaxSize,
MaxDuration: p.MaxDuration,
}
}
// covers reports whether a job cap is at least as loose as a requester's
// cap, where 0 means "no cap".
func covers(jobCap, myCap int64) bool {
return jobCap == 0 || (myCap != 0 && jobCap >= myCap)
}
// AttachTx adds a requester to a job that is already queued or running
// for the same result, so the file is fetched once and everyone is
// notified when it is done. It reports false when the job cannot be
// shared: a running job was started under tighter caps than this
// requester has, and would fail or fall short for them.
//
// A queued job is lifted instead: its caps become the looser of the two
// and it moves to the paid lane when the newcomer pays, which also speeds
// 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 {
n, err := tx.CountActiveDeliveries(ctx, p.UserID)
if err != nil {
return nil, false, err
}
if n >= p.ActiveLimit {
return nil, false, ErrTooManyActive
}
}
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)
if err != nil {
return nil, false, err
}
shared = shared || raised
}
if !shared {
return nil, false, nil
}
del := s.newDelivery(job.ID, p, s.now())
if err := tx.InsertDelivery(ctx, del); err != nil {
return nil, false, err
}
return del, true, nil
}
// Announce tells listeners and waiting workers about a committed job.
func (s *Scheduler) Announce(job *db.Job, del *db.Delivery) {
s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID,
"profile", job.Profile, "lane", job.Lane, "source", del.Source)
"profile", job.Profile, "lane", job.Lane, "source", del.Source, "kind", job.Kind, "cache_hit", job.CacheHit)
if job.CacheHit {
s.emit(EventStored, job.ID) // nothing to wait for: deliver now
return
}
s.emit(EventQueued, job.ID)
s.notifyWork()
}
// AnnounceAttached tells listeners that a requester joined a job.
func (s *Scheduler) AnnounceAttached(job *db.Job, del *db.Delivery) {
s.log.Info("requester attached to job", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID)
s.emit(EventRequeued, job.ID) // refreshes status messages
s.notifyWork()
}
// Redownload turns a job that was meant to be served from the cache into
// a plain download, when the cached file turned out to be unusable.
func (s *Scheduler) Redownload(ctx context.Context, jobID string) (bool, error) {
ok, err := s.store.RedownloadJob(ctx, jobID, []string{db.JobDelivering}, s.now())
if err != nil || !ok {
return false, err
}
s.log.Info("cached file unusable, downloading again", "job_id", jobID)
s.emit(EventRequeued, jobID)
s.notifyWork()
return true, nil
}
// Claim order: paid jobs first, then free.
var (
allLanes = []string{db.LanePaid, db.LaneFree}
@@ -367,6 +487,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w
Profile: job.Profile,
MaxSize: job.MaxSize,
MaxDuration: job.MaxDuration,
SourceKey: job.SourceKey,
UploadKey: UploadKey(job.ID),
Attempt: job.Attempts,
LeaseSeconds: int(s.cfg.Lease.Seconds()),
@@ -474,6 +595,11 @@ func (s *Scheduler) Fail(ctx context.Context, req workerproto.FailRequest) error
ev = EventCancelled
_, err = tx.FinishJob(ctx, job.ID, db.JobCancelled, string(ytdlp.CodeCancelled), req.Detail,
[]string{db.JobRunning}, s.now())
case job.Kind == db.KindDerive && req.Code != string(ytdlp.CodeWorkerLost):
// Transcoding from the stored copy did not work. Downloading
// the profile directly is the fallback, at no cost in attempts.
ev = EventRequeued
_, err = tx.RedownloadJob(ctx, job.ID, []string{db.JobRunning}, s.now())
case req.Retryable && req.Code == string(ytdlp.CodeWorkerLost):
// A clean worker shutdown is not the job's fault: hand it to
// another worker without spending an attempt.