Files
Media-download-telegram-bot/internal/db/db.go
T
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

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

205 lines
5.3 KiB
Go

// 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 the form the database expects. Code
// outside this package that runs its own SQL, mostly tests, uses it to stay
// portable.
func (d *DB) Rebind(query string) string { return (&Store{db: d}).rebind(query) }
// 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
}