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
+25 -9
View File
@@ -17,6 +17,7 @@ import (
"github.com/noderunners/dlbot/internal/bot"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/ffmpeg"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp"
@@ -29,6 +30,7 @@ type harness struct {
srv *fakeserver.Server
fake *ytdlptest.Fake
runner ytdlp.Runner
trans ffmpeg.Transcoder
app *app.App
cfg config.Config
cancel context.CancelFunc
@@ -52,6 +54,17 @@ func start(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *harnes
return h
}
// startWith starts a core with a scripted yt-dlp and a scripted ffmpeg.
func startWith(t *testing.T, fake *ytdlptest.Fake, trans ffmpeg.Transcoder, mut func(*config.Config)) *harness {
t.Helper()
pendingTranscoder = trans
defer func() { pendingTranscoder = nil }()
return start(t, fake, mut)
}
// pendingTranscoder hands a transcoder to the next harness that starts.
var pendingTranscoder ffmpeg.Transcoder
func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)) *harness {
t.Helper()
dir := t.TempDir()
@@ -68,7 +81,7 @@ func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)
if mut != nil {
mut(&cfg)
}
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg}
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg, trans: pendingTranscoder}
h.boot()
t.Cleanup(func() {
h.stop()
@@ -90,8 +103,8 @@ func (h *harness) boot() {
a, err := app.New(ctx, app.Options{
Config: h.cfg,
Log: slog.New(&guardHandler{Handler: base, t: h.t}),
Runner: h.runner,
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
Runner: h.runner, Transcoder: h.trans,
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
})
if err != nil {
cancel()
@@ -302,8 +315,9 @@ func TestPrivateLinkReturnsFile(t *testing.T) {
}
h.waitJobs(db.JobDone, 1)
if n := h.storedFiles(); n != 0 {
t.Fatalf("%d files left in storage after delivery", n)
// The delivered file stays as the cache's stored copy.
if n := h.storedFiles(); n != 1 {
t.Fatalf("%d files in storage after delivery, want the one cached copy", n)
}
if n := len(h.fake.Probes()); n != 1 {
t.Fatalf("probes = %d, want 1", n)
@@ -572,9 +586,11 @@ func TestSendGivesUpAfterRepeatedFailures(t *testing.T) {
}
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("could not send the file to Telegram"))
h.waitJobs(db.JobDone, 1) // the job itself is closed and cleaned up
if n := h.storedFiles(); n != 0 {
t.Fatalf("%d files left in storage", n)
h.waitJobs(db.JobDone, 1) // the job itself is closed
// The download worked, only the send did not: the file is kept in the
// cache, so the next request does not have to fetch it again.
if n := h.storedFiles(); n != 1 {
t.Fatalf("%d files in storage, want the cached copy", n)
}
}
@@ -774,7 +790,7 @@ func TestCommandMenuIsRegistered(t *testing.T) {
if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil {
t.Fatal(err)
}
if len(cmds) != 9 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
if len(cmds) != 10 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
t.Fatalf("commands = %+v", cmds)
}
for _, c := range cmds {