Files
Media-download-telegram-bot/internal/db/deliveries.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

174 lines
7.1 KiB
Go

package db
import (
"context"
"database/sql"
)
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,
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.MaxSize, &d.MaxDuration)
if err != nil {
return nil, notFound(err)
}
return &d, nil
}
func scanDeliveries(rows *sql.Rows, err error) ([]*Delivery, error) {
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Delivery
for rows.Next() {
d, err := scanDelivery(rows)
if err != nil {
return nil, err
}
out = append(out, d)
}
return out, rows.Err()
}
// InsertDelivery stores a new delivery.
func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error {
if d.CreatedAt == 0 {
d.CreatedAt = NowMilli()
}
d.UpdatedAt = d.CreatedAt
if d.Source == "" {
d.Source = "free"
}
_, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`)
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.MaxSize, d.MaxDuration)
return err
}
// GetDelivery loads a delivery.
func (s *Store) GetDelivery(ctx context.Context, id string) (*Delivery, error) {
return scanDelivery(s.row(ctx, `SELECT `+deliveryCols+` FROM deliveries WHERE id = ?`, id))
}
// DeliveriesForJob lists the deliveries of a job in the given statuses.
func (s *Store) DeliveriesForJob(ctx context.Context, jobID string, statuses ...string) ([]*Delivery, error) {
ph, args := in(statuses)
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE job_id = ? AND status IN (`+ph+`) ORDER BY id`, append([]any{jobID}, args...)...))
}
// ActiveDeliveriesForUser lists a user's deliveries that are still waiting.
func (s *Store) ActiveDeliveriesForUser(ctx context.Context, userID int64) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE user_id = ? AND status IN ('pending', 'sending') ORDER BY id`, userID))
}
// CountActiveDeliveries counts a user's waiting deliveries.
func (s *Store) CountActiveDeliveries(ctx context.Context, userID int64) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE user_id = ? AND status IN ('pending', 'sending')`,
userID).Scan(&n)
return n, err
}
// CountDeliveriesInStatus counts the deliveries of a job in the statuses.
func (s *Store) CountDeliveriesInStatus(ctx context.Context, jobID string, statuses ...string) (int, error) {
ph, args := in(statuses)
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE job_id = ? AND status IN (`+ph+`)`,
append([]any{jobID}, args...)...).Scan(&n)
return n, err
}
// TransitionDelivery moves a delivery between statuses and reports whether
// the row was in the expected status.
func (s *Store) TransitionDelivery(ctx context.Context, id, from, to, errorCode string) (bool, error) {
n, err := s.exec(ctx, `UPDATE deliveries SET status = ?, error_code = ?, updated_at = ?,
attempts = attempts + CASE WHEN ? = 'sending' THEN 1 ELSE 0 END
WHERE id = ? AND status = ?`, to, errorCode, NowMilli(), to, id, from)
return n == 1, err
}
// MarkDeliverySent records the Telegram file and message of a delivery.
func (s *Store) MarkDeliverySent(ctx context.Context, id, fileID string, messageID int64) error {
_, err := s.exec(ctx, `UPDATE deliveries SET status = 'sent', tg_file_id = ?, tg_message_id = ?,
error_code = '', updated_at = ? WHERE id = ?`, fileID, messageID, NowMilli(), id)
return err
}
// SetDeliveryStatusMessage records which message shows the live status.
func (s *Store) SetDeliveryStatusMessage(ctx context.Context, id string, messageID int64, isPhoto bool) error {
_, err := s.exec(ctx, `UPDATE deliveries SET status_message_id = ?, status_is_photo = ?, updated_at = ?
WHERE id = ?`, messageID, isPhoto, NowMilli(), id)
return err
}
// StaleSendingDeliveries lists deliveries stuck in sending since before the
// cutoff, which happens when the core stops in the middle of an upload.
func (s *Store) StaleSendingDeliveries(ctx context.Context, before int64) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE status = 'sending' AND updated_at < ? ORDER BY id`, before))
}
// PendingDeliveryJobIDs lists the jobs in a status that still have pending
// deliveries. The core uses it to resume work after a restart.
func (s *Store) PendingDeliveryJobIDs(ctx context.Context, jobStatus string, limit int) ([]string, error) {
rows, err := s.rows(ctx, `SELECT DISTINCT j.id FROM jobs j
JOIN deliveries d ON d.job_id = j.id
WHERE j.status = ? AND d.status = 'pending' ORDER BY j.id LIMIT ?`, jobStatus, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
// MarkDeliveryReleased flags a delivery as refunded and reports whether
// this call was the one that flagged it. It is the idempotency guard for
// giving back a charge and a quota slot.
func (s *Store) MarkDeliveryReleased(ctx context.Context, id string) (bool, error) {
n, err := s.exec(ctx, `UPDATE deliveries SET released = ?, updated_at = ? WHERE id = ? AND released = ?`,
true, NowMilli(), id, false)
return n == 1, err
}
// UnreleasedDeliveries lists deliveries that ended without a file and have
// not been refunded yet. It is the safety net behind the refund events.
func (s *Store) UnreleasedDeliveries(ctx context.Context, limit int) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE status IN ('failed', 'cancelled') AND released = ?
AND (charge_sats > 0 OR quota_day > 0) ORDER BY id LIMIT ?`, false, limit))
}
// CountDeliveriesForRequest counts the deliveries created from a request.
func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string) (int, error) {
var n int
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))
}