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

73 lines
2.2 KiB
Go

package db
import (
"context"
"database/sql"
"errors"
"fmt"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
// openPostgres connects with pgx. The DSN is a connection URL such as
// postgres://user:pass@host:5432/dbname?sslmode=require.
func openPostgres(ctx context.Context, dsn string) (*DB, error) {
if dsn == "" {
return nil, errors.New("db: postgres needs a connection URL")
}
sqldb, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
sqldb.SetMaxOpenConns(20)
sqldb.SetMaxIdleConns(10)
if err := sqldb.PingContext(ctx); err != nil {
sqldb.Close()
// The driver's error can quote the DSN, which holds the password.
return nil, fmt.Errorf("db: cannot connect to postgres: %s", redactDSN(err.Error(), dsn))
}
return &DB{SQL: sqldb, Dialect: Postgres}, nil
}
// redactDSN removes the connection string from an error message.
func redactDSN(msg, dsn string) string {
out := msg
for i := 0; i+len(dsn) <= len(out); {
if out[i:i+len(dsn)] == dsn {
out = out[:i] + "[dsn]" + out[i+len(dsn):]
continue
}
i++
}
return out
}
// LockUser serializes transactions that check and then change a user's
// rows, such as "count active jobs, then insert one". SQLite does this by
// itself, because every transaction holds the write lock. Postgres runs
// transactions side by side, so two fast requests could both pass the
// check. The advisory lock is held until the transaction ends.
func (s *Store) LockUser(ctx context.Context, userID int64) error {
if s.db.Dialect != Postgres || !s.inTx {
return nil
}
_, err := s.q.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, userID)
return err
}
// LockJob takes a row lock on a job until the transaction ends, so that
// its status cannot change between reading it and acting on it. Without
// it Postgres lets, for example, a worker claim a job in the moment a
// requester cancels it. SQLite needs nothing: its transactions are serial.
func (s *Store) LockJob(ctx context.Context, jobID string) error {
if s.db.Dialect != Postgres || !s.inTx {
return nil
}
var id string
err := s.q.QueryRowContext(ctx, `SELECT id FROM jobs WHERE id = $1 FOR UPDATE`, jobID).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}