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>
227 lines
8.7 KiB
Go
227 lines
8.7 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
)
|
|
|
|
const cacheCols = `bot_id, extractor, video_id, profile, tg_file_id, tg_file_unique_id, storage_key, size,
|
|
duration, title, uploader, file_ext, width, height, hits, last_hit, expires_at, private, status, created_at`
|
|
|
|
func scanCache(sc interface{ Scan(...any) error }) (*CacheEntry, error) {
|
|
var e CacheEntry
|
|
err := sc.Scan(&e.BotID, &e.Extractor, &e.VideoID, &e.Profile, &e.TgFileID, &e.TgFileUniqueID, &e.StorageKey,
|
|
&e.Size, &e.Duration, &e.Title, &e.Uploader, &e.FileExt, &e.Width, &e.Height, &e.Hits, &e.LastHit,
|
|
&e.ExpiresAt, &e.Private, &e.Status, &e.CreatedAt)
|
|
if err != nil {
|
|
return nil, notFound(err)
|
|
}
|
|
return &e, nil
|
|
}
|
|
|
|
func scanCaches(rows *sql.Rows, err error) ([]*CacheEntry, error) {
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []*CacheEntry
|
|
for rows.Next() {
|
|
e, err := scanCache(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, e)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// GetCacheEntry loads one entry in any status.
|
|
func (s *Store) GetCacheEntry(ctx context.Context, botID int64, extractor, videoID, profile string) (*CacheEntry, error) {
|
|
return scanCache(s.row(ctx, `SELECT `+cacheCols+` FROM cache_entries
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`, botID, extractor, videoID, profile))
|
|
}
|
|
|
|
// CacheEntriesForVideo lists every profile cached for a video.
|
|
func (s *Store) CacheEntriesForVideo(ctx context.Context, botID int64, extractor, videoID string) ([]*CacheEntry, error) {
|
|
return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? ORDER BY profile`, botID, extractor, videoID))
|
|
}
|
|
|
|
// UpsertCacheEntry stores a result. An existing entry keeps its hit
|
|
// counters. A blocked entry is never overwritten.
|
|
func (s *Store) UpsertCacheEntry(ctx context.Context, e *CacheEntry) error {
|
|
_, err := s.exec(ctx, `INSERT INTO cache_entries (`+cacheCols+`)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT (bot_id, extractor, video_id, profile) DO UPDATE SET
|
|
tg_file_id = excluded.tg_file_id,
|
|
tg_file_unique_id = excluded.tg_file_unique_id,
|
|
storage_key = excluded.storage_key,
|
|
size = excluded.size,
|
|
duration = excluded.duration,
|
|
title = excluded.title,
|
|
uploader = excluded.uploader,
|
|
file_ext = excluded.file_ext,
|
|
width = excluded.width,
|
|
height = excluded.height,
|
|
expires_at = excluded.expires_at,
|
|
private = excluded.private
|
|
WHERE cache_entries.status <> 'blocked'`,
|
|
e.BotID, e.Extractor, e.VideoID, e.Profile, e.TgFileID, e.TgFileUniqueID, e.StorageKey, e.Size,
|
|
e.Duration, e.Title, e.Uploader, e.FileExt, e.Width, e.Height, e.Hits, e.LastHit, e.ExpiresAt,
|
|
e.Private, e.Status, e.CreatedAt)
|
|
return err
|
|
}
|
|
|
|
// TouchCacheEntry counts a hit.
|
|
func (s *Store) TouchCacheEntry(ctx context.Context, e *CacheEntry, now int64) error {
|
|
_, err := s.exec(ctx, `UPDATE cache_entries SET hits = hits + 1, last_hit = ?
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`,
|
|
now, e.BotID, e.Extractor, e.VideoID, e.Profile)
|
|
return err
|
|
}
|
|
|
|
// SetCacheFileID replaces the Telegram file_id of an entry. An empty ID
|
|
// invalidates the instant-resend layer.
|
|
func (s *Store) SetCacheFileID(ctx context.Context, e *CacheEntry, fileID, uniqueID string) error {
|
|
_, err := s.exec(ctx, `UPDATE cache_entries SET tg_file_id = ?, tg_file_unique_id = ?
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`,
|
|
fileID, uniqueID, e.BotID, e.Extractor, e.VideoID, e.Profile)
|
|
return err
|
|
}
|
|
|
|
// ClearCacheStorage forgets the stored copy of an entry.
|
|
func (s *Store) ClearCacheStorage(ctx context.Context, e *CacheEntry) error {
|
|
_, err := s.exec(ctx, `UPDATE cache_entries SET storage_key = ''
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`,
|
|
e.BotID, e.Extractor, e.VideoID, e.Profile)
|
|
return err
|
|
}
|
|
|
|
// DeleteCacheEntry removes an entry unless it is a takedown marker.
|
|
func (s *Store) DeleteCacheEntry(ctx context.Context, e *CacheEntry) error {
|
|
_, err := s.exec(ctx, `DELETE FROM cache_entries
|
|
WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ? AND status <> 'blocked'`,
|
|
e.BotID, e.Extractor, e.VideoID, e.Profile)
|
|
return err
|
|
}
|
|
|
|
// BlockCacheKey turns every entry of a video into a takedown marker
|
|
// without a file, and adds a marker for the key as a whole.
|
|
func (s *Store) BlockCacheKey(ctx context.Context, botID int64, extractor, videoID string, now int64) error {
|
|
_, err := s.exec(ctx, `UPDATE cache_entries SET status = 'blocked', tg_file_id = '', tg_file_unique_id = '',
|
|
storage_key = '', size = 0 WHERE bot_id = ? AND extractor = ? AND video_id = ?`, botID, extractor, videoID)
|
|
return err
|
|
}
|
|
|
|
// ExpiredCacheEntries lists ready entries past their expiry.
|
|
func (s *Store) ExpiredCacheEntries(ctx context.Context, botID, now int64, limit int) ([]*CacheEntry, error) {
|
|
return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries
|
|
WHERE bot_id = ? AND status = 'ready' AND expires_at > 0 AND expires_at < ? LIMIT ?`, botID, now, limit))
|
|
}
|
|
|
|
// CacheStoredBytes sums the size of all stored copies.
|
|
func (s *Store) CacheStoredBytes(ctx context.Context, botID int64) (int64, error) {
|
|
var n sql.NullInt64
|
|
err := s.row(ctx, `SELECT SUM(size) FROM cache_entries WHERE bot_id = ? AND status = 'ready' AND storage_key <> ''`,
|
|
botID).Scan(&n)
|
|
return n.Int64, err
|
|
}
|
|
|
|
// CacheEvictionCandidates lists entries with a stored copy, least valuable
|
|
// first. Value is recency plus a bonus per hit: every hit, up to 48,
|
|
// protects an entry like one more hour of recency.
|
|
func (s *Store) CacheEvictionCandidates(ctx context.Context, botID int64, limit int) ([]*CacheEntry, error) {
|
|
return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries
|
|
WHERE bot_id = ? AND status = 'ready' AND storage_key <> ''
|
|
ORDER BY (last_hit + (CASE WHEN hits > 48 THEN 48 ELSE hits END) * 3600000) ASC, created_at ASC
|
|
LIMIT ?`, botID, limit))
|
|
}
|
|
|
|
// CacheStorageKeys returns every storage key the cache still references.
|
|
func (s *Store) CacheStorageKeys(ctx context.Context) (map[string]bool, error) {
|
|
rows, err := s.rows(ctx, `SELECT storage_key FROM cache_entries WHERE storage_key <> ''`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]bool{}
|
|
for rows.Next() {
|
|
var k string
|
|
if err := rows.Scan(&k); err != nil {
|
|
return nil, err
|
|
}
|
|
out[k] = true
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// CacheCounts summarizes the cache for the owner.
|
|
type CacheCounts struct {
|
|
Entries int64
|
|
Stored int64
|
|
Bytes int64
|
|
Hits int64
|
|
Blocked int64
|
|
}
|
|
|
|
// CacheSummary counts entries, stored copies, bytes and hits.
|
|
func (s *Store) CacheSummary(ctx context.Context, botID int64) (CacheCounts, error) {
|
|
var c CacheCounts
|
|
var bytes, hits sql.NullInt64
|
|
err := s.row(ctx, `SELECT
|
|
COALESCE(SUM(CASE WHEN status = 'ready' THEN 1 ELSE 0 END), 0),
|
|
COALESCE(SUM(CASE WHEN status = 'ready' AND storage_key <> '' THEN 1 ELSE 0 END), 0),
|
|
SUM(CASE WHEN status = 'ready' AND storage_key <> '' THEN size ELSE 0 END),
|
|
SUM(hits),
|
|
COALESCE(SUM(CASE WHEN status = 'blocked' THEN 1 ELSE 0 END), 0)
|
|
FROM cache_entries WHERE bot_id = ?`, botID).Scan(&c.Entries, &c.Stored, &bytes, &hits, &c.Blocked)
|
|
c.Bytes, c.Hits = bytes.Int64, hits.Int64
|
|
return c, err
|
|
}
|
|
|
|
// --- blocklist -------------------------------------------------------------
|
|
|
|
// AddBlock adds a site or key to the owner blocklist.
|
|
func (s *Store) AddBlock(ctx context.Context, kind, value, reason string, by int64) error {
|
|
_, err := s.exec(ctx, `INSERT INTO blocklist (kind, value, reason, created_by, created_at) VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT (kind, value) DO UPDATE SET reason = excluded.reason`, kind, value, reason, by, NowMilli())
|
|
return err
|
|
}
|
|
|
|
// RemoveBlock removes an entry and reports whether it existed.
|
|
func (s *Store) RemoveBlock(ctx context.Context, kind, value string) (bool, error) {
|
|
n, err := s.exec(ctx, `DELETE FROM blocklist WHERE kind = ? AND value = ?`, kind, value)
|
|
return n > 0, err
|
|
}
|
|
|
|
// IsBlocked reports whether a site or key is on the blocklist.
|
|
func (s *Store) IsBlocked(ctx context.Context, kind, value string) (bool, error) {
|
|
var n int
|
|
err := s.row(ctx, `SELECT COUNT(*) FROM blocklist WHERE kind = ? AND value = ?`, kind, value).Scan(&n)
|
|
return n > 0, err
|
|
}
|
|
|
|
// Block is one blocklist row.
|
|
type Block struct {
|
|
Kind, Value, Reason string
|
|
CreatedAt int64
|
|
}
|
|
|
|
// ListBlocks returns the blocklist, newest first.
|
|
func (s *Store) ListBlocks(ctx context.Context, limit int) ([]Block, error) {
|
|
rows, err := s.rows(ctx, `SELECT kind, value, reason, created_at FROM blocklist ORDER BY created_at DESC LIMIT ?`, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []Block
|
|
for rows.Next() {
|
|
var b Block
|
|
if err := rows.Scan(&b.Kind, &b.Value, &b.Reason, &b.CreatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, b)
|
|
}
|
|
return out, rows.Err()
|
|
}
|