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>
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
// Package db is the data layer. SQLite and Postgres share one schema and
|
||||
// one set of queries; the few places where they differ go through Dialect.
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
_ "modernc.org/sqlite" // registers the "sqlite" driver
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
// Dialect names a SQL backend.
|
||||
type Dialect string
|
||||
|
||||
// The supported dialects.
|
||||
const (
|
||||
SQLite Dialect = "sqlite"
|
||||
Postgres Dialect = "postgres"
|
||||
)
|
||||
|
||||
// ErrNotFound is returned when a row does not exist.
|
||||
var ErrNotFound = errors.New("db: not found")
|
||||
|
||||
// DB is an open database.
|
||||
type DB struct {
|
||||
SQL *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// Open connects to the database named by driver ("sqlite" or "postgres").
|
||||
// For sqlite the DSN is a file path.
|
||||
func Open(ctx context.Context, driver, dsn string) (*DB, error) {
|
||||
switch Dialect(driver) {
|
||||
case SQLite:
|
||||
return openSQLite(ctx, dsn)
|
||||
case Postgres:
|
||||
return openPostgres(ctx, dsn)
|
||||
}
|
||||
return nil, fmt.Errorf("db: unknown driver %q", driver)
|
||||
}
|
||||
|
||||
func openSQLite(ctx context.Context, path string) (*DB, error) {
|
||||
if path == "" {
|
||||
return nil, errors.New("db: sqlite needs a file path")
|
||||
}
|
||||
if dir := filepath.Dir(path); dir != "." {
|
||||
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Add("_pragma", "busy_timeout(10000)")
|
||||
q.Add("_pragma", "journal_mode(WAL)")
|
||||
q.Add("_pragma", "synchronous(NORMAL)")
|
||||
q.Add("_pragma", "foreign_keys(1)")
|
||||
// Every transaction takes the write lock up front. This is what makes
|
||||
// job claiming atomic on SQLite and avoids lock upgrade deadlocks.
|
||||
q.Set("_txlock", "immediate")
|
||||
sqldb, err := sql.Open("sqlite", "file:"+path+"?"+q.Encode())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqldb.SetMaxOpenConns(4)
|
||||
sqldb.SetMaxIdleConns(4)
|
||||
if err := sqldb.PingContext(ctx); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("db: open sqlite %s: %w", path, err)
|
||||
}
|
||||
return &DB{SQL: sqldb, Dialect: SQLite}, nil
|
||||
}
|
||||
|
||||
// Close closes the pool.
|
||||
func (d *DB) Close() error { return d.SQL.Close() }
|
||||
|
||||
// Migrate applies all pending migrations.
|
||||
func (d *DB) Migrate(ctx context.Context) error {
|
||||
sub, err := fs.Sub(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dialect := goose.DialectSQLite3
|
||||
if d.Dialect == Postgres {
|
||||
dialect = goose.DialectPostgres
|
||||
}
|
||||
p, err := goose.NewProvider(dialect, d.SQL, sub)
|
||||
if err != nil {
|
||||
return fmt.Errorf("db: migrations: %w", err)
|
||||
}
|
||||
if _, err := p.Up(ctx); err != nil {
|
||||
return fmt.Errorf("db: migrate: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// querier is satisfied by *sql.DB and *sql.Tx.
|
||||
type querier interface {
|
||||
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
// Store runs queries, either on the pool or inside a transaction.
|
||||
type Store struct {
|
||||
db *DB
|
||||
q querier
|
||||
inTx bool
|
||||
}
|
||||
|
||||
// Store returns a Store that runs each query on the pool.
|
||||
func (d *DB) Store() *Store { return &Store{db: d, q: d.SQL} }
|
||||
|
||||
// Dialect returns the dialect of the underlying database.
|
||||
func (s *Store) Dialect() Dialect { return s.db.Dialect }
|
||||
|
||||
// InTx runs fn in a transaction. Nested calls reuse the outer transaction.
|
||||
// On SQLite the transaction holds the write lock from the start.
|
||||
func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error {
|
||||
if s.inTx {
|
||||
return fn(s)
|
||||
}
|
||||
tx, err := s.db.SQL.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fn(&Store{db: s.db, q: tx, inTx: true}); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// rebind turns "?" placeholders into "$1, $2, ..." for Postgres.
|
||||
func (s *Store) rebind(query string) string {
|
||||
if s.db.Dialect != Postgres {
|
||||
return query
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(query) + 8)
|
||||
n := 0
|
||||
for i := 0; i < len(query); i++ {
|
||||
if query[i] == '?' {
|
||||
n++
|
||||
b.WriteByte('$')
|
||||
b.WriteString(strconv.Itoa(n))
|
||||
continue
|
||||
}
|
||||
b.WriteByte(query[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (s *Store) exec(ctx context.Context, query string, args ...any) (int64, error) {
|
||||
res, err := s.q.ExecContext(ctx, s.rebind(query), args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *Store) row(ctx context.Context, query string, args ...any) *sql.Row {
|
||||
return s.q.QueryRowContext(ctx, s.rebind(query), args...)
|
||||
}
|
||||
|
||||
func (s *Store) rows(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
|
||||
return s.q.QueryContext(ctx, s.rebind(query), args...)
|
||||
}
|
||||
|
||||
// NowMilli is the timestamp format used in every table.
|
||||
func NowMilli() int64 { return time.Now().UnixMilli() }
|
||||
|
||||
func notFound(err error) error {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// in builds "?, ?, ?" and the matching argument list.
|
||||
func in[T any](vals []T) (string, []any) {
|
||||
args := make([]any, len(vals))
|
||||
for i, v := range vals {
|
||||
args[i] = v
|
||||
}
|
||||
return strings.TrimSuffix(strings.Repeat("?, ", len(vals)), ", "), args
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package dbtest opens throwaway databases for tests.
|
||||
package dbtest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
)
|
||||
|
||||
// Open returns a migrated database that is removed when the test ends.
|
||||
func Open(t testing.TB) *db.DB {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
d, err := db.Open(ctx, "sqlite", filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
if err := d.Migrate(ctx); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
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`
|
||||
|
||||
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)
|
||||
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
|
||||
_, 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)
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
-- +goose Up
|
||||
-- One schema for SQLite and Postgres. Rules that keep it portable:
|
||||
-- identifiers are application generated TEXT, timestamps are unix
|
||||
-- milliseconds in BIGINT, flags are BOOLEAN, no engine specific types.
|
||||
|
||||
CREATE TABLE users (
|
||||
id BIGINT PRIMARY KEY,
|
||||
username TEXT NOT NULL DEFAULT '',
|
||||
first_name TEXT NOT NULL DEFAULT '',
|
||||
lang TEXT NOT NULL DEFAULT '',
|
||||
lang_override TEXT NOT NULL DEFAULT '',
|
||||
banned BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at BIGINT NOT NULL,
|
||||
last_seen_at BIGINT NOT NULL
|
||||
);
|
||||
|
||||
-- A request is one link a user sent, shown as a card with format buttons.
|
||||
CREATE TABLE requests (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
chat_id BIGINT NOT NULL,
|
||||
chat_type TEXT NOT NULL DEFAULT 'private',
|
||||
source_message_id BIGINT NOT NULL DEFAULT 0,
|
||||
card_message_id BIGINT NOT NULL DEFAULT 0,
|
||||
card_is_photo BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
url TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
info TEXT NOT NULL DEFAULT '',
|
||||
lang TEXT NOT NULL DEFAULT 'en',
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX requests_user_idx ON requests (user_id, created_at);
|
||||
|
||||
-- A job is one unit of work for a worker.
|
||||
CREATE TABLE jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL DEFAULT 'download',
|
||||
url TEXT NOT NULL,
|
||||
extractor TEXT NOT NULL DEFAULT '',
|
||||
video_id TEXT NOT NULL DEFAULT '',
|
||||
profile TEXT NOT NULL,
|
||||
cache_key TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL,
|
||||
lane TEXT NOT NULL DEFAULT 'free',
|
||||
priority INTEGER NOT NULL DEFAULT 0,
|
||||
required_tags TEXT NOT NULL DEFAULT '',
|
||||
max_size BIGINT NOT NULL DEFAULT 0,
|
||||
max_duration BIGINT NOT NULL DEFAULT 0,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
max_attempts INTEGER NOT NULL DEFAULT 2,
|
||||
worker_id TEXT NOT NULL DEFAULT '',
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
cancel_requested BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
stage TEXT NOT NULL DEFAULT '',
|
||||
progress_bytes BIGINT NOT NULL DEFAULT 0,
|
||||
total_bytes BIGINT NOT NULL DEFAULT 0,
|
||||
error_code TEXT NOT NULL DEFAULT '',
|
||||
error_detail TEXT NOT NULL DEFAULT '',
|
||||
storage_key TEXT NOT NULL DEFAULT '',
|
||||
file_ext TEXT NOT NULL DEFAULT '',
|
||||
file_size BIGINT NOT NULL DEFAULT 0,
|
||||
duration BIGINT NOT NULL DEFAULT 0,
|
||||
width INTEGER NOT NULL DEFAULT 0,
|
||||
height INTEGER NOT NULL DEFAULT 0,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
uploader TEXT NOT NULL DEFAULT '',
|
||||
created_at BIGINT NOT NULL,
|
||||
queued_at BIGINT NOT NULL,
|
||||
started_at BIGINT NOT NULL DEFAULT 0,
|
||||
finished_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX jobs_queue_idx ON jobs (status, lane, priority, queued_at);
|
||||
CREATE INDEX jobs_lease_idx ON jobs (status, lease_expires_at);
|
||||
|
||||
-- A delivery is one requester waiting for the result of a job.
|
||||
CREATE TABLE deliveries (
|
||||
id TEXT PRIMARY KEY,
|
||||
job_id TEXT NOT NULL REFERENCES jobs (id),
|
||||
request_id TEXT NOT NULL DEFAULT '',
|
||||
user_id BIGINT NOT NULL,
|
||||
chat_id BIGINT NOT NULL,
|
||||
chat_type TEXT NOT NULL DEFAULT 'private',
|
||||
reply_to_message_id BIGINT NOT NULL DEFAULT 0,
|
||||
status_message_id BIGINT NOT NULL DEFAULT 0,
|
||||
status_is_photo BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
lang TEXT NOT NULL DEFAULT 'en',
|
||||
status TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
error_code TEXT NOT NULL DEFAULT '',
|
||||
tg_file_id TEXT NOT NULL DEFAULT '',
|
||||
tg_message_id BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX deliveries_job_idx ON deliveries (job_id);
|
||||
CREATE INDEX deliveries_user_idx ON deliveries (user_id, status);
|
||||
CREATE INDEX deliveries_status_idx ON deliveries (status, updated_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE deliveries;
|
||||
DROP TABLE jobs;
|
||||
DROP TABLE requests;
|
||||
DROP TABLE users;
|
||||
@@ -0,0 +1,132 @@
|
||||
package db
|
||||
|
||||
// Request statuses.
|
||||
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
|
||||
)
|
||||
|
||||
// Job statuses.
|
||||
const (
|
||||
JobQueued = "queued"
|
||||
JobRunning = "running"
|
||||
JobDelivering = "delivering" // file is stored, the core is sending it
|
||||
JobDone = "done"
|
||||
JobFailed = "failed"
|
||||
JobCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// Delivery statuses.
|
||||
const (
|
||||
DeliveryPending = "pending"
|
||||
DeliverySending = "sending"
|
||||
DeliverySent = "sent"
|
||||
DeliveryFailed = "failed"
|
||||
DeliveryCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// Queue lanes.
|
||||
const (
|
||||
LanePaid = "paid"
|
||||
LaneFree = "free"
|
||||
)
|
||||
|
||||
// Job kinds.
|
||||
const (
|
||||
KindDownload = "download"
|
||||
)
|
||||
|
||||
// User is a Telegram user known to the bot.
|
||||
type User struct {
|
||||
ID int64
|
||||
Username string
|
||||
FirstName string
|
||||
Lang string // detected from Telegram
|
||||
LangOverride string // chosen with /language
|
||||
Banned bool
|
||||
CreatedAt int64
|
||||
LastSeenAt int64
|
||||
}
|
||||
|
||||
// Request is one link sent by a user.
|
||||
type Request struct {
|
||||
ID string
|
||||
UserID int64
|
||||
ChatID int64
|
||||
ChatType string
|
||||
SourceMessageID int64
|
||||
CardMessageID int64
|
||||
CardIsPhoto bool
|
||||
URL string
|
||||
Status string
|
||||
Info string // JSON, see service.CardInfo
|
||||
Lang string
|
||||
CreatedAt int64
|
||||
UpdatedAt int64
|
||||
}
|
||||
|
||||
// Job is one unit of work for a worker.
|
||||
type Job struct {
|
||||
ID string
|
||||
Kind string
|
||||
URL string
|
||||
Extractor string
|
||||
VideoID string
|
||||
Profile string
|
||||
CacheKey string
|
||||
Status string
|
||||
Lane string
|
||||
Priority int
|
||||
RequiredTags string
|
||||
MaxSize int64
|
||||
MaxDuration int64 // seconds
|
||||
Attempts int
|
||||
MaxAttempts int
|
||||
WorkerID string
|
||||
LeaseExpiresAt int64
|
||||
CancelRequested bool
|
||||
Stage string
|
||||
ProgressBytes int64
|
||||
TotalBytes int64
|
||||
ErrorCode string
|
||||
ErrorDetail string
|
||||
StorageKey string
|
||||
FileExt string
|
||||
FileSize int64
|
||||
Duration int64 // seconds
|
||||
Width int
|
||||
Height int
|
||||
Title string
|
||||
Uploader string
|
||||
CreatedAt int64
|
||||
QueuedAt int64
|
||||
StartedAt int64
|
||||
FinishedAt int64
|
||||
}
|
||||
|
||||
// Active reports whether the job still needs a worker or the core.
|
||||
func (j *Job) Active() bool {
|
||||
return j.Status == JobQueued || j.Status == JobRunning || j.Status == JobDelivering
|
||||
}
|
||||
|
||||
// Delivery is one requester waiting for a job.
|
||||
type Delivery struct {
|
||||
ID string
|
||||
JobID string
|
||||
RequestID string
|
||||
UserID int64
|
||||
ChatID int64
|
||||
ChatType string
|
||||
ReplyToMessageID int64
|
||||
StatusMessageID int64
|
||||
StatusIsPhoto bool
|
||||
Lang string
|
||||
Status string
|
||||
Attempts int
|
||||
ErrorCode string
|
||||
TgFileID string
|
||||
TgMessageID int64
|
||||
CreatedAt int64
|
||||
UpdatedAt int64
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// openPostgres is replaced by the real implementation in Phase 4. Keeping
|
||||
// the entry point here means the driver switch in Open never changes.
|
||||
func openPostgres(_ context.Context, _ string) (*DB, error) {
|
||||
return nil, errors.New("db: the postgres backend is not built into this version yet")
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
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`
|
||||
|
||||
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)
|
||||
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)
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package db
|
||||
|
||||
import "context"
|
||||
|
||||
const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at`
|
||||
|
||||
func scanUser(sc interface{ Scan(...any) error }) (*User, error) {
|
||||
var u User
|
||||
err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt)
|
||||
if err != nil {
|
||||
return nil, notFound(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// UpsertUser records a sighting of a Telegram user and returns the stored
|
||||
// row. The detected language follows Telegram; an override is kept.
|
||||
func (s *Store) UpsertUser(ctx context.Context, id int64, username, firstName, lang string) (*User, error) {
|
||||
now := NowMilli()
|
||||
_, err := s.exec(ctx, `
|
||||
INSERT INTO users (id, username, first_name, lang, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
username = excluded.username,
|
||||
first_name = excluded.first_name,
|
||||
lang = CASE WHEN excluded.lang <> '' THEN excluded.lang ELSE users.lang END,
|
||||
last_seen_at = excluded.last_seen_at`,
|
||||
id, username, firstName, lang, now, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetUser(ctx, id)
|
||||
}
|
||||
|
||||
// GetUser loads a user by Telegram ID.
|
||||
func (s *Store) GetUser(ctx context.Context, id int64) (*User, error) {
|
||||
return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE id = ?`, id))
|
||||
}
|
||||
Reference in New Issue
Block a user