// Package cache makes repeat downloads fast. It has three layers: // // 1. Telegram file_ids, valid for one bot token, for instant resends. // 2. Stored copies in Storage, used to re-upload when a file_id stops // working and as the source for transcoding lower profiles. // 3. A short-lived metadata cache, so cards for known links are instant. // // The cache only removes work. It decides nothing about limits: every // request, hit or miss, passes the same admission in package service. package cache import ( "context" "crypto/sha256" "encoding/hex" "errors" "log/slog" "strings" "sync" "sync/atomic" "time" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/storage" ) // Config holds the cache settings. type Config struct { Enabled bool // BudgetBytes caps the total size of stored copies. 0 means no cap. BudgetBytes int64 // TTLs by source class. Stable sites keep files for a long time, // ephemeral ones (stories, feeds) for a short time. TTLDefault time.Duration TTLStable time.Duration TTLEphemeral time.Duration // Stable and Ephemeral are extractor name prefixes. Stable []string Ephemeral []string // MetaTTL is how long link metadata is remembered. MetaTTL time.Duration // Derive allows making lower profiles from a stored higher one. Derive bool } // Stats are counters for metrics. type Stats struct { Hits int64 Misses int64 BytesSaved int64 } // Cache is the cache service. type Cache struct { cfg Config botID int64 store *db.Store storage storage.Storage log *slog.Logger now func() time.Time hits, misses, saved atomic.Int64 metaMu sync.Mutex meta map[string]metaItem } type metaItem struct { value string expires time.Time } // New creates the cache for one bot. func New(cfg Config, botID int64, store *db.Store, st storage.Storage, log *slog.Logger) *Cache { if log == nil { log = slog.Default() } return &Cache{cfg: cfg, botID: botID, store: store, storage: st, log: log, now: time.Now, meta: map[string]metaItem{}} } // SetClock replaces the time source, for tests. func (c *Cache) SetClock(now func() time.Time) { c.now = now } // Enabled reports whether results are cached. func (c *Cache) Enabled() bool { return c.cfg.Enabled } // Stats returns the counters. func (c *Cache) Stats() Stats { return Stats{Hits: c.hits.Load(), Misses: c.misses.Load(), BytesSaved: c.saved.Load()} } // Canonical turns yt-dlp metadata into the two stable parts of a cache // key. Different URLs of the same video (watch page, short link, embed) // give the same extractor and ID, which is what lets them share an entry. // // The generic extractor has no real IDs: it names a file after the last // part of its URL, so two sites can collide. For it, and whenever an ID is // missing, the key falls back to a hash of the URL. func Canonical(extractor, videoID, url string) (string, string) { ext := strings.ToLower(strings.TrimSpace(extractor)) if i := strings.IndexByte(ext, ':'); i > 0 { ext = ext[:i] // "youtube:tab" and "youtube" are one site } id := strings.TrimSpace(videoID) if ext == "" || ext == "generic" || id == "" { sum := sha256.Sum256([]byte(url)) if ext == "" { ext = "generic" } return ext, "url-" + hex.EncodeToString(sum[:16]) } return ext, id } // JobKey is the string stored with a job to find others working on the // same result. func JobKey(extractor, videoID, profile string) string { return extractor + "\x1f" + videoID + "\x1f" + profile } // Cacheable reports whether content with this availability may be kept. // Anything that needed a login, is private or is members-only is never // cached or shared between users. func Cacheable(availability string, live bool) bool { if live { return false } switch availability { case "", "public", "unlisted": return true } return false } // ttl picks the lifetime for an extractor. func (c *Cache) ttl(extractor string) time.Duration { for _, p := range c.cfg.Ephemeral { if strings.HasPrefix(extractor, strings.ToLower(p)) { return c.cfg.TTLEphemeral } } for _, p := range c.cfg.Stable { if strings.HasPrefix(extractor, strings.ToLower(p)) { return c.cfg.TTLStable } } return c.cfg.TTLDefault } // Blocked reports whether a video or its site was taken down by the owner. func (c *Cache) Blocked(ctx context.Context, extractor, videoID, site string) (bool, error) { if site != "" { // A blocked host also blocks its subdomains. for host := site; strings.Contains(host, "."); host = host[strings.IndexByte(host, '.')+1:] { if ok, err := c.store.IsBlocked(ctx, db.BlockSite, host); err != nil || ok { return ok, err } } } if ok, err := c.store.IsBlocked(ctx, db.BlockKey, extractor+":"+videoID); err != nil || ok { return ok, err } entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, extractor, videoID) if err != nil { return false, err } for _, e := range entries { if e.Status == db.CacheBlocked { return true, nil } } return false, nil } // usable reports whether an entry can serve a request right now. func (c *Cache) usable(e *db.CacheEntry) bool { if e == nil || e.Status != db.CacheReady || e.Private { return false } if e.ExpiresAt > 0 && e.ExpiresAt < c.now().UnixMilli() { return false } return e.TgFileID != "" || e.StorageKey != "" } // Lookup finds a ready entry for exactly this profile, or nil. func (c *Cache) Lookup(ctx context.Context, extractor, videoID string, profile media.Profile) (*db.CacheEntry, error) { if !c.cfg.Enabled { return nil, nil } e, err := c.store.GetCacheEntry(ctx, c.botID, extractor, videoID, string(profile)) if errors.Is(err, db.ErrNotFound) { return nil, nil } if err != nil || !c.usable(e) { return nil, err } return e, nil } // higher lists the video profiles above p, nearest first. func higher(p media.Profile) []media.Profile { switch p { case media.P480: return []media.Profile{media.P720, media.P1080, media.Best} case media.P720: return []media.Profile{media.P1080, media.Best} case media.P1080: return []media.Profile{media.Best} case media.MP3, media.M4A: return []media.Profile{media.P480, media.P720, media.P1080, media.Best} } return nil } // Related looks for a cached higher profile that can stand in for the // requested one. // // - alias: a higher profile whose picture is already no taller than the // requested cap. It is the very file yt-dlp would fetch, so it is // served as a hit. (A 480p source asked for as "720" is one example.) // - source: a stored higher profile to transcode from, when Derive is on. // // At most one of the two is returned. func (c *Cache) Related(ctx context.Context, extractor, videoID string, profile media.Profile) (alias, source *db.CacheEntry, err error) { if !c.cfg.Enabled { return nil, nil, nil } target := profile.Height() for _, hp := range higher(profile) { e, err := c.Lookup(ctx, extractor, videoID, hp) if err != nil { return nil, nil, err } if e == nil { continue } if profile.Kind() == media.KindVideo && e.Height > 0 && e.Height <= target { return e, nil, nil } if source == nil && c.cfg.Derive && e.StorageKey != "" && streamable(e.FileExt) { if profile.Kind() == media.KindAudio || e.Height > target { source = e } } } return nil, source, nil } func streamable(ext string) bool { switch ext { case "mp4", "m4v", "mov", "mkv", "webm": return true } return false } // ProfileServing returns the profile of the entry a cache hit job is being // served from. It is usually the job's own profile, but an alias hit is // served from a higher profile's entry. The entry is found by the file_id // or stored copy the job carries. func (c *Cache) ProfileServing(ctx context.Context, job *db.Job) string { entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, job.Extractor, job.VideoID) if err == nil { for _, e := range entries { if (job.TgFileID != "" && e.TgFileID == job.TgFileID) || (job.StorageKey != "" && e.StorageKey == job.StorageKey) { return e.Profile } } } return job.Profile } // RecordHit counts a hit and the bytes it saved. func (c *Cache) RecordHit(ctx context.Context, e *db.CacheEntry) { c.hits.Add(1) c.saved.Add(e.Size) if err := c.store.TouchCacheEntry(ctx, e, c.now().UnixMilli()); err != nil { c.log.Warn("cache: count hit", "err", err) } } // RecordMiss counts a request the cache could not serve. func (c *Cache) RecordMiss() { c.misses.Add(1) } // Put stores the result of a finished job. The job's stored file becomes // the cache's stored copy; a copy held by an older entry is deleted. func (c *Cache) Put(ctx context.Context, job *db.Job, fileID, uniqueID string) error { if !c.cfg.Enabled || !job.Cacheable || job.Extractor == "" || job.VideoID == "" { return errors.New("cache: job is not cacheable") } now := c.now().UnixMilli() old, err := c.store.GetCacheEntry(ctx, c.botID, job.Extractor, job.VideoID, job.Profile) if err != nil && !errors.Is(err, db.ErrNotFound) { return err } if old != nil && old.Status == db.CacheBlocked { return errors.New("cache: key is blocked") } e := &db.CacheEntry{ BotID: c.botID, Extractor: job.Extractor, VideoID: job.VideoID, Profile: job.Profile, TgFileID: fileID, TgFileUniqueID: uniqueID, StorageKey: job.StorageKey, Size: job.FileSize, Duration: job.Duration, Title: job.Title, Uploader: job.Uploader, FileExt: job.FileExt, Width: job.Width, Height: job.Height, LastHit: now, Status: db.CacheReady, CreatedAt: now, ExpiresAt: now + c.ttl(job.Extractor).Milliseconds(), } if err := c.store.UpsertCacheEntry(ctx, e); err != nil { return err } if old != nil && old.StorageKey != "" && old.StorageKey != job.StorageKey { if err := c.storage.Delete(ctx, old.StorageKey); err != nil { c.log.Warn("cache: delete replaced copy", "key", old.StorageKey, "err", err) } } return nil } // SetFileID records a new file_id for an entry, after a re-upload. func (c *Cache) SetFileID(ctx context.Context, extractor, videoID, profile, fileID, uniqueID string) error { return c.store.SetCacheFileID(ctx, &db.CacheEntry{BotID: c.botID, Extractor: extractor, VideoID: videoID, Profile: profile}, fileID, uniqueID) } // DropStored forgets a stored copy that turned out to be missing. func (c *Cache) DropStored(ctx context.Context, extractor, videoID, profile string) error { return c.store.ClearCacheStorage(ctx, &db.CacheEntry{BotID: c.botID, Extractor: extractor, VideoID: videoID, Profile: profile}) } // Forget removes an entry completely, with its stored copy. func (c *Cache) Forget(ctx context.Context, extractor, videoID, profile string) error { e, err := c.store.GetCacheEntry(ctx, c.botID, extractor, videoID, profile) if errors.Is(err, db.ErrNotFound) { return nil } if err != nil { return err } return c.remove(ctx, e) } func (c *Cache) remove(ctx context.Context, e *db.CacheEntry) error { if e.StorageKey != "" { if err := c.storage.Delete(ctx, e.StorageKey); err != nil { return err } } return c.store.DeleteCacheEntry(ctx, e) } // Purge is a takedown: it deletes the stored files of every profile of a // video, invalidates their file_ids and blocks the key, so the video is // neither served from the cache nor downloaded again. It returns the // number of entries that were purged. func (c *Cache) Purge(ctx context.Context, extractor, videoID, reason string, by int64) (int, error) { entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, extractor, videoID) if err != nil { return 0, err } n := 0 for _, e := range entries { if e.StorageKey != "" { if err := c.storage.Delete(ctx, e.StorageKey); err != nil { return n, err } } if e.Status == db.CacheReady { n++ } } if err := c.store.BlockCacheKey(ctx, c.botID, extractor, videoID, c.now().UnixMilli()); err != nil { return n, err } // The blocklist row is what stops a key that was never cached. if err := c.store.AddBlock(ctx, db.BlockKey, extractor+":"+videoID, reason, by); err != nil { return n, err } c.log.Info("cache: purged", "extractor", extractor, "video_id", videoID, "entries", n, "by", by) return n, nil } // --- metadata layer -------------------------------------------------------- // MetaGet returns remembered metadata for a URL. func (c *Cache) MetaGet(url string) (string, bool) { if c.cfg.MetaTTL <= 0 { return "", false } c.metaMu.Lock() defer c.metaMu.Unlock() it, ok := c.meta[url] if !ok || c.now().After(it.expires) { delete(c.meta, url) return "", false } return it.value, true } // MetaPut remembers metadata for a URL. func (c *Cache) MetaPut(url, value string) { if c.cfg.MetaTTL <= 0 { return } c.metaMu.Lock() defer c.metaMu.Unlock() if len(c.meta) >= 5000 { now := c.now() for k, v := range c.meta { if now.After(v.expires) || len(c.meta) >= 5000 { delete(c.meta, k) } if len(c.meta) < 4000 { break } } } c.meta[url] = metaItem{value: value, expires: c.now().Add(c.cfg.MetaTTL)} } // MetaDrop forgets the metadata of a URL. func (c *Cache) MetaDrop(url string) { c.metaMu.Lock() delete(c.meta, url) c.metaMu.Unlock() } // --- eviction -------------------------------------------------------------- // SweepResult summarizes one sweep. type SweepResult struct { Expired int Evicted int Orphans int } // orphanAge is how old an unreferenced stored file must be before the // sweeper removes it. It leaves room for an upload that is in progress. const orphanAge = time.Hour // Sweep expires old entries, enforces the size budget and deletes stored // files that nothing references anymore. func (c *Cache) Sweep(ctx context.Context) (SweepResult, error) { var res SweepResult now := c.now().UnixMilli() expired, err := c.store.ExpiredCacheEntries(ctx, c.botID, now, 500) if err != nil { return res, err } for _, e := range expired { if err := c.remove(ctx, e); err != nil { c.log.Warn("cache: expire entry", "err", err) continue } res.Expired++ } if c.cfg.BudgetBytes > 0 { used, err := c.store.CacheStoredBytes(ctx, c.botID) if err != nil { return res, err } for used > c.cfg.BudgetBytes { victims, err := c.store.CacheEvictionCandidates(ctx, c.botID, 50) if err != nil { return res, err } if len(victims) == 0 { break } for _, e := range victims { if used <= c.cfg.BudgetBytes { break } // Only the stored copy goes. The file_id stays, so the entry // still serves instant resends at no storage cost. if err := c.storage.Delete(ctx, e.StorageKey); err != nil { return res, err } if err := c.store.ClearCacheStorage(ctx, e); err != nil { return res, err } if e.TgFileID == "" { _ = c.store.DeleteCacheEntry(ctx, e) // nothing left to serve } used -= e.Size res.Evicted++ } } } orphans, err := c.sweepOrphans(ctx) res.Orphans = orphans if res.Expired+res.Evicted+res.Orphans > 0 { c.log.Info("cache: sweep", "expired", res.Expired, "evicted", res.Evicted, "orphans", res.Orphans) } return res, err } // sweepOrphans deletes stored files that neither a live job nor a cache // entry points at, such as the leftovers of a crash between an upload and // its bookkeeping. func (c *Cache) sweepOrphans(ctx context.Context) (int, error) { inCache, err := c.store.CacheStorageKeys(ctx) if err != nil { return 0, err } inJobs, err := c.store.JobStorageKeys(ctx) if err != nil { return 0, err } cutoff := c.now().Add(-orphanAge) var doomed []string err = c.storage.List(ctx, "jobs/", func(o storage.Object) error { if !inCache[o.Key] && !inJobs[o.Key] && o.ModTime.Before(cutoff) { doomed = append(doomed, o.Key) } return nil }) if err != nil { return 0, err } n := 0 for _, key := range doomed { if err := c.storage.Delete(ctx, key); err != nil { c.log.Warn("cache: delete orphan", "key", key, "err", err) continue } n++ } return n, nil } // Run sweeps on a schedule until ctx ends. func (c *Cache) Run(ctx context.Context, every time.Duration) { if every <= 0 { every = 10 * time.Minute } t := time.NewTicker(every) defer t.Stop() for { if _, err := c.Sweep(ctx); err != nil && ctx.Err() == nil { c.log.Error("cache: sweep failed", "err", err) } select { case <-ctx.Done(): return case <-t.C: } } } // Summary returns counts for the owner. func (c *Cache) Summary(ctx context.Context) (db.CacheCounts, error) { return c.store.CacheSummary(ctx, c.botID) }