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
+495
View File
@@ -0,0 +1,495 @@
package cache_test
import (
"context"
"errors"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/noderunners/dlbot/internal/cache"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/db/dbtest"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/storage"
)
const botID = int64(777)
type rig struct {
t *testing.T
store *db.Store
st *storage.Local
c *cache.Cache
now atomic.Int64
seq int
}
func newRig(t *testing.T, mut func(*cache.Config)) *rig {
t.Helper()
st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files"))
if err != nil {
t.Fatal(err)
}
cfg := cache.Config{
Enabled: true, TTLDefault: 7 * 24 * time.Hour, TTLStable: 30 * 24 * time.Hour,
TTLEphemeral: 6 * time.Hour, Stable: []string{"youtube"}, Ephemeral: []string{"twitter", "generic"},
MetaTTL: 30 * time.Minute, Derive: true,
}
if mut != nil {
mut(&cfg)
}
r := &rig{t: t, store: dbtest.Open(t).Store(), st: st}
r.now.Store(time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC).UnixMilli())
r.c = cache.New(cfg, botID, r.store, st, nil)
r.c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
return r
}
func (r *rig) advance(d time.Duration) { r.now.Add(d.Milliseconds()) }
// put stores a result of the given size as a finished job would.
func (r *rig) put(extractor, videoID, profile string, size int64, height int, fileID string) *db.Job {
r.t.Helper()
r.seq++
key := "jobs/job" + strings.Repeat("0", 3) + string(rune('a'+r.seq)) + "/media"
if err := r.st.Put(context.Background(), key, strings.NewReader(strings.Repeat("x", int(size))), size); err != nil {
r.t.Fatal(err)
}
job := &db.Job{
ID: "job" + string(rune('a'+r.seq)), Extractor: extractor, VideoID: videoID, Profile: profile,
StorageKey: key, FileSize: size, FileExt: "mp4", Duration: 60, Width: height * 16 / 9, Height: height,
Title: "T", Cacheable: true,
}
if err := r.c.Put(context.Background(), job, fileID, "u-"+fileID); err != nil {
r.t.Fatalf("Put: %v", err)
}
return job
}
func (r *rig) lookup(extractor, videoID string, p media.Profile) *db.CacheEntry {
r.t.Helper()
e, err := r.c.Lookup(context.Background(), extractor, videoID, p)
if err != nil {
r.t.Fatal(err)
}
return e
}
func (r *rig) stored(key string) bool {
_, err := r.st.Stat(context.Background(), key)
return err == nil
}
func TestCanonical(t *testing.T) {
tests := []struct {
name string
extractor, id, url string
wantExt, wantID string
}{
{"plain", "youtube", "dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"},
{"short link, same video", "youtube", "dQw4w9WgXcQ", "https://youtu.be/dQw4w9WgXcQ?t=5", "youtube", "dQw4w9WgXcQ"},
{"extractor case and suffix", "Youtube:tab", "abc", "https://youtube.com/x", "youtube", "abc"},
{"spaces", " vimeo ", " 123 ", "https://vimeo.com/123", "vimeo", "123"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ext, id := cache.Canonical(tc.extractor, tc.id, tc.url)
if ext != tc.wantExt || id != tc.wantID {
t.Fatalf("Canonical = %q, %q; want %q, %q", ext, id, tc.wantExt, tc.wantID)
}
})
}
// The generic extractor names files after the end of the URL, so two
// sites can produce the same ID. Its key must come from the whole URL.
e1, id1 := cache.Canonical("generic", "video", "https://a.example/video.mp4")
e2, id2 := cache.Canonical("generic", "video", "https://b.example/video.mp4")
_, id3 := cache.Canonical("generic", "video", "https://a.example/video.mp4")
if e1 != "generic" || e2 != "generic" || id1 == id2 {
t.Fatalf("generic IDs must differ per URL: %q vs %q", id1, id2)
}
if id1 != id3 || !strings.HasPrefix(id1, "url-") || id1 == "video" {
t.Fatalf("generic IDs must be stable hashes: %q, %q", id1, id3)
}
// A missing ID or extractor falls back the same way.
if ext, id := cache.Canonical("", "", "https://x.example/y"); ext != "generic" || !strings.HasPrefix(id, "url-") {
t.Fatalf("empty metadata: %q, %q", ext, id)
}
if _, id := cache.Canonical("vimeo", "", "https://vimeo.com/1"); !strings.HasPrefix(id, "url-") {
t.Fatalf("missing ID: %q", id)
}
if a, b := cache.JobKey("youtube", "abc", "720"), cache.JobKey("youtube", "abc", "480"); a == b {
t.Fatal("profiles must have separate job keys")
}
}
func TestCacheable(t *testing.T) {
for av, want := range map[string]bool{
"": true, "public": true, "unlisted": true,
"private": false, "needs_auth": false, "premium_only": false, "subscriber_only": false,
} {
if got := cache.Cacheable(av, false); got != want {
t.Errorf("Cacheable(%q) = %v, want %v", av, got, want)
}
}
if cache.Cacheable("public", true) {
t.Error("live streams are never cached")
}
}
func TestPutLookupAndReplace(t *testing.T) {
r := newRig(t, nil)
ctx := context.Background()
if e := r.lookup("youtube", "v1", media.P720); e != nil {
t.Fatalf("empty cache returned %+v", e)
}
first := r.put("youtube", "v1", "720", 1000, 720, "file-1")
e := r.lookup("youtube", "v1", media.P720)
if e == nil || e.TgFileID != "file-1" || e.TgFileUniqueID != "u-file-1" || e.StorageKey != first.StorageKey ||
e.Size != 1000 || e.Height != 720 || e.BotID != botID || e.Status != db.CacheReady {
t.Fatalf("entry = %+v", e)
}
if r.lookup("youtube", "v1", media.P480) != nil || r.lookup("youtube", "v2", media.P720) != nil {
t.Fatal("lookup must match extractor, video and profile exactly")
}
r.c.RecordHit(ctx, e)
r.c.RecordHit(ctx, e)
r.c.RecordMiss()
if e := r.lookup("youtube", "v1", media.P720); e.Hits != 2 {
t.Fatalf("hits = %d", e.Hits)
}
if st := r.c.Stats(); st.Hits != 2 || st.Misses != 1 || st.BytesSaved != 2000 {
t.Fatalf("stats = %+v", st)
}
// A newer result for the same key replaces the stored copy and keeps
// the hit count.
second := r.put("youtube", "v1", "720", 1200, 720, "file-2")
e = r.lookup("youtube", "v1", media.P720)
if e.TgFileID != "file-2" || e.StorageKey != second.StorageKey || e.Size != 1200 || e.Hits != 2 {
t.Fatalf("replaced entry = %+v", e)
}
if r.stored(first.StorageKey) || !r.stored(second.StorageKey) {
t.Fatal("the replaced copy must be deleted, the new one kept")
}
// file_ids belong to one bot. Another bot on the same database sees
// nothing.
other := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour}, botID+1, r.store, r.st, nil)
if e, _ := other.Lookup(ctx, "youtube", "v1", media.P720); e != nil {
t.Fatalf("another bot got this bot's entry: %+v", e)
}
// A disabled cache finds nothing and stores nothing.
off := cache.New(cache.Config{Enabled: false}, botID, r.store, r.st, nil)
if e, _ := off.Lookup(ctx, "youtube", "v1", media.P720); e != nil {
t.Fatal("a disabled cache must not serve")
}
if err := off.Put(ctx, second, "x", ""); err == nil {
t.Fatal("a disabled cache must not store")
}
notCacheable := *second
notCacheable.Cacheable = false
if err := r.c.Put(ctx, &notCacheable, "x", ""); err == nil {
t.Fatal("a job that is not cacheable must be refused")
}
}
func TestTTLBySourceType(t *testing.T) {
r := newRig(t, nil)
stable := r.put("youtube", "s", "best", 10, 1080, "f1") // 30 days
normal := r.put("vimeo", "n", "best", 10, 1080, "f2") // 7 days
ephemeral := r.put("twitter", "e", "best", 10, 720, "f3") // 6 hours
generic := r.put("generic", "url-abc", "best", 10, 720, "f4") // 6 hours
alive := func() (s, n, e, g bool) {
return r.lookup("youtube", "s", media.Best) != nil, r.lookup("vimeo", "n", media.Best) != nil,
r.lookup("twitter", "e", media.Best) != nil, r.lookup("generic", "url-abc", media.Best) != nil
}
if s, n, e, g := alive(); !s || !n || !e || !g {
t.Fatal("fresh entries must all be served")
}
r.advance(7 * time.Hour)
if s, n, e, g := alive(); !s || !n || e || g {
t.Fatalf("after 7h: stable=%v normal=%v ephemeral=%v generic=%v", s, n, e, g)
}
res, err := r.c.Sweep(context.Background())
if err != nil || res.Expired != 2 {
t.Fatalf("sweep = %+v, %v", res, err)
}
if r.stored(ephemeral.StorageKey) || r.stored(generic.StorageKey) || !r.stored(stable.StorageKey) {
t.Fatal("expired entries lose their files, live ones keep them")
}
r.advance(8 * 24 * time.Hour)
if s, n, _, _ := alive(); !s || n {
t.Fatalf("after 8 days: stable=%v normal=%v", s, n)
}
r.advance(30 * 24 * time.Hour)
if _, err := r.c.Sweep(context.Background()); err != nil {
t.Fatal(err)
}
if r.stored(stable.StorageKey) || r.stored(normal.StorageKey) {
t.Fatal("everything is expired and swept by now")
}
}
func TestBudgetEvictsLeastValuableStoredCopies(t *testing.T) {
r := newRig(t, func(c *cache.Config) { c.BudgetBytes = 2500 })
ctx := context.Background()
old := r.put("vimeo", "old", "best", 1000, 720, "f-old")
r.advance(time.Hour)
popular := r.put("vimeo", "popular", "best", 1000, 720, "f-pop")
r.advance(time.Hour)
recent := r.put("vimeo", "recent", "best", 1000, 720, "f-new")
// "popular" is older than "recent" but was requested many times.
e := r.lookup("vimeo", "popular", media.Best)
for i := 0; i < 5; i++ {
r.c.RecordHit(ctx, e)
}
// 3000 bytes against a budget of 2500: one copy has to go, and it is
// the one nobody asked for in the longest time.
res, err := r.c.Sweep(ctx)
if err != nil || res.Evicted != 1 {
t.Fatalf("sweep = %+v, %v", res, err)
}
if r.stored(old.StorageKey) || !r.stored(popular.StorageKey) || !r.stored(recent.StorageKey) {
t.Fatal("the wrong copy was evicted")
}
// The evicted entry still serves instant resends through its file_id.
e = r.lookup("vimeo", "old", media.Best)
if e == nil || e.TgFileID != "f-old" || e.StorageKey != "" {
t.Fatalf("evicted entry = %+v", e)
}
// Hits outweigh recency: with room for one copy, "popular" survives
// although "recent" is newer.
r.advance(time.Minute)
small := newRigConfig(r, 1000)
if res, err := small.Sweep(ctx); err != nil || res.Evicted != 1 {
t.Fatalf("second sweep = %+v, %v", res, err)
}
if !r.stored(popular.StorageKey) || r.stored(recent.StorageKey) {
t.Fatal("hit count must protect the popular entry")
}
// An entry with neither file_id nor stored copy is removed entirely.
lone := r.put("vimeo", "lone", "best", 1000, 720, "")
tiny := newRigConfig(r, 1)
if _, err := tiny.Sweep(ctx); err != nil {
t.Fatal(err)
}
if r.stored(lone.StorageKey) {
t.Fatal("the copy should be gone")
}
if _, err := r.store.GetCacheEntry(ctx, botID, "vimeo", "lone", "best"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("an entry with nothing to serve must be deleted: %v", err)
}
}
// newRigConfig returns a cache on the same data with another budget.
func newRigConfig(r *rig, budget int64) *cache.Cache {
c := cache.New(cache.Config{Enabled: true, BudgetBytes: budget, TTLDefault: 7 * 24 * time.Hour}, botID, r.store, r.st, nil)
c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
return c
}
func TestRelatedAliasAndDeriveSource(t *testing.T) {
r := newRig(t, nil)
ctx := context.Background()
// A 1080p "best" is stored. 720 and 480 can be transcoded from it,
// and so can audio.
r.put("youtube", "hd", "best", 5000, 1080, "f-hd")
for _, p := range []media.Profile{media.P720, media.P480, media.MP3, media.M4A} {
alias, source, err := r.c.Related(ctx, "youtube", "hd", p)
if err != nil || alias != nil || source == nil || source.Profile != "best" {
t.Errorf("%s: alias=%v source=%+v err=%v, want the best copy as source", p, alias, source, err)
}
}
// Nothing sits above best.
if alias, source, _ := r.c.Related(ctx, "youtube", "hd", media.Best); alias != nil || source != nil {
t.Error("best has nothing to derive from")
}
// A 360p "best" is stored. Asked for as 720 or 480 it is already the
// file yt-dlp would fetch, so it is served as is, without transcoding.
r.put("youtube", "sd", "best", 800, 360, "f-sd")
for _, p := range []media.Profile{media.P720, media.P480} {
alias, source, err := r.c.Related(ctx, "youtube", "sd", p)
if err != nil || source != nil || alias == nil || alias.TgFileID != "f-sd" {
t.Errorf("%s: alias=%+v source=%v err=%v, want the 360p file as alias", p, alias, source, err)
}
}
// The nearest profile above wins as a source: less work to scale.
r.put("youtube", "multi", "best", 9000, 2160, "f-4k")
r.put("youtube", "multi", "720", 2000, 720, "f-720")
if _, source, _ := r.c.Related(ctx, "youtube", "multi", media.P480); source == nil || source.Profile != "720" {
t.Errorf("480 should derive from the 720 copy, got %+v", source)
}
// Without a stored copy there is nothing to transcode from.
r.put("vimeo", "nofile", "best", 5000, 1080, "f-x")
e := r.lookup("vimeo", "nofile", media.Best)
if err := r.c.DropStored(ctx, "vimeo", "nofile", "best"); err != nil {
t.Fatal(err)
}
if _, source, _ := r.c.Related(ctx, "vimeo", "nofile", media.P720); source != nil {
t.Errorf("an entry without a stored copy (was %s) cannot be a source", e.StorageKey)
}
// Deriving can be switched off.
noDerive := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour, Derive: false}, botID, r.store, r.st, nil)
noDerive.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
if _, source, _ := noDerive.Related(ctx, "youtube", "hd", media.P720); source != nil {
t.Error("derive is off, no source expected")
}
if alias, _, _ := noDerive.Related(ctx, "youtube", "sd", media.P720); alias == nil {
t.Error("aliases need no transcoding and still work with derive off")
}
}
func TestPurgeDeletesInvalidatesAndBlocks(t *testing.T) {
r := newRig(t, nil)
ctx := context.Background()
a := r.put("youtube", "bad", "best", 100, 1080, "f-a")
b := r.put("youtube", "bad", "mp3", 50, 0, "f-b")
keep := r.put("youtube", "good", "best", 100, 1080, "f-k")
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); blocked {
t.Fatal("nothing is blocked yet")
}
n, err := r.c.Purge(ctx, "youtube", "bad", "copyright notice", 1)
if err != nil || n != 2 {
t.Fatalf("Purge = %d, %v", n, err)
}
if r.stored(a.StorageKey) || r.stored(b.StorageKey) || !r.stored(keep.StorageKey) {
t.Fatal("purge must delete exactly the files of that video")
}
if r.lookup("youtube", "bad", media.Best) != nil || r.lookup("youtube", "bad", media.MP3) != nil {
t.Fatal("a purged video must not be served")
}
e, err := r.store.GetCacheEntry(ctx, botID, "youtube", "bad", "best")
if err != nil || e.Status != db.CacheBlocked || e.TgFileID != "" || e.StorageKey != "" {
t.Fatalf("purged entry = %+v, %v", e, err)
}
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); !blocked {
t.Fatal("the key must be blocked")
}
if blocked, _ := r.c.Blocked(ctx, "youtube", "good", "youtube.com"); blocked {
t.Fatal("other videos stay available")
}
// A blocked key cannot be cached again, whatever finishes later.
late := *a
late.StorageKey = "jobs/late/media"
if err := r.c.Put(ctx, &late, "f-late", ""); err == nil {
t.Fatal("a blocked key must refuse new results")
}
// Purging a video that was never cached still blocks it.
if n, err := r.c.Purge(ctx, "vimeo", "never", "", 1); err != nil || n != 0 {
t.Fatalf("purge of an unknown key = %d, %v", n, err)
}
if blocked, _ := r.c.Blocked(ctx, "vimeo", "never", "vimeo.com"); !blocked {
t.Fatal("a never-cached key must be blocked too")
}
// Expiry sweeps never remove takedown markers.
r.advance(365 * 24 * time.Hour)
if _, err := r.c.Sweep(ctx); err != nil {
t.Fatal(err)
}
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", ""); !blocked {
t.Fatal("a takedown must outlive every TTL")
}
}
func TestSiteBlocklistCoversSubdomains(t *testing.T) {
r := newRig(t, nil)
ctx := context.Background()
if err := r.store.AddBlock(ctx, db.BlockSite, "bad.example", "spam", 1); err != nil {
t.Fatal(err)
}
for site, want := range map[string]bool{
"bad.example": true, "cdn.bad.example": true, "a.b.bad.example": true,
"notbad.example": false, "example": false, "good.example": false, "": false,
} {
got, err := r.c.Blocked(ctx, "generic", "url-x", site)
if err != nil || got != want {
t.Errorf("Blocked(site=%q) = %v, %v; want %v", site, got, err, want)
}
}
if ok, _ := r.store.RemoveBlock(ctx, db.BlockSite, "bad.example"); !ok {
t.Fatal("RemoveBlock should report the removal")
}
if got, _ := r.c.Blocked(ctx, "generic", "url-x", "cdn.bad.example"); got {
t.Fatal("an unblocked site must be available again")
}
}
func TestSweepRemovesOrphanFiles(t *testing.T) {
r := newRig(t, nil)
ctx := context.Background()
// Orphans are judged by the real modification time of their files, so
// this test starts its clock at the real time.
r.now.Store(time.Now().UnixMilli())
cached := r.put("youtube", "v", "best", 100, 720, "f")
for _, key := range []string{"jobs/orphan1/media", "jobs/orphan2/media"} {
if err := r.st.Put(ctx, key, strings.NewReader("left over"), 9); err != nil {
t.Fatal(err)
}
}
// A file of a job that is still running must survive.
live := &db.Job{ID: "livejob", URL: "u", Profile: "best", Status: db.JobRunning, CreatedAt: 1, QueuedAt: 1, MaxAttempts: 2}
if err := r.store.InsertJob(ctx, live); err != nil {
t.Fatal(err)
}
if err := r.st.Put(ctx, "jobs/livejob/media", strings.NewReader("in progress"), 11); err != nil {
t.Fatal(err)
}
// Young files are left alone: an upload may still be running.
if res, err := r.c.Sweep(ctx); err != nil || res.Orphans != 0 {
t.Fatalf("sweep of young files = %+v, %v", res, err)
}
r.advance(2 * time.Hour)
res, err := r.c.Sweep(ctx)
if err != nil || res.Orphans != 2 {
t.Fatalf("sweep = %+v, %v", res, err)
}
if r.stored("jobs/orphan1/media") || r.stored("jobs/orphan2/media") {
t.Fatal("orphans must be deleted")
}
if !r.stored(cached.StorageKey) || !r.stored("jobs/livejob/media") {
t.Fatal("referenced files must be kept")
}
}
func TestMetaLayer(t *testing.T) {
r := newRig(t, nil)
if _, ok := r.c.MetaGet("https://a.example/1"); ok {
t.Fatal("empty meta cache hit")
}
r.c.MetaPut("https://a.example/1", `{"x":1}`)
if v, ok := r.c.MetaGet("https://a.example/1"); !ok || v != `{"x":1}` {
t.Fatalf("meta = %q, %v", v, ok)
}
r.advance(29 * time.Minute)
if _, ok := r.c.MetaGet("https://a.example/1"); !ok {
t.Fatal("metadata should still be remembered")
}
r.advance(2 * time.Minute)
if _, ok := r.c.MetaGet("https://a.example/1"); ok {
t.Fatal("metadata should have expired")
}
r.c.MetaPut("https://a.example/2", "v")
r.c.MetaDrop("https://a.example/2")
if _, ok := r.c.MetaGet("https://a.example/2"); ok {
t.Fatal("dropped metadata was served")
}
off := cache.New(cache.Config{Enabled: true, MetaTTL: 0}, botID, r.store, r.st, nil)
off.MetaPut("k", "v")
if _, ok := off.MetaGet("k"); ok {
t.Fatal("a zero TTL turns the metadata layer off")
}
}