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
+226
View File
@@ -0,0 +1,226 @@
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()
}
+13 -4
View File
@@ -7,13 +7,15 @@ import (
const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id,
status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id,
tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released`
tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released,
max_size, max_duration`
func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) {
var d Delivery
err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID,
&d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID,
&d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released)
&d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released,
&d.MaxSize, &d.MaxDuration)
if err != nil {
return nil, notFound(err)
}
@@ -46,10 +48,11 @@ func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error {
d.Source = "free"
}
_, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID,
d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID,
d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released)
d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released,
d.MaxSize, d.MaxDuration)
return err
}
@@ -162,3 +165,9 @@ func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string)
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE request_id = ?`, requestID).Scan(&n)
return n, err
}
// History lists a user's delivered files, newest first.
func (s *Store) History(ctx context.Context, userID int64, limit int) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE user_id = ? AND status = 'sent' ORDER BY updated_at DESC, id DESC LIMIT ?`, userID, limit))
}
+77 -8
View File
@@ -10,7 +10,7 @@ const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status,
required_tags, max_size, max_duration, attempts, max_attempts, worker_id, lease_expires_at,
cancel_requested, stage, progress_bytes, total_bytes, error_code, error_detail, storage_key,
file_ext, file_size, duration, width, height, title, uploader, created_at, queued_at,
started_at, finished_at`
started_at, finished_at, source_key, tg_file_id, cacheable, cache_hit`
func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
var j Job
@@ -18,7 +18,8 @@ func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
&j.Lane, &j.Priority, &j.RequiredTags, &j.MaxSize, &j.MaxDuration, &j.Attempts, &j.MaxAttempts,
&j.WorkerID, &j.LeaseExpiresAt, &j.CancelRequested, &j.Stage, &j.ProgressBytes, &j.TotalBytes,
&j.ErrorCode, &j.ErrorDetail, &j.StorageKey, &j.FileExt, &j.FileSize, &j.Duration, &j.Width,
&j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt)
&j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt,
&j.SourceKey, &j.TgFileID, &j.Cacheable, &j.CacheHit)
if err != nil {
return nil, notFound(err)
}
@@ -44,12 +45,13 @@ func scanJobs(rows *sql.Rows, err error) ([]*Job, error) {
// InsertJob stores a new job.
func (s *Store) InsertJob(ctx context.Context, j *Job) error {
_, err := s.exec(ctx, `INSERT INTO jobs (`+jobCols+`) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?)`,
j.ID, j.Kind, j.URL, j.Extractor, j.VideoID, j.Profile, j.CacheKey, j.Status, j.Lane, j.Priority,
j.RequiredTags, j.MaxSize, j.MaxDuration, j.Attempts, j.MaxAttempts, j.WorkerID, j.LeaseExpiresAt,
j.CancelRequested, j.Stage, j.ProgressBytes, j.TotalBytes, j.ErrorCode, j.ErrorDetail, j.StorageKey,
j.FileExt, j.FileSize, j.Duration, j.Width, j.Height, j.Title, j.Uploader, j.CreatedAt, j.QueuedAt,
j.StartedAt, j.FinishedAt)
j.StartedAt, j.FinishedAt, j.SourceKey, j.TgFileID, j.Cacheable, j.CacheHit)
return err
}
@@ -111,18 +113,20 @@ type JobResult struct {
VideoID string
}
// CompleteJob stores the result and moves the job to delivering.
// CompleteJob stores the result and moves the job to delivering. The
// extractor and video ID a job was queued with are its cache key and are
// kept; the worker's values only fill them in when they were empty.
func (s *Store) CompleteJob(ctx context.Context, id, workerID string, r JobResult, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET status = 'delivering', storage_key = ?, file_ext = ?, file_size = ?,
duration = ?, width = ?, height = ?,
title = CASE WHEN ? <> '' THEN ? ELSE title END,
uploader = CASE WHEN ? <> '' THEN ? ELSE uploader END,
extractor = CASE WHEN ? <> '' THEN ? ELSE extractor END,
video_id = CASE WHEN ? <> '' THEN ? ELSE video_id END,
extractor = CASE WHEN extractor = '' THEN ? ELSE extractor END,
video_id = CASE WHEN video_id = '' THEN ? ELSE video_id END,
lease_expires_at = 0, stage = 'uploading', finished_at = ?
WHERE id = ? AND worker_id = ? AND status = 'running'`,
r.StorageKey, r.FileExt, r.FileSize, r.Duration, r.Width, r.Height,
r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.Extractor, r.VideoID, r.VideoID,
r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.VideoID,
now, id, workerID)
return n == 1, err
}
@@ -240,3 +244,68 @@ func (s *Store) PromoteJob(ctx context.Context, id string) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET lane = 'paid' WHERE id = ? AND status = 'queued' AND lane = 'free'`, id)
return n == 1, err
}
// ActiveJobForKey returns the newest queued or running job for a cache
// key, which a second requester can share, or ErrNotFound.
func (s *Store) ActiveJobForKey(ctx context.Context, cacheKey string) (*Job, error) {
return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs
WHERE cache_key = ? AND status IN ('queued', 'running') ORDER BY id DESC LIMIT 1`, cacheKey))
}
// RaiseJob lifts a queued job to cover another requester: the caps become
// the looser of the two (0 means no cap) and the lane becomes paid when
// the newcomer pays.
func (s *Store) RaiseJob(ctx context.Context, id string, maxSize, maxDuration int64, lane string) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET
max_size = CASE WHEN max_size = 0 OR ? = 0 THEN 0 WHEN ? > max_size THEN ? ELSE max_size END,
max_duration = CASE WHEN max_duration = 0 OR ? = 0 THEN 0 WHEN ? > max_duration THEN ? ELSE max_duration END,
lane = CASE WHEN ? = 'paid' THEN 'paid' ELSE lane END
WHERE id = ? AND status = 'queued'`,
maxSize, maxSize, maxSize, maxDuration, maxDuration, maxDuration, lane, id)
return n == 1, err
}
// RedownloadJob turns a job that could not be served from the cache or
// derived from a stored copy into a plain download and queues it. The
// attempt counter starts over: nothing was the job's fault.
func (s *Store) RedownloadJob(ctx context.Context, id string, from []string, now int64) (bool, error) {
ph, args := in(from)
all := append([]any{KindDownload, false, now, id}, args...)
n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', kind = ?, cache_hit = ?, source_key = '',
tg_file_id = '', storage_key = '', worker_id = '', lease_expires_at = 0, attempts = 0, stage = '',
progress_bytes = 0, total_bytes = 0, queued_at = ?, error_code = '', error_detail = ''
WHERE id = ? AND status IN (`+ph+`)`, all...)
return n == 1, err
}
// SetJobFileID records the Telegram file_id a job's file got.
func (s *Store) SetJobFileID(ctx context.Context, id, fileID string) error {
_, err := s.exec(ctx, `UPDATE jobs SET tg_file_id = ? WHERE id = ?`, fileID, id)
return err
}
// JobStorageKeys lists the storage keys still referenced by jobs that are
// not finished, so the orphan sweeper leaves them alone.
func (s *Store) JobStorageKeys(ctx context.Context) (map[string]bool, error) {
rows, err := s.rows(ctx, `SELECT id, storage_key, source_key FROM jobs
WHERE status IN ('queued', 'running', 'delivering')`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]bool{}
for rows.Next() {
var id, key, src string
if err := rows.Scan(&id, &key, &src); err != nil {
return nil, err
}
out["jobs/"+id+"/media"] = true
if key != "" {
out[key] = true
}
if src != "" {
out[src] = true
}
}
return out, rows.Err()
}
+75
View File
@@ -0,0 +1,75 @@
-- +goose Up
-- The smart cache. One row per (bot, extractor, video, profile).
-- tg_file_id layer 1: resend instantly, valid for one bot token only
-- storage_key layer 2: stored copy, used for re-upload and transcoding
-- A row with status 'blocked' is a takedown: it has no file and stops the
-- key from being downloaded or cached again.
CREATE TABLE cache_entries (
bot_id BIGINT NOT NULL,
extractor TEXT NOT NULL,
video_id TEXT NOT NULL,
profile TEXT NOT NULL,
tg_file_id TEXT NOT NULL DEFAULT '',
tg_file_unique_id TEXT NOT NULL DEFAULT '',
storage_key TEXT NOT NULL DEFAULT '',
size BIGINT NOT NULL DEFAULT 0,
duration BIGINT NOT NULL DEFAULT 0,
title TEXT NOT NULL DEFAULT '',
uploader TEXT NOT NULL DEFAULT '',
file_ext TEXT NOT NULL DEFAULT '',
width INTEGER NOT NULL DEFAULT 0,
height INTEGER NOT NULL DEFAULT 0,
hits BIGINT NOT NULL DEFAULT 0,
last_hit BIGINT NOT NULL DEFAULT 0,
expires_at BIGINT NOT NULL DEFAULT 0,
private BOOLEAN NOT NULL DEFAULT FALSE,
status TEXT NOT NULL DEFAULT 'ready',
created_at BIGINT NOT NULL,
PRIMARY KEY (bot_id, extractor, video_id, profile)
);
CREATE INDEX cache_expiry_idx ON cache_entries (status, expires_at);
CREATE INDEX cache_lru_idx ON cache_entries (status, last_hit);
-- Owner blocklist: kind is 'site' (a host) or 'key' (extractor and video).
CREATE TABLE blocklist (
kind TEXT NOT NULL,
value TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
created_by BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
PRIMARY KEY (kind, value)
);
-- source_key: stored copy a derive job transcodes from.
-- tg_file_id: file_id a cache hit resends.
-- cacheable: whether the result may enter the cache.
-- cache_hit: the job was served from the cache and never saw a worker.
ALTER TABLE jobs ADD COLUMN source_key TEXT NOT NULL DEFAULT '';
ALTER TABLE jobs ADD COLUMN tg_file_id TEXT NOT NULL DEFAULT '';
ALTER TABLE jobs ADD COLUMN cacheable BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE jobs ADD COLUMN cache_hit BOOLEAN NOT NULL DEFAULT FALSE;
CREATE INDEX jobs_cache_key_idx ON jobs (cache_key, status);
-- Each requester keeps their own caps, because several requesters with
-- different limits can share one job.
ALTER TABLE deliveries ADD COLUMN max_size BIGINT NOT NULL DEFAULT 0;
ALTER TABLE deliveries ADD COLUMN max_duration BIGINT NOT NULL DEFAULT 0;
-- Playlist items are requests that wait their turn under a parent.
ALTER TABLE requests ADD COLUMN parent_id TEXT NOT NULL DEFAULT '';
ALTER TABLE requests ADD COLUMN profile TEXT NOT NULL DEFAULT '';
CREATE INDEX requests_waiting_idx ON requests (status, user_id, created_at);
-- +goose Down
DROP INDEX requests_waiting_idx;
ALTER TABLE requests DROP COLUMN profile;
ALTER TABLE requests DROP COLUMN parent_id;
ALTER TABLE deliveries DROP COLUMN max_duration;
ALTER TABLE deliveries DROP COLUMN max_size;
DROP INDEX jobs_cache_key_idx;
ALTER TABLE jobs DROP COLUMN cache_hit;
ALTER TABLE jobs DROP COLUMN cacheable;
ALTER TABLE jobs DROP COLUMN tg_file_id;
ALTER TABLE jobs DROP COLUMN source_key;
DROP TABLE blocklist;
DROP TABLE cache_entries;
+56
View File
@@ -5,6 +5,8 @@ const (
RequestReady = "ready" // card shown, waiting for a format choice
RequestChosen = "chosen" // a format was picked and a job exists
RequestCancelled = "cancelled" // the requester dismissed the card
RequestWaiting = "waiting" // playlist item waiting for a free slot
RequestFailed = "failed" // playlist item that could not start
)
// Job statuses.
@@ -35,6 +37,20 @@ const (
// Job kinds.
const (
KindDownload = "download"
// KindDerive transcodes a stored copy into a lower profile.
KindDerive = "derive"
)
// Cache entry statuses.
const (
CacheReady = "ready"
CacheBlocked = "blocked" // taken down: never download or cache again
)
// Blocklist kinds.
const (
BlockSite = "site"
BlockKey = "key"
)
// User is a Telegram user known to the bot.
@@ -67,6 +83,10 @@ type Request struct {
Lang string
CreatedAt int64
UpdatedAt int64
// ParentID is the playlist request an item belongs to.
ParentID string
// Profile is the format chosen for a waiting playlist item.
Profile string
}
// Job is one unit of work for a worker.
@@ -106,6 +126,14 @@ type Job struct {
QueuedAt int64
StartedAt int64
FinishedAt int64
// SourceKey is the stored copy a derive job transcodes from.
SourceKey string
// TgFileID is the Telegram file_id of the result, when known.
TgFileID string
// Cacheable says the result may be kept in the cache.
Cacheable bool
// CacheHit says the job was served from the cache without a worker.
CacheHit bool
}
// Active reports whether the job still needs a worker or the core.
@@ -143,6 +171,34 @@ type Delivery struct {
QuotaDay int
// Released is true once charge and quota were given back.
Released bool
// MaxSize and MaxDuration are this requester's own caps. Requesters
// who share a job can have different limits.
MaxSize int64
MaxDuration int64
}
// CacheEntry is one cached result.
type CacheEntry struct {
BotID int64
Extractor string
VideoID string
Profile string
TgFileID string
TgFileUniqueID string
StorageKey string
Size int64
Duration int64
Title string
Uploader string
FileExt string
Width int
Height int
Hits int64
LastHit int64
ExpiresAt int64
Private bool
Status string
CreatedAt int64
}
// Wallet owner types.
+46 -4
View File
@@ -3,12 +3,12 @@ package db
import "context"
const requestCols = `id, user_id, chat_id, chat_type, source_message_id, card_message_id,
card_is_photo, url, status, info, lang, created_at, updated_at`
card_is_photo, url, status, info, lang, created_at, updated_at, parent_id, profile`
func scanRequest(sc interface{ Scan(...any) error }) (*Request, error) {
var r Request
err := sc.Scan(&r.ID, &r.UserID, &r.ChatID, &r.ChatType, &r.SourceMessageID, &r.CardMessageID,
&r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt)
&r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt, &r.ParentID, &r.Profile)
if err != nil {
return nil, notFound(err)
}
@@ -22,9 +22,9 @@ func (s *Store) InsertRequest(ctx context.Context, r *Request) error {
}
r.UpdatedAt = r.CreatedAt
_, err := s.exec(ctx, `INSERT INTO requests (`+requestCols+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
r.ID, r.UserID, r.ChatID, r.ChatType, r.SourceMessageID, r.CardMessageID,
r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt)
r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt, r.ParentID, r.Profile)
return err
}
@@ -48,3 +48,45 @@ func (s *Store) TransitionRequest(ctx context.Context, id, from, to string) (boo
to, NowMilli(), id, from)
return n == 1, err
}
// SetRequestInfo stores the metadata of a request.
func (s *Store) SetRequestInfo(ctx context.Context, id, info string) error {
_, err := s.exec(ctx, `UPDATE requests SET info = ?, updated_at = ? WHERE id = ?`, info, NowMilli(), id)
return err
}
// WaitingRequests lists playlist items that have not started yet, oldest
// first, at most one per user so the pump stays fair.
func (s *Store) WaitingRequests(ctx context.Context, limit int) ([]*Request, error) {
rows, err := s.rows(ctx, `SELECT `+requestCols+` FROM requests r
WHERE status = 'waiting' AND id = (
SELECT MIN(w.id) FROM requests w WHERE w.status = 'waiting' AND w.user_id = r.user_id
) ORDER BY id LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Request
for rows.Next() {
r, err := scanRequest(rows)
if err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}
// CancelWaitingRequests cancels a user's playlist items that have not
// started, and returns how many there were.
func (s *Store) CancelWaitingRequests(ctx context.Context, userID int64) (int64, error) {
return s.exec(ctx, `UPDATE requests SET status = 'cancelled', updated_at = ?
WHERE user_id = ? AND status = 'waiting'`, NowMilli(), userID)
}
// CountWaitingRequests counts a user's playlist items that wait to start.
func (s *Store) CountWaitingRequests(ctx context.Context, userID int64) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM requests WHERE user_id = ? AND status = 'waiting'`, userID).Scan(&n)
return n, err
}