Files
shared/backend/postgres/postgres.go
T

255 lines
7.4 KiB
Go

// Package postgres centralizes PostgreSQL pool creation and the small pieces
// of error/transaction handling that are repeated by the Go services.
package postgres
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/config"
)
// Config controls a shared pgx connection pool. URL is normally read from
// DATABASE_URL with FromEnv.
type Config struct {
URL string
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
HealthCheckPeriod time.Duration
ConnectTimeout time.Duration
}
// StartupRetryOptions controls retries while a service is waiting for
// PostgreSQL to become reachable during startup.
type StartupRetryOptions struct {
Interval time.Duration
MaxAttempts int64
}
const (
defaultStartupRetryInterval = 5 * time.Second
defaultStartupRetryAttempts = 0 // 0 = retry indefinitely
minimumStartupRetryInterval = 250 * time.Millisecond
)
// StartupRetryOptionsFromEnv loads the common startup retry policy. The
// database has to be reachable before settings stored in it can be read, so
// these options intentionally come from the environment.
func StartupRetryOptionsFromEnv() StartupRetryOptions {
intervalMs := config.Int("DB_INIT_RETRY_INTERVAL_MS", int(defaultStartupRetryInterval/time.Millisecond))
if intervalMs < int(minimumStartupRetryInterval/time.Millisecond) {
intervalMs = int(minimumStartupRetryInterval / time.Millisecond)
}
maxAttempts := int64(config.Int("DB_INIT_RETRY_MAX_ATTEMPTS", defaultStartupRetryAttempts))
if maxAttempts < 0 {
maxAttempts = defaultStartupRetryAttempts
}
return StartupRetryOptions{
Interval: time.Duration(intervalMs) * time.Millisecond,
MaxAttempts: maxAttempts,
}
}
// RetryStartup reruns fn until it succeeds, the configured attempt limit is
// reached, or ctx is canceled.
func RetryStartup(ctx context.Context, fn func() error) error {
return RetryStartupWithOptions(ctx, StartupRetryOptionsFromEnv(), fn)
}
// RetryStartupWithOptions is the configurable form of RetryStartup, useful
// when a caller has already loaded the startup options.
func RetryStartupWithOptions(ctx context.Context, options StartupRetryOptions, fn func() error) error {
if fn == nil {
return errors.New("startup retry callback is nil")
}
if options.Interval < minimumStartupRetryInterval {
options.Interval = minimumStartupRetryInterval
}
if options.MaxAttempts < 0 {
options.MaxAttempts = defaultStartupRetryAttempts
}
var lastErr error
for attempt := int64(1); ; attempt++ {
if err := ctx.Err(); err != nil {
return err
}
if err := fn(); err == nil {
return nil
} else {
lastErr = err
}
if options.MaxAttempts > 0 && attempt >= options.MaxAttempts {
return lastErr
}
log.Printf("[postgres] startup attempt %d failed: %v; retrying in %s", attempt, lastErr, options.Interval)
timer := time.NewTimer(options.Interval)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
case <-timer.C:
}
}
}
// DefaultConfig returns sensible defaults for a small self-hosted service.
func DefaultConfig(url string) Config {
return Config{
URL: strings.TrimSpace(url),
MaxConns: 20,
MinConns: 0,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
HealthCheckPeriod: 30 * time.Second,
ConnectTimeout: 10 * time.Second,
}
}
// FromEnv loads DATABASE_URL and optional pool settings. Duration values use
// Go duration syntax, for example 30s or 1h. Invalid optional values fall back
// to defaults; the URL is the only required setting.
func FromEnv() (Config, error) {
url, err := config.Required("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg := DefaultConfig(url)
cfg.MaxConns = int32(config.Int("DATABASE_MAX_CONNS", int(cfg.MaxConns)))
cfg.MinConns = int32(config.Int("DATABASE_MIN_CONNS", int(cfg.MinConns)))
cfg.MaxConnLifetime = config.Duration("DATABASE_MAX_CONN_LIFETIME", cfg.MaxConnLifetime)
cfg.MaxConnIdleTime = config.Duration("DATABASE_MAX_CONN_IDLE_TIME", cfg.MaxConnIdleTime)
cfg.HealthCheckPeriod = config.Duration("DATABASE_HEALTH_CHECK_PERIOD", cfg.HealthCheckPeriod)
cfg.ConnectTimeout = config.Duration("DATABASE_CONNECT_TIMEOUT", cfg.ConnectTimeout)
if cfg.MaxConns < 1 {
return Config{}, fmt.Errorf("DATABASE_MAX_CONNS must be at least 1")
}
if cfg.MinConns < 0 || cfg.MinConns > cfg.MaxConns {
return Config{}, fmt.Errorf("DATABASE_MIN_CONNS must be between 0 and DATABASE_MAX_CONNS")
}
if cfg.ConnectTimeout <= 0 {
return Config{}, fmt.Errorf("DATABASE_CONNECT_TIMEOUT must be greater than 0")
}
return cfg, nil
}
// Open creates and verifies a PostgreSQL pool. A failed ping closes the pool
// before returning so callers do not leak connections during startup errors.
func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
if strings.TrimSpace(cfg.URL) == "" {
return nil, errors.New("postgres URL is required")
}
poolConfig, err := pgxpool.ParseConfig(cfg.URL)
if err != nil {
return nil, fmt.Errorf("parse postgres URL: %w", err)
}
if cfg.MaxConns > 0 {
poolConfig.MaxConns = cfg.MaxConns
}
if cfg.MinConns >= 0 {
poolConfig.MinConns = cfg.MinConns
}
if cfg.MaxConnLifetime > 0 {
poolConfig.MaxConnLifetime = cfg.MaxConnLifetime
}
if cfg.MaxConnIdleTime > 0 {
poolConfig.MaxConnIdleTime = cfg.MaxConnIdleTime
}
if cfg.HealthCheckPeriod > 0 {
poolConfig.HealthCheckPeriod = cfg.HealthCheckPeriod
}
if cfg.ConnectTimeout > 0 {
poolConfig.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create postgres pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping postgres: %w", err)
}
return pool, nil
}
// OpenWithRetry opens and verifies a PostgreSQL pool using the common startup
// retry policy.
func OpenWithRetry(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
var pool *pgxpool.Pool
err := RetryStartup(ctx, func() error {
if pool != nil {
pool.Close()
pool = nil
}
var err error
pool, err = Open(ctx, cfg)
return err
})
if err != nil {
return nil, err
}
return pool, nil
}
// WithTx runs fn in a transaction and rolls back on all error paths.
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
if pool == nil {
return errors.New("postgres pool is nil")
}
if fn == nil {
return errors.New("postgres transaction callback is nil")
}
tx, err := pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin postgres transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit postgres transaction: %w", err)
}
return nil
}
// IsNoRows reports whether err is pgx's not-found sentinel.
func IsNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
// IsUniqueViolation reports a PostgreSQL unique/exclusion constraint error.
func IsUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "23505" || pgErr.Code == "23P01")
}
// IsForeignKeyViolation reports a PostgreSQL foreign-key constraint error.
func IsForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}