Files
Media-download-telegram-bot/internal/db/requests.go
T
MichilisandClaude Fable 5.2 9c9d641eda 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>
2026-11-18 08:38:38 +00:00

93 lines
3.5 KiB
Go

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, 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.ParentID, &r.Profile)
if err != nil {
return nil, notFound(err)
}
return &r, nil
}
// InsertRequest stores a new request.
func (s *Store) InsertRequest(ctx context.Context, r *Request) error {
if r.CreatedAt == 0 {
r.CreatedAt = NowMilli()
}
r.UpdatedAt = r.CreatedAt
_, err := s.exec(ctx, `INSERT INTO requests (`+requestCols+`)
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.ParentID, r.Profile)
return err
}
// GetRequest loads a request.
func (s *Store) GetRequest(ctx context.Context, id string) (*Request, error) {
return scanRequest(s.row(ctx, `SELECT `+requestCols+` FROM requests WHERE id = ?`, id))
}
// SetRequestCard records which message shows the card.
func (s *Store) SetRequestCard(ctx context.Context, id string, messageID int64, isPhoto bool) error {
_, err := s.exec(ctx, `UPDATE requests SET card_message_id = ?, card_is_photo = ?, updated_at = ? WHERE id = ?`,
messageID, isPhoto, NowMilli(), id)
return err
}
// TransitionRequest moves a request from one status to another and reports
// whether the row was in the expected status. It is the guard against two
// button presses racing each other.
func (s *Store) TransitionRequest(ctx context.Context, id, from, to string) (bool, error) {
n, err := s.exec(ctx, `UPDATE requests SET status = ?, updated_at = ? WHERE id = ? AND status = ?`,
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
}