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
+126
View File
@@ -0,0 +1,126 @@
// Package ffmpeg makes lower profiles and audio from a stored file, so a
// video that is already in the cache does not have to be downloaded again.
package ffmpeg
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// Transcoder derives one profile from a source file.
type Transcoder interface {
// Derive writes the profile made from src into dir and describes it.
// Failures are returned as *ytdlp.Error.
Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error)
}
// Exec runs the real ffmpeg.
type Exec struct {
// Path of the ffmpeg binary. Defaults to "ffmpeg". ffprobe is expected
// next to it.
Path string
// Timeout bounds one transcode. Defaults to 30 minutes.
Timeout time.Duration
}
var _ Transcoder = (*Exec)(nil)
func (e *Exec) bin() string {
if e.Path == "" {
return "ffmpeg"
}
return e.Path
}
func (e *Exec) probeBin() string {
if e.Path == "" || e.Path == "ffmpeg" {
return "ffprobe"
}
return filepath.Join(filepath.Dir(e.Path), "ffprobe")
}
// Args returns the ffmpeg arguments for a profile and the output file
// name. It is exported for tests and the operations docs.
func Args(src, dir string, profile media.Profile) (args []string, out string, err error) {
base := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", src}
switch {
case profile == media.MP3:
out = filepath.Join(dir, "media.mp3")
return append(base, "-vn", "-c:a", "libmp3lame", "-b:a", "192k", out), out, nil
case profile == media.M4A:
out = filepath.Join(dir, "media.m4a")
return append(base, "-vn", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", out), out, nil
case profile.Height() > 0:
out = filepath.Join(dir, "media.mp4")
// Scale to the target height, keep the aspect ratio, and keep the
// width even, which h264 requires.
scale := "scale=-2:" + strconv.Itoa(profile.Height())
return append(base, "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out), out, nil
}
return nil, "", fmt.Errorf("ffmpeg: profile %q cannot be derived", profile)
}
// Derive implements Transcoder.
func (e *Exec) Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error) {
timeout := e.Timeout
if timeout <= 0 {
timeout = 30 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()}
}
args, out, err := Args(src, dir, profile)
if err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: err.Error()}
}
cmd := exec.CommandContext(ctx, e.bin(), args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process == nil {
return nil
}
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
cmd.WaitDelay = 5 * time.Second
var stderr bytes.Buffer
cmd.Stderr = &stderr
runErr := cmd.Run()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &ytdlp.Error{Code: ytdlp.CodeTimeout, Retryable: true, Raw: "transcode timed out"}
}
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "transcode cancelled"}
}
if runErr != nil {
raw := strings.TrimSpace(stderr.String())
if len(raw) > 600 {
raw = raw[len(raw)-600:]
}
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg: " + links.RedactText(raw)}
}
st, err := os.Stat(out)
if err != nil || st.Size() == 0 {
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg produced no output"}
}
res := &ytdlp.Result{Path: out, Size: st.Size(), Ext: strings.TrimPrefix(filepath.Ext(out), ".")}
if d, w, h, err := ytdlp.FileInfo(ctx, e.probeBin(), out); err == nil {
res.Duration, res.Width, res.Height = d, w, h
}
return res, nil
}
+93
View File
@@ -0,0 +1,93 @@
package ffmpeg
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
func TestArgs(t *testing.T) {
tests := map[media.Profile]struct{ want, out string }{
media.P480: {"-vf scale=-2:480 -c:v libx264 -preset veryfast -crf 23 -c:a aac -b:a 128k -movflags +faststart", "media.mp4"},
media.P720: {"-vf scale=-2:720", "media.mp4"},
media.MP3: {"-vn -c:a libmp3lame -b:a 192k", "media.mp3"},
media.M4A: {"-vn -c:a aac -b:a 160k -movflags +faststart", "media.m4a"},
}
for p, tc := range tests {
args, out, err := Args("/src/in", "/dst", p)
if err != nil {
t.Errorf("%s: %v", p, err)
continue
}
joined := strings.Join(args, " ")
if !strings.Contains(joined, tc.want) || out != filepath.Join("/dst", tc.out) || args[len(args)-1] != out {
t.Errorf("%s: args = %q, out = %q", p, joined, out)
}
if !strings.Contains(joined, "-i /src/in") || !strings.Contains(joined, "-nostdin") {
t.Errorf("%s: input or -nostdin missing: %q", p, joined)
}
}
// Profiles that are not made by transcoding.
for _, p := range []media.Profile{media.Best, media.Thumb, media.Subs("en")} {
if _, _, err := Args("in", "out", p); err == nil {
t.Errorf("%s must not be derivable", p)
}
}
}
// TestDeriveWithRealFfmpeg makes a two second 720p test clip and derives
// 480p and MP3 from it. It is skipped when ffmpeg is not installed.
func TestDeriveWithRealFfmpeg(t *testing.T) {
if _, err := exec.LookPath("ffmpeg"); err != nil {
t.Skip("ffmpeg is not installed")
}
dir := t.TempDir()
src := filepath.Join(dir, "source.mp4")
gen := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-f", "lavfi", "-i", "testsrc=duration=2:size=1280x720:rate=15",
"-f", "lavfi", "-i", "sine=frequency=440:duration=2",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", src)
if out, err := gen.CombinedOutput(); err != nil {
t.Skipf("cannot generate a test clip with this ffmpeg build: %v %s", err, out)
}
e := &Exec{Timeout: time.Minute}
ctx := context.Background()
video, err := e.Derive(ctx, src, filepath.Join(dir, "v"), media.P480)
if err != nil {
t.Fatalf("derive 480: %v", err)
}
if video.Ext != "mp4" || video.Height != 480 || video.Width != 854 || video.Size == 0 ||
video.Duration < 1.5 || video.Duration > 2.6 {
t.Fatalf("480p result = %+v", video)
}
audio, err := e.Derive(ctx, src, filepath.Join(dir, "a"), media.MP3)
if err != nil {
t.Fatalf("derive mp3: %v", err)
}
if audio.Ext != "mp3" || audio.Size == 0 || audio.Width != 0 || audio.Duration < 1.5 {
t.Fatalf("mp3 result = %+v", audio)
}
// A source that is not media gives a classified error, not a crash.
bad := filepath.Join(dir, "bad.mp4")
if err := os.WriteFile(bad, []byte("this is not a video"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := e.Derive(ctx, bad, filepath.Join(dir, "b"), media.P480); ytdlp.CodeOf(err) != ytdlp.CodeProcessing {
t.Fatalf("bad source: %v, want processing_failed", err)
}
// Cancelling stops ffmpeg.
cctx, cancel := context.WithCancel(ctx)
cancel()
if _, err := e.Derive(cctx, src, filepath.Join(dir, "c"), media.P480); ytdlp.CodeOf(err) != ytdlp.CodeCancelled {
t.Fatalf("cancelled derive: %v, want cancelled", err)
}
}