Files
Media-download-telegram-bot/internal/ytdlp/ytdlptest/fake.go
T
MichilisandClaude Fable 5.2 9c9d641eda 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>
2026-11-18 08:38:38 +00:00

163 lines
4.4 KiB
Go

// Package ytdlptest provides a scriptable ytdlp.Runner for tests.
package ytdlptest
import (
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"sync"
"time"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// Fake is an in-memory ytdlp.Runner. The zero value answers every URL with
// a small default video.
type Fake struct {
mu sync.Mutex
// Infos maps a URL to the metadata Probe returns.
Infos map[string]*ytdlp.Info
// ProbeErrs maps a URL to the error Probe returns.
ProbeErrs map[string]error
// DownloadErrs is consumed one error per Download call, per URL. A nil
// entry means success. This is how tests script "fail once, then work".
DownloadErrs map[string][]error
// FileSize is the size of produced files. Defaults to 1024 bytes.
FileSize int
// Delay is how long a download takes. It stops early on cancel.
Delay time.Duration
// Block, when set, makes downloads wait until the channel is closed.
Block chan struct{}
probes []string
downloads []ytdlp.DownloadRequest
}
var _ ytdlp.Runner = (*Fake)(nil)
// DefaultInfo is the metadata returned for URLs without an explicit entry.
// Every URL is its own video: the ID is derived from the URL.
func DefaultInfo(url string) *ytdlp.Info {
sum := sha256.Sum256([]byte(url))
return &ytdlp.Info{
Type: "video",
ID: "vid-" + hex.EncodeToString(sum[:5]),
Title: "Test Video",
Extractor: "fake",
WebpageURL: url,
Uploader: "Tester",
Duration: 60,
Thumbnail: "https://img.example.com/t.jpg",
Formats: []ytdlp.Format{
{FormatID: "a", Ext: "m4a", VCodec: "none", ACodec: "mp4a", Filesize: 1 << 20},
{FormatID: "v480", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 480, Filesize: 4 << 20},
{FormatID: "v720", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 720, Filesize: 9 << 20},
},
}
}
// Probe implements ytdlp.Runner.
func (f *Fake) Probe(_ context.Context, url string) (*ytdlp.Info, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.probes = append(f.probes, url)
if err := f.ProbeErrs[url]; err != nil {
return nil, err
}
if info := f.Infos[url]; info != nil {
cp := *info
return &cp, nil
}
return DefaultInfo(url), nil
}
// Download implements ytdlp.Runner.
func (f *Fake) Download(ctx context.Context, req ytdlp.DownloadRequest, onProgress func(ytdlp.Progress)) (*ytdlp.Result, error) {
f.mu.Lock()
f.downloads = append(f.downloads, req)
var scripted error
if q := f.DownloadErrs[req.URL]; len(q) > 0 {
scripted = q[0]
f.DownloadErrs[req.URL] = q[1:]
}
size := f.FileSize
if size == 0 {
size = 1024
}
delay, block := f.Delay, f.Block
info := f.Infos[req.URL]
f.mu.Unlock()
if onProgress != nil {
onProgress(ytdlp.Progress{Stage: ytdlp.StageDownloading, Downloaded: int64(size / 2), Total: int64(size)})
}
if block != nil {
select {
case <-block:
case <-ctx.Done():
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"}
}
}
if delay > 0 {
select {
case <-time.After(delay):
case <-ctx.Done():
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"}
}
}
if scripted != nil {
return nil, scripted
}
if req.MaxSize > 0 && int64(size) > req.MaxSize {
return nil, &ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "too large"}
}
ext := "mp4"
switch req.Profile.Kind() {
case media.KindAudio:
ext = string(req.Profile)
case media.KindThumb:
ext = "jpg"
case media.KindSubs:
ext = "srt"
}
if err := os.MkdirAll(req.Dir, 0o750); err != nil {
return nil, err
}
path := filepath.Join(req.Dir, "media."+ext)
if err := os.WriteFile(path, make([]byte, size), 0o640); err != nil {
return nil, err
}
if info == nil {
info = DefaultInfo(req.URL)
}
res := &ytdlp.Result{
Path: path, Size: int64(size), Ext: ext,
ID: info.ID, Title: info.Title, Uploader: info.Uploader, Extractor: info.Extractor,
Duration: float64(info.Duration),
}
if req.Profile.Kind() == media.KindVideo {
res.Width, res.Height = 1280, 720
}
if onProgress != nil {
onProgress(ytdlp.Progress{Stage: ytdlp.StageProcessing})
}
return res, nil
}
// Probes returns the URLs probed so far.
func (f *Fake) Probes() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.probes...)
}
// Downloads returns the download requests seen so far.
func (f *Fake) Downloads() []ytdlp.DownloadRequest {
f.mu.Lock()
defer f.mu.Unlock()
return append([]ytdlp.DownloadRequest(nil), f.downloads...)
}