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
+217 -20
View File
@@ -9,9 +9,11 @@ import (
"errors"
"log/slog"
"math"
"strings"
"time"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/cache"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/entitle"
@@ -38,6 +40,47 @@ type CardInfo struct {
// Sizes maps a profile to its estimated size in bytes. Profiles with an
// unknown size are absent.
Sizes map[string]int64 `json:"sizes,omitempty"`
// Availability is yt-dlp's access class ("public", "private", ...).
// Anything that is not public or unlisted is never cached.
Availability string `json:"availability,omitempty"`
// SubLangs are the subtitle languages, written ones before automatic.
SubLangs []string `json:"sub_langs,omitempty"`
AutoSubLangs []string `json:"auto_sub_langs,omitempty"`
// Fresh asks to skip the cache and download again.
Fresh bool `json:"fresh,omitempty"`
}
// Playlist is a link that resolved to a list of items.
type Playlist struct {
Title string `json:"title"`
Entries []PlaylistEntry `json:"entries"`
}
// PlaylistEntry is one item of a playlist.
type PlaylistEntry struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
}
// JSON encodes the playlist for storage.
func (p *Playlist) JSON() string {
b, _ := json.Marshal(p)
return string(b)
}
// ParsePlaylist decodes a stored playlist.
func ParsePlaylist(s string) (*Playlist, error) {
var p Playlist
if err := json.Unmarshal([]byte(s), &p); err != nil {
return nil, err
}
return &p, nil
}
// Probed is the result of looking up a link: one item or a playlist.
type Probed struct {
Info *CardInfo `json:"info,omitempty"`
Playlist *Playlist `json:"playlist,omitempty"`
}
// JSON encodes the info for storage.
@@ -72,6 +115,8 @@ func cardInfo(url string, info *ytdlp.Info) *CardInfo {
Live: info.Live(),
Sizes: map[string]int64{},
}
c.Availability = info.Availability
c.SubLangs, c.AutoSubLangs = info.SubtitleLangs()
if c.Title == "" {
c.Title = info.ID
}
@@ -107,6 +152,9 @@ const (
LimitQueueFull = "queue_full"
LimitDailyDownloads = "daily_downloads"
LimitDailyVolume = "daily_volume"
// LimitBlocked is a takedown by the owner: the video or its site is on
// the blocklist.
LimitBlocked = "blocked"
)
// ErrPlaylist is returned by Probe for links that resolve to a list.
@@ -118,6 +166,7 @@ type Service struct {
store *db.Store
sched *sched.Scheduler
billing *billing.Billing
cache *cache.Cache
runner ytdlp.Runner
log *slog.Logger
probes chan struct{}
@@ -125,13 +174,13 @@ type Service struct {
}
// New creates the service.
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, runner ytdlp.Runner, log *slog.Logger) *Service {
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, ch *cache.Cache, runner ytdlp.Runner, log *slog.Logger) *Service {
n := cfg.Worker.ProbeConcurrency
if n < 1 {
n = 1
}
return &Service{
cfg: cfg, store: store, sched: sch, billing: bill, runner: runner, log: log,
cfg: cfg, store: store, sched: sch, billing: bill, cache: ch, runner: runner, log: log,
probes: make(chan struct{}, n), now: time.Now,
}
}
@@ -139,9 +188,30 @@ func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing
// SetClock replaces the time source, for tests.
func (s *Service) SetClock(now func() time.Time) { s.now = now }
// Probe looks up the metadata of a link. Lookups are limited to a few at a
// time so a burst of links cannot start dozens of yt-dlp processes.
// Probe looks up the metadata of a single item. A link that turns out to
// be a playlist gives ErrPlaylist; use ProbeAny to handle both.
func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) {
p, err := s.ProbeAny(ctx, url)
if err != nil {
return nil, err
}
if p.Info == nil {
return nil, ErrPlaylist
}
return p.Info, nil
}
// ProbeAny looks up a link, which may be one item or a playlist. Results
// are remembered for a while, so a link that was just seen answers at
// once. Lookups are limited to a few at a time so a burst of links cannot
// start dozens of yt-dlp processes.
func (s *Service) ProbeAny(ctx context.Context, url string) (*Probed, error) {
if raw, ok := s.cache.MetaGet(url); ok {
var p Probed
if json.Unmarshal([]byte(raw), &p) == nil && (p.Info != nil || p.Playlist != nil) {
return &p, nil
}
}
select {
case s.probes <- struct{}{}:
defer func() { <-s.probes }()
@@ -156,10 +226,24 @@ func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) {
}
return nil, err
}
p := &Probed{}
if info.IsPlaylist() {
return nil, ErrPlaylist
pl := &Playlist{Title: info.Title}
for _, e := range info.Entries {
// Flat listings sometimes carry bare IDs. Only real links are
// usable as separate downloads.
if u, err := links.Normalize(e.URL); err == nil && strings.Contains(e.URL, "://") {
pl.Entries = append(pl.Entries, PlaylistEntry{URL: u, Title: e.Title})
}
}
p.Playlist = pl
} else {
p.Info = cardInfo(url, info)
}
return cardInfo(url, info), nil
if raw, err := json.Marshal(p); err == nil {
s.cache.MetaPut(url, string(raw))
}
return p, nil
}
// tier converts a configured tier to resolver limits.
@@ -170,6 +254,7 @@ func tier(t config.Tier) entitle.Limits {
ActiveJobs: t.ActiveJobs,
DailyDownloads: t.DailyDownloads,
DailyBytes: t.DailyMB << 20,
PlaylistItems: t.PlaylistItems,
}
}
@@ -256,7 +341,7 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me
func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError {
le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]}
if code == LimitLive || code == LimitQueueFull || dec.Source.Paid() || !s.billing.Enabled() {
if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || dec.Source.Paid() || !s.billing.Enabled() {
return le
}
// Would the paid tier accept it? Only then is it worth offering.
@@ -268,15 +353,72 @@ func (s *Service) limitError(code string, info *CardInfo, profile media.Profile,
return le
}
// resolved is what a request maps to before admission: the canonical
// cache key and, when the cache can serve it, the entry to serve from.
type resolved struct {
extractor string
videoID string
cacheable bool
// hit is a cached result that answers the request as is.
hit *db.CacheEntry
// source is a stored higher profile to transcode from.
source *db.CacheEntry
// view is the metadata admission judges. For a hit it carries the real
// size and duration of the cached file instead of estimates.
view *CardInfo
}
// resolve finds the cache key of a request and what the cache has for it.
// It refuses content the owner took down.
func (s *Service) resolve(ctx context.Context, url string, info *CardInfo, profile media.Profile, dec entitle.Decision) (*resolved, error) {
r := &resolved{view: info}
r.extractor, r.videoID = cache.Canonical(info.Extractor, info.VideoID, url)
blocked, err := s.cache.Blocked(ctx, r.extractor, r.videoID, info.Site)
if err != nil {
return nil, err
}
if blocked {
return nil, &LimitError{Code: LimitBlocked, Decision: dec}
}
r.cacheable = s.cache.Enabled() && cache.Cacheable(info.Availability, info.Live)
if !r.cacheable || info.Fresh {
return r, nil
}
if r.hit, err = s.cache.Lookup(ctx, r.extractor, r.videoID, profile); err != nil {
return nil, err
}
if r.hit == nil {
if r.hit, r.source, err = s.cache.Related(ctx, r.extractor, r.videoID, profile); err != nil {
return nil, err
}
}
if r.hit != nil {
// Judge the request by the real file. This is what keeps the cache
// from bypassing limits: a file somebody with a pass put in the
// cache is still too large for a free user, and says so here.
view := *info
view.Sizes = map[string]int64{string(profile): r.hit.Size}
if r.hit.Duration > 0 {
view.Duration = r.hit.Duration
}
r.view = &view
}
return r, nil
}
// Preview reports whether a download would be accepted right now, without
// queueing or charging anything. It returns *LimitError when a rule would
// refuse it.
func (s *Service) Preview(ctx context.Context, who Who, info *CardInfo, profile media.Profile) error {
func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardInfo, profile media.Profile) error {
dec, err := s.Entitlement(ctx, who, false)
if err != nil {
return err
}
return s.admit(ctx, who, info, profile, dec)
r, err := s.resolve(ctx, url, info, profile, dec)
if err != nil {
return err
}
return s.admit(ctx, who, r.view, profile, dec)
}
// StartParams describes a download a requester asked for.
@@ -292,8 +434,13 @@ type StartParams struct {
}
// Start resolves the entitlement, checks every limit, charges the wallet
// when credits pay, and queues the download. Charge, quota and job are
// written in one transaction. It returns *LimitError when a rule refuses.
// when credits pay, and gets the file on its way: from the cache when it
// is there, by joining a download that is already running for the same
// result, by transcoding a stored copy, or by a fresh download.
//
// Whichever of those it is, the request passes the same admission and
// costs the same. Charge, quota and job are written in one transaction.
// It returns *LimitError when a rule refuses.
func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delivery, error) {
who := Who{UserID: p.Request.UserID, ChatID: p.Request.ChatID, ChatType: p.Request.ChatType}
// A wallet changing under us (two downloads racing for the last
@@ -313,14 +460,20 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo
if err != nil {
return nil, nil, err
}
if err := s.admit(ctx, who, p.Info, p.Profile, dec); err != nil {
r, err := s.resolve(ctx, p.Request.URL, p.Info, p.Profile, dec)
if err != nil {
return nil, nil, err
}
// One gate for everything. A cache hit is admitted exactly like a
// fresh download; it only skips the worker afterwards.
if err := s.admit(ctx, who, r.view, p.Profile, dec); err != nil {
return nil, nil, err
}
day := Day(s.now())
params := sched.EnqueueParams{
URL: p.Request.URL,
Extractor: p.Info.Extractor,
VideoID: p.Info.VideoID,
Extractor: r.extractor,
VideoID: r.videoID,
Profile: string(p.Profile),
Title: p.Info.Title,
Uploader: p.Info.Uploader,
@@ -341,6 +494,8 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo
WalletID: dec.WalletID,
ChargeSats: dec.Charge,
QuotaDay: day,
CacheKey: cache.JobKey(r.extractor, r.videoID, string(p.Profile)),
Cacheable: r.cacheable,
}
if p.OneOff != nil {
// Prepaid by invoice. Remember the amount and the payer's wallet so
@@ -352,14 +507,46 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo
params.WalletID = w.ID
params.ChargeSats = p.OneOff.AmountSats
}
switch {
case r.hit != nil:
params.Hit = &sched.CacheHit{
StorageKey: r.hit.StorageKey, TgFileID: r.hit.TgFileID, FileExt: r.hit.FileExt,
FileSize: r.hit.Size, Duration: r.hit.Duration, Width: r.hit.Width, Height: r.hit.Height,
Title: r.hit.Title, Uploader: r.hit.Uploader,
}
case r.source != nil:
params.Kind = db.KindDerive
params.SourceKey = r.source.StorageKey
}
var (
job *db.Job
del *db.Delivery
job *db.Job
del *db.Delivery
attached bool
)
err = s.store.InTx(ctx, func(tx *db.Store) error {
var err error
if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil {
return err
job, del, attached = nil, nil, false
// Singleflight: the same result is already on its way for somebody
// else, so wait for that instead of fetching it twice.
if r.hit == nil && r.cacheable && !p.Info.Fresh {
active, err := tx.ActiveJobForKey(ctx, params.CacheKey)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return err
}
if active != nil {
d, ok, err := s.sched.AttachTx(ctx, tx, active, params)
if err != nil {
return err
}
if ok {
job, del, attached = active, d, true
}
}
}
if !attached {
var err error
if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil {
return err
}
}
if dec.Charge > 0 {
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
@@ -379,7 +566,17 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo
case err != nil:
return nil, nil, err
}
s.sched.Announce(job, del)
switch {
case r.hit != nil:
s.cache.RecordHit(ctx, r.hit)
case r.cacheable:
s.cache.RecordMiss()
}
if attached {
s.sched.AnnounceAttached(job, del)
} else {
s.sched.Announce(job, del)
}
return job, del, nil
}