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:
co-authored by
Claude Fable 5.2
parent
0d50f453a0
commit
9c9d641eda
Vendored
+555
@@ -0,0 +1,555 @@
|
||||
// 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)
|
||||
}
|
||||
Vendored
+495
@@ -0,0 +1,495 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/cache"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/db/dbtest"
|
||||
"github.com/noderunners/dlbot/internal/media"
|
||||
"github.com/noderunners/dlbot/internal/storage"
|
||||
)
|
||||
|
||||
const botID = int64(777)
|
||||
|
||||
type rig struct {
|
||||
t *testing.T
|
||||
store *db.Store
|
||||
st *storage.Local
|
||||
c *cache.Cache
|
||||
now atomic.Int64
|
||||
seq int
|
||||
}
|
||||
|
||||
func newRig(t *testing.T, mut func(*cache.Config)) *rig {
|
||||
t.Helper()
|
||||
st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := cache.Config{
|
||||
Enabled: true, TTLDefault: 7 * 24 * time.Hour, TTLStable: 30 * 24 * time.Hour,
|
||||
TTLEphemeral: 6 * time.Hour, Stable: []string{"youtube"}, Ephemeral: []string{"twitter", "generic"},
|
||||
MetaTTL: 30 * time.Minute, Derive: true,
|
||||
}
|
||||
if mut != nil {
|
||||
mut(&cfg)
|
||||
}
|
||||
r := &rig{t: t, store: dbtest.Open(t).Store(), st: st}
|
||||
r.now.Store(time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC).UnixMilli())
|
||||
r.c = cache.New(cfg, botID, r.store, st, nil)
|
||||
r.c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *rig) advance(d time.Duration) { r.now.Add(d.Milliseconds()) }
|
||||
|
||||
// put stores a result of the given size as a finished job would.
|
||||
func (r *rig) put(extractor, videoID, profile string, size int64, height int, fileID string) *db.Job {
|
||||
r.t.Helper()
|
||||
r.seq++
|
||||
key := "jobs/job" + strings.Repeat("0", 3) + string(rune('a'+r.seq)) + "/media"
|
||||
if err := r.st.Put(context.Background(), key, strings.NewReader(strings.Repeat("x", int(size))), size); err != nil {
|
||||
r.t.Fatal(err)
|
||||
}
|
||||
job := &db.Job{
|
||||
ID: "job" + string(rune('a'+r.seq)), Extractor: extractor, VideoID: videoID, Profile: profile,
|
||||
StorageKey: key, FileSize: size, FileExt: "mp4", Duration: 60, Width: height * 16 / 9, Height: height,
|
||||
Title: "T", Cacheable: true,
|
||||
}
|
||||
if err := r.c.Put(context.Background(), job, fileID, "u-"+fileID); err != nil {
|
||||
r.t.Fatalf("Put: %v", err)
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
func (r *rig) lookup(extractor, videoID string, p media.Profile) *db.CacheEntry {
|
||||
r.t.Helper()
|
||||
e, err := r.c.Lookup(context.Background(), extractor, videoID, p)
|
||||
if err != nil {
|
||||
r.t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func (r *rig) stored(key string) bool {
|
||||
_, err := r.st.Stat(context.Background(), key)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func TestCanonical(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extractor, id, url string
|
||||
wantExt, wantID string
|
||||
}{
|
||||
{"plain", "youtube", "dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"},
|
||||
{"short link, same video", "youtube", "dQw4w9WgXcQ", "https://youtu.be/dQw4w9WgXcQ?t=5", "youtube", "dQw4w9WgXcQ"},
|
||||
{"extractor case and suffix", "Youtube:tab", "abc", "https://youtube.com/x", "youtube", "abc"},
|
||||
{"spaces", " vimeo ", " 123 ", "https://vimeo.com/123", "vimeo", "123"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ext, id := cache.Canonical(tc.extractor, tc.id, tc.url)
|
||||
if ext != tc.wantExt || id != tc.wantID {
|
||||
t.Fatalf("Canonical = %q, %q; want %q, %q", ext, id, tc.wantExt, tc.wantID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The generic extractor names files after the end of the URL, so two
|
||||
// sites can produce the same ID. Its key must come from the whole URL.
|
||||
e1, id1 := cache.Canonical("generic", "video", "https://a.example/video.mp4")
|
||||
e2, id2 := cache.Canonical("generic", "video", "https://b.example/video.mp4")
|
||||
_, id3 := cache.Canonical("generic", "video", "https://a.example/video.mp4")
|
||||
if e1 != "generic" || e2 != "generic" || id1 == id2 {
|
||||
t.Fatalf("generic IDs must differ per URL: %q vs %q", id1, id2)
|
||||
}
|
||||
if id1 != id3 || !strings.HasPrefix(id1, "url-") || id1 == "video" {
|
||||
t.Fatalf("generic IDs must be stable hashes: %q, %q", id1, id3)
|
||||
}
|
||||
// A missing ID or extractor falls back the same way.
|
||||
if ext, id := cache.Canonical("", "", "https://x.example/y"); ext != "generic" || !strings.HasPrefix(id, "url-") {
|
||||
t.Fatalf("empty metadata: %q, %q", ext, id)
|
||||
}
|
||||
if _, id := cache.Canonical("vimeo", "", "https://vimeo.com/1"); !strings.HasPrefix(id, "url-") {
|
||||
t.Fatalf("missing ID: %q", id)
|
||||
}
|
||||
if a, b := cache.JobKey("youtube", "abc", "720"), cache.JobKey("youtube", "abc", "480"); a == b {
|
||||
t.Fatal("profiles must have separate job keys")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheable(t *testing.T) {
|
||||
for av, want := range map[string]bool{
|
||||
"": true, "public": true, "unlisted": true,
|
||||
"private": false, "needs_auth": false, "premium_only": false, "subscriber_only": false,
|
||||
} {
|
||||
if got := cache.Cacheable(av, false); got != want {
|
||||
t.Errorf("Cacheable(%q) = %v, want %v", av, got, want)
|
||||
}
|
||||
}
|
||||
if cache.Cacheable("public", true) {
|
||||
t.Error("live streams are never cached")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutLookupAndReplace(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
ctx := context.Background()
|
||||
if e := r.lookup("youtube", "v1", media.P720); e != nil {
|
||||
t.Fatalf("empty cache returned %+v", e)
|
||||
}
|
||||
first := r.put("youtube", "v1", "720", 1000, 720, "file-1")
|
||||
e := r.lookup("youtube", "v1", media.P720)
|
||||
if e == nil || e.TgFileID != "file-1" || e.TgFileUniqueID != "u-file-1" || e.StorageKey != first.StorageKey ||
|
||||
e.Size != 1000 || e.Height != 720 || e.BotID != botID || e.Status != db.CacheReady {
|
||||
t.Fatalf("entry = %+v", e)
|
||||
}
|
||||
if r.lookup("youtube", "v1", media.P480) != nil || r.lookup("youtube", "v2", media.P720) != nil {
|
||||
t.Fatal("lookup must match extractor, video and profile exactly")
|
||||
}
|
||||
|
||||
r.c.RecordHit(ctx, e)
|
||||
r.c.RecordHit(ctx, e)
|
||||
r.c.RecordMiss()
|
||||
if e := r.lookup("youtube", "v1", media.P720); e.Hits != 2 {
|
||||
t.Fatalf("hits = %d", e.Hits)
|
||||
}
|
||||
if st := r.c.Stats(); st.Hits != 2 || st.Misses != 1 || st.BytesSaved != 2000 {
|
||||
t.Fatalf("stats = %+v", st)
|
||||
}
|
||||
|
||||
// A newer result for the same key replaces the stored copy and keeps
|
||||
// the hit count.
|
||||
second := r.put("youtube", "v1", "720", 1200, 720, "file-2")
|
||||
e = r.lookup("youtube", "v1", media.P720)
|
||||
if e.TgFileID != "file-2" || e.StorageKey != second.StorageKey || e.Size != 1200 || e.Hits != 2 {
|
||||
t.Fatalf("replaced entry = %+v", e)
|
||||
}
|
||||
if r.stored(first.StorageKey) || !r.stored(second.StorageKey) {
|
||||
t.Fatal("the replaced copy must be deleted, the new one kept")
|
||||
}
|
||||
|
||||
// file_ids belong to one bot. Another bot on the same database sees
|
||||
// nothing.
|
||||
other := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour}, botID+1, r.store, r.st, nil)
|
||||
if e, _ := other.Lookup(ctx, "youtube", "v1", media.P720); e != nil {
|
||||
t.Fatalf("another bot got this bot's entry: %+v", e)
|
||||
}
|
||||
// A disabled cache finds nothing and stores nothing.
|
||||
off := cache.New(cache.Config{Enabled: false}, botID, r.store, r.st, nil)
|
||||
if e, _ := off.Lookup(ctx, "youtube", "v1", media.P720); e != nil {
|
||||
t.Fatal("a disabled cache must not serve")
|
||||
}
|
||||
if err := off.Put(ctx, second, "x", ""); err == nil {
|
||||
t.Fatal("a disabled cache must not store")
|
||||
}
|
||||
notCacheable := *second
|
||||
notCacheable.Cacheable = false
|
||||
if err := r.c.Put(ctx, ¬Cacheable, "x", ""); err == nil {
|
||||
t.Fatal("a job that is not cacheable must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLBySourceType(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
stable := r.put("youtube", "s", "best", 10, 1080, "f1") // 30 days
|
||||
normal := r.put("vimeo", "n", "best", 10, 1080, "f2") // 7 days
|
||||
ephemeral := r.put("twitter", "e", "best", 10, 720, "f3") // 6 hours
|
||||
generic := r.put("generic", "url-abc", "best", 10, 720, "f4") // 6 hours
|
||||
|
||||
alive := func() (s, n, e, g bool) {
|
||||
return r.lookup("youtube", "s", media.Best) != nil, r.lookup("vimeo", "n", media.Best) != nil,
|
||||
r.lookup("twitter", "e", media.Best) != nil, r.lookup("generic", "url-abc", media.Best) != nil
|
||||
}
|
||||
if s, n, e, g := alive(); !s || !n || !e || !g {
|
||||
t.Fatal("fresh entries must all be served")
|
||||
}
|
||||
r.advance(7 * time.Hour)
|
||||
if s, n, e, g := alive(); !s || !n || e || g {
|
||||
t.Fatalf("after 7h: stable=%v normal=%v ephemeral=%v generic=%v", s, n, e, g)
|
||||
}
|
||||
res, err := r.c.Sweep(context.Background())
|
||||
if err != nil || res.Expired != 2 {
|
||||
t.Fatalf("sweep = %+v, %v", res, err)
|
||||
}
|
||||
if r.stored(ephemeral.StorageKey) || r.stored(generic.StorageKey) || !r.stored(stable.StorageKey) {
|
||||
t.Fatal("expired entries lose their files, live ones keep them")
|
||||
}
|
||||
r.advance(8 * 24 * time.Hour)
|
||||
if s, n, _, _ := alive(); !s || n {
|
||||
t.Fatalf("after 8 days: stable=%v normal=%v", s, n)
|
||||
}
|
||||
r.advance(30 * 24 * time.Hour)
|
||||
if _, err := r.c.Sweep(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.stored(stable.StorageKey) || r.stored(normal.StorageKey) {
|
||||
t.Fatal("everything is expired and swept by now")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBudgetEvictsLeastValuableStoredCopies(t *testing.T) {
|
||||
r := newRig(t, func(c *cache.Config) { c.BudgetBytes = 2500 })
|
||||
ctx := context.Background()
|
||||
old := r.put("vimeo", "old", "best", 1000, 720, "f-old")
|
||||
r.advance(time.Hour)
|
||||
popular := r.put("vimeo", "popular", "best", 1000, 720, "f-pop")
|
||||
r.advance(time.Hour)
|
||||
recent := r.put("vimeo", "recent", "best", 1000, 720, "f-new")
|
||||
|
||||
// "popular" is older than "recent" but was requested many times.
|
||||
e := r.lookup("vimeo", "popular", media.Best)
|
||||
for i := 0; i < 5; i++ {
|
||||
r.c.RecordHit(ctx, e)
|
||||
}
|
||||
// 3000 bytes against a budget of 2500: one copy has to go, and it is
|
||||
// the one nobody asked for in the longest time.
|
||||
res, err := r.c.Sweep(ctx)
|
||||
if err != nil || res.Evicted != 1 {
|
||||
t.Fatalf("sweep = %+v, %v", res, err)
|
||||
}
|
||||
if r.stored(old.StorageKey) || !r.stored(popular.StorageKey) || !r.stored(recent.StorageKey) {
|
||||
t.Fatal("the wrong copy was evicted")
|
||||
}
|
||||
// The evicted entry still serves instant resends through its file_id.
|
||||
e = r.lookup("vimeo", "old", media.Best)
|
||||
if e == nil || e.TgFileID != "f-old" || e.StorageKey != "" {
|
||||
t.Fatalf("evicted entry = %+v", e)
|
||||
}
|
||||
|
||||
// Hits outweigh recency: with room for one copy, "popular" survives
|
||||
// although "recent" is newer.
|
||||
r.advance(time.Minute)
|
||||
small := newRigConfig(r, 1000)
|
||||
if res, err := small.Sweep(ctx); err != nil || res.Evicted != 1 {
|
||||
t.Fatalf("second sweep = %+v, %v", res, err)
|
||||
}
|
||||
if !r.stored(popular.StorageKey) || r.stored(recent.StorageKey) {
|
||||
t.Fatal("hit count must protect the popular entry")
|
||||
}
|
||||
// An entry with neither file_id nor stored copy is removed entirely.
|
||||
lone := r.put("vimeo", "lone", "best", 1000, 720, "")
|
||||
tiny := newRigConfig(r, 1)
|
||||
if _, err := tiny.Sweep(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.stored(lone.StorageKey) {
|
||||
t.Fatal("the copy should be gone")
|
||||
}
|
||||
if _, err := r.store.GetCacheEntry(ctx, botID, "vimeo", "lone", "best"); !errors.Is(err, db.ErrNotFound) {
|
||||
t.Fatalf("an entry with nothing to serve must be deleted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// newRigConfig returns a cache on the same data with another budget.
|
||||
func newRigConfig(r *rig, budget int64) *cache.Cache {
|
||||
c := cache.New(cache.Config{Enabled: true, BudgetBytes: budget, TTLDefault: 7 * 24 * time.Hour}, botID, r.store, r.st, nil)
|
||||
c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
|
||||
return c
|
||||
}
|
||||
|
||||
func TestRelatedAliasAndDeriveSource(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
// A 1080p "best" is stored. 720 and 480 can be transcoded from it,
|
||||
// and so can audio.
|
||||
r.put("youtube", "hd", "best", 5000, 1080, "f-hd")
|
||||
for _, p := range []media.Profile{media.P720, media.P480, media.MP3, media.M4A} {
|
||||
alias, source, err := r.c.Related(ctx, "youtube", "hd", p)
|
||||
if err != nil || alias != nil || source == nil || source.Profile != "best" {
|
||||
t.Errorf("%s: alias=%v source=%+v err=%v, want the best copy as source", p, alias, source, err)
|
||||
}
|
||||
}
|
||||
// Nothing sits above best.
|
||||
if alias, source, _ := r.c.Related(ctx, "youtube", "hd", media.Best); alias != nil || source != nil {
|
||||
t.Error("best has nothing to derive from")
|
||||
}
|
||||
|
||||
// A 360p "best" is stored. Asked for as 720 or 480 it is already the
|
||||
// file yt-dlp would fetch, so it is served as is, without transcoding.
|
||||
r.put("youtube", "sd", "best", 800, 360, "f-sd")
|
||||
for _, p := range []media.Profile{media.P720, media.P480} {
|
||||
alias, source, err := r.c.Related(ctx, "youtube", "sd", p)
|
||||
if err != nil || source != nil || alias == nil || alias.TgFileID != "f-sd" {
|
||||
t.Errorf("%s: alias=%+v source=%v err=%v, want the 360p file as alias", p, alias, source, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The nearest profile above wins as a source: less work to scale.
|
||||
r.put("youtube", "multi", "best", 9000, 2160, "f-4k")
|
||||
r.put("youtube", "multi", "720", 2000, 720, "f-720")
|
||||
if _, source, _ := r.c.Related(ctx, "youtube", "multi", media.P480); source == nil || source.Profile != "720" {
|
||||
t.Errorf("480 should derive from the 720 copy, got %+v", source)
|
||||
}
|
||||
|
||||
// Without a stored copy there is nothing to transcode from.
|
||||
r.put("vimeo", "nofile", "best", 5000, 1080, "f-x")
|
||||
e := r.lookup("vimeo", "nofile", media.Best)
|
||||
if err := r.c.DropStored(ctx, "vimeo", "nofile", "best"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, source, _ := r.c.Related(ctx, "vimeo", "nofile", media.P720); source != nil {
|
||||
t.Errorf("an entry without a stored copy (was %s) cannot be a source", e.StorageKey)
|
||||
}
|
||||
// Deriving can be switched off.
|
||||
noDerive := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour, Derive: false}, botID, r.store, r.st, nil)
|
||||
noDerive.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
|
||||
if _, source, _ := noDerive.Related(ctx, "youtube", "hd", media.P720); source != nil {
|
||||
t.Error("derive is off, no source expected")
|
||||
}
|
||||
if alias, _, _ := noDerive.Related(ctx, "youtube", "sd", media.P720); alias == nil {
|
||||
t.Error("aliases need no transcoding and still work with derive off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPurgeDeletesInvalidatesAndBlocks(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
ctx := context.Background()
|
||||
a := r.put("youtube", "bad", "best", 100, 1080, "f-a")
|
||||
b := r.put("youtube", "bad", "mp3", 50, 0, "f-b")
|
||||
keep := r.put("youtube", "good", "best", 100, 1080, "f-k")
|
||||
|
||||
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); blocked {
|
||||
t.Fatal("nothing is blocked yet")
|
||||
}
|
||||
n, err := r.c.Purge(ctx, "youtube", "bad", "copyright notice", 1)
|
||||
if err != nil || n != 2 {
|
||||
t.Fatalf("Purge = %d, %v", n, err)
|
||||
}
|
||||
if r.stored(a.StorageKey) || r.stored(b.StorageKey) || !r.stored(keep.StorageKey) {
|
||||
t.Fatal("purge must delete exactly the files of that video")
|
||||
}
|
||||
if r.lookup("youtube", "bad", media.Best) != nil || r.lookup("youtube", "bad", media.MP3) != nil {
|
||||
t.Fatal("a purged video must not be served")
|
||||
}
|
||||
e, err := r.store.GetCacheEntry(ctx, botID, "youtube", "bad", "best")
|
||||
if err != nil || e.Status != db.CacheBlocked || e.TgFileID != "" || e.StorageKey != "" {
|
||||
t.Fatalf("purged entry = %+v, %v", e, err)
|
||||
}
|
||||
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); !blocked {
|
||||
t.Fatal("the key must be blocked")
|
||||
}
|
||||
if blocked, _ := r.c.Blocked(ctx, "youtube", "good", "youtube.com"); blocked {
|
||||
t.Fatal("other videos stay available")
|
||||
}
|
||||
// A blocked key cannot be cached again, whatever finishes later.
|
||||
late := *a
|
||||
late.StorageKey = "jobs/late/media"
|
||||
if err := r.c.Put(ctx, &late, "f-late", ""); err == nil {
|
||||
t.Fatal("a blocked key must refuse new results")
|
||||
}
|
||||
// Purging a video that was never cached still blocks it.
|
||||
if n, err := r.c.Purge(ctx, "vimeo", "never", "", 1); err != nil || n != 0 {
|
||||
t.Fatalf("purge of an unknown key = %d, %v", n, err)
|
||||
}
|
||||
if blocked, _ := r.c.Blocked(ctx, "vimeo", "never", "vimeo.com"); !blocked {
|
||||
t.Fatal("a never-cached key must be blocked too")
|
||||
}
|
||||
// Expiry sweeps never remove takedown markers.
|
||||
r.advance(365 * 24 * time.Hour)
|
||||
if _, err := r.c.Sweep(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", ""); !blocked {
|
||||
t.Fatal("a takedown must outlive every TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSiteBlocklistCoversSubdomains(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
ctx := context.Background()
|
||||
if err := r.store.AddBlock(ctx, db.BlockSite, "bad.example", "spam", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for site, want := range map[string]bool{
|
||||
"bad.example": true, "cdn.bad.example": true, "a.b.bad.example": true,
|
||||
"notbad.example": false, "example": false, "good.example": false, "": false,
|
||||
} {
|
||||
got, err := r.c.Blocked(ctx, "generic", "url-x", site)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("Blocked(site=%q) = %v, %v; want %v", site, got, err, want)
|
||||
}
|
||||
}
|
||||
if ok, _ := r.store.RemoveBlock(ctx, db.BlockSite, "bad.example"); !ok {
|
||||
t.Fatal("RemoveBlock should report the removal")
|
||||
}
|
||||
if got, _ := r.c.Blocked(ctx, "generic", "url-x", "cdn.bad.example"); got {
|
||||
t.Fatal("an unblocked site must be available again")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepRemovesOrphanFiles(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
ctx := context.Background()
|
||||
// Orphans are judged by the real modification time of their files, so
|
||||
// this test starts its clock at the real time.
|
||||
r.now.Store(time.Now().UnixMilli())
|
||||
cached := r.put("youtube", "v", "best", 100, 720, "f")
|
||||
for _, key := range []string{"jobs/orphan1/media", "jobs/orphan2/media"} {
|
||||
if err := r.st.Put(ctx, key, strings.NewReader("left over"), 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// A file of a job that is still running must survive.
|
||||
live := &db.Job{ID: "livejob", URL: "u", Profile: "best", Status: db.JobRunning, CreatedAt: 1, QueuedAt: 1, MaxAttempts: 2}
|
||||
if err := r.store.InsertJob(ctx, live); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.st.Put(ctx, "jobs/livejob/media", strings.NewReader("in progress"), 11); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Young files are left alone: an upload may still be running.
|
||||
if res, err := r.c.Sweep(ctx); err != nil || res.Orphans != 0 {
|
||||
t.Fatalf("sweep of young files = %+v, %v", res, err)
|
||||
}
|
||||
r.advance(2 * time.Hour)
|
||||
res, err := r.c.Sweep(ctx)
|
||||
if err != nil || res.Orphans != 2 {
|
||||
t.Fatalf("sweep = %+v, %v", res, err)
|
||||
}
|
||||
if r.stored("jobs/orphan1/media") || r.stored("jobs/orphan2/media") {
|
||||
t.Fatal("orphans must be deleted")
|
||||
}
|
||||
if !r.stored(cached.StorageKey) || !r.stored("jobs/livejob/media") {
|
||||
t.Fatal("referenced files must be kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetaLayer(t *testing.T) {
|
||||
r := newRig(t, nil)
|
||||
if _, ok := r.c.MetaGet("https://a.example/1"); ok {
|
||||
t.Fatal("empty meta cache hit")
|
||||
}
|
||||
r.c.MetaPut("https://a.example/1", `{"x":1}`)
|
||||
if v, ok := r.c.MetaGet("https://a.example/1"); !ok || v != `{"x":1}` {
|
||||
t.Fatalf("meta = %q, %v", v, ok)
|
||||
}
|
||||
r.advance(29 * time.Minute)
|
||||
if _, ok := r.c.MetaGet("https://a.example/1"); !ok {
|
||||
t.Fatal("metadata should still be remembered")
|
||||
}
|
||||
r.advance(2 * time.Minute)
|
||||
if _, ok := r.c.MetaGet("https://a.example/1"); ok {
|
||||
t.Fatal("metadata should have expired")
|
||||
}
|
||||
r.c.MetaPut("https://a.example/2", "v")
|
||||
r.c.MetaDrop("https://a.example/2")
|
||||
if _, ok := r.c.MetaGet("https://a.example/2"); ok {
|
||||
t.Fatal("dropped metadata was served")
|
||||
}
|
||||
off := cache.New(cache.Config{Enabled: true, MetaTTL: 0}, botID, r.store, r.st, nil)
|
||||
off.MetaPut("k", "v")
|
||||
if _, ok := off.MetaGet("k"); ok {
|
||||
t.Fatal("a zero TTL turns the metadata layer off")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user