Files
Media-download-telegram-bot/internal/db/jobs.go
T
MichilisandClaude Fable 5.2 3b361c17a1 Phase 1: core bot
Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 07:33:32 +00:00

216 lines
8.6 KiB
Go

package db
import (
"context"
"database/sql"
"errors"
)
const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, lane, priority,
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`
func scanJob(sc interface{ Scan(...any) error }) (*Job, error) {
var j Job
err := sc.Scan(&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)
if err != nil {
return nil, notFound(err)
}
return &j, nil
}
func scanJobs(rows *sql.Rows, err error) ([]*Job, error) {
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Job
for rows.Next() {
j, err := scanJob(rows)
if err != nil {
return nil, err
}
out = append(out, j)
}
return out, rows.Err()
}
// 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)
return err
}
// GetJob loads a job.
func (s *Store) GetJob(ctx context.Context, id string) (*Job, error) {
return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs WHERE id = ?`, id))
}
// laneRank is the SQL expression that orders lanes: paid before free.
const laneRank = `CASE lane WHEN 'paid' THEN 0 ELSE 1 END`
// queueOrder is the one ordering used for claiming and for positions.
const queueOrder = laneRank + ` ASC, priority DESC, queued_at ASC, id ASC`
// NextQueuedJob returns the first queued job in the given lanes, locking it
// against other claimers. It must run inside a transaction. On Postgres the
// lock is FOR UPDATE SKIP LOCKED; on SQLite the immediate transaction
// already serializes writers.
func (s *Store) NextQueuedJob(ctx context.Context, lanes []string) (*Job, error) {
if !s.inTx {
return nil, errors.New("db: NextQueuedJob needs a transaction")
}
ph, args := in(lanes)
q := `SELECT ` + jobCols + ` FROM jobs WHERE status = 'queued' AND lane IN (` + ph + `)
ORDER BY ` + queueOrder + ` LIMIT 1`
if s.db.Dialect == Postgres {
q += ` FOR UPDATE SKIP LOCKED`
}
return scanJob(s.row(ctx, q, args...))
}
// MarkJobRunning hands a queued job to a worker.
func (s *Store) MarkJobRunning(ctx context.Context, id, workerID string, leaseUntil, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET status = 'running', worker_id = ?, lease_expires_at = ?,
attempts = attempts + 1, started_at = ?, stage = '', progress_bytes = 0, total_bytes = 0
WHERE id = ? AND status = 'queued'`, workerID, leaseUntil, now, id)
return n == 1, err
}
// HeartbeatJob extends the lease and stores progress. It reports false when
// the job is no longer owned by the worker.
func (s *Store) HeartbeatJob(ctx context.Context, id, workerID string, leaseUntil int64, stage string, done, total int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE jobs SET lease_expires_at = ?, stage = ?, progress_bytes = ?, total_bytes = ?
WHERE id = ? AND worker_id = ? AND status = 'running'`, leaseUntil, stage, done, total, id, workerID)
return n == 1, err
}
// JobResult is what a worker reports on success.
type JobResult struct {
StorageKey string
FileExt string
FileSize int64
Duration int64
Width int
Height int
Title string
Uploader string
Extractor string
VideoID string
}
// CompleteJob stores the result and moves the job to delivering.
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,
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,
now, id, workerID)
return n == 1, err
}
// RequeueJob puts a running job back in the queue. The original queued_at is
// kept so a retried job does not lose its place. refundAttempt gives the
// attempt back, for interruptions that were not the job's fault.
func (s *Store) RequeueJob(ctx context.Context, id, errorCode, detail string, refundAttempt bool) (bool, error) {
refund := 0
if refundAttempt {
refund = 1
}
n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', worker_id = '', lease_expires_at = 0,
stage = '', progress_bytes = 0, total_bytes = 0, error_code = ?, error_detail = ?,
attempts = attempts - ?
WHERE id = ? AND status = 'running'`, errorCode, detail, refund, id)
return n == 1, err
}
// FinishJob moves a job to a terminal status from any of the given statuses.
func (s *Store) FinishJob(ctx context.Context, id, status, errorCode, detail string, from []string, now int64) (bool, error) {
ph, args := in(from)
all := append([]any{status, errorCode, detail, now, id}, args...)
n, err := s.exec(ctx, `UPDATE jobs SET status = ?, error_code = ?, error_detail = ?, lease_expires_at = 0,
finished_at = ? WHERE id = ? AND status IN (`+ph+`)`, all...)
return n == 1, err
}
// RequestJobCancel flags a running job so the worker stops at its next
// heartbeat.
func (s *Store) RequestJobCancel(ctx context.Context, id string) error {
_, err := s.exec(ctx, `UPDATE jobs SET cancel_requested = ? WHERE id = ? AND status = 'running'`, true, id)
return err
}
// ExpiredJobs lists running jobs whose lease ran out.
func (s *Store) ExpiredJobs(ctx context.Context, now int64) ([]*Job, error) {
return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs
WHERE status = 'running' AND lease_expires_at < ? ORDER BY id`, now))
}
// JobsByStatus lists jobs in a status, oldest first.
func (s *Store) JobsByStatus(ctx context.Context, status string, limit int) ([]*Job, error) {
return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status = ? ORDER BY `+queueOrder+` LIMIT ?`,
status, limit))
}
// CountQueued counts queued jobs in a lane.
func (s *Store) CountQueued(ctx context.Context, lane string) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND lane = ?`, lane).Scan(&n)
return n, err
}
// QueuePosition returns how many queued jobs are ahead of j in claim order.
// Zero means j is next.
func (s *Store) QueuePosition(ctx context.Context, j *Job) (int, error) {
rank := 1
if j.Lane == LanePaid {
rank = 0
}
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND id <> ? AND (
`+laneRank+` < ?
OR (`+laneRank+` = ? AND (
priority > ?
OR (priority = ? AND (queued_at < ? OR (queued_at = ? AND id < ?)))
))
)`, j.ID, rank, rank, j.Priority, j.Priority, j.QueuedAt, j.QueuedAt, j.ID).Scan(&n)
return n, err
}
// AvgJobSeconds returns the average run time of the most recent finished
// jobs, or 0 when there is no history.
func (s *Store) AvgJobSeconds(ctx context.Context, sample int) (float64, error) {
var avg sql.NullFloat64
err := s.row(ctx, `SELECT AVG(d) FROM (
SELECT (finished_at - started_at) / 1000.0 AS d FROM jobs
WHERE status IN ('done', 'delivering') AND started_at > 0 AND finished_at >= started_at
ORDER BY finished_at DESC LIMIT ?
) recent`, sample).Scan(&avg)
return avg.Float64, err
}
// CountRunning counts jobs currently held by workers.
func (s *Store) CountRunning(ctx context.Context) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'running'`).Scan(&n)
return n, err
}