Files
2026-11-06 17:30:30 +03:00

166 lines
4.3 KiB
Go

package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type Store struct {
pool *pgxpool.Pool
queries *sqlcgen.Queries
queryTimeout time.Duration
idempotencyTTL time.Duration
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
pipeline *PipelineRepository
}
type options struct {
queryTracer pgx.QueryTracer
}
// Option customizes the PostgreSQL store without leaking telemetry into the
// storage package's public API.
type Option func(*options)
// WithQueryTracer installs a pgx tracer (nil means no tracing).
func WithQueryTracer(tracer pgx.QueryTracer) Option {
return func(o *options) { o.queryTracer = tracer }
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration, opts ...Option) (*Store, error) {
options := options{}
for _, opt := range opts {
opt(&options)
}
cfg, err := normalize(cfg)
if err != nil {
return nil, fmt.Errorf("normalize database config: %w", err)
}
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
if err != nil {
return nil, fmt.Errorf("parse database dsn: %w", err)
}
poolCfg.MaxConns = cfg.MaxConns
poolCfg.MinConns = cfg.MinConns
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
if options.queryTracer != nil {
poolCfg.ConnConfig.Tracer = options.queryTracer
}
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
store := &Store{
pool: pool,
queries: sqlcgen.New(pool),
queryTimeout: cfg.QueryTimeout,
idempotencyTTL: idempotencyTTL,
}
store.users = &UserRepository{store: store}
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
store.sessions = &SessionRepository{store: store}
store.pipeline = &PipelineRepository{store: store}
return store, nil
}
func (s *Store) Users() *UserRepository { return s.users }
func (s *Store) Chats() *ChatRepository { return s.chats }
func (s *Store) Messages() *MessageRepository { return s.messages }
func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err := s.pool.Ping(pingCtx); err != nil {
return fmt.Errorf("ping database: %w", err)
}
return nil
}
// PoolStats exposes a point-in-time pgxpool snapshot for telemetry callbacks.
func (s *Store) PoolStats() *pgxpool.Stat { return s.pool.Stat() }
func (s *Store) Close() { s.pool.Close() }
// sweepLockKey is a process-independent constant: every replica contends for the
// same PostgreSQL session lock, so only one sweeper runs at a time.
const sweepLockKey int64 = 0x4c414234 // "LAB4"
// AcquireSweepLock holds a session-level advisory lock on a dedicated
// connection. The returned release function must be called on that same
// connection before it is returned to the pool.
func (s *Store) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return nil, false, fmt.Errorf("acquire sweep connection: %w", err)
}
var acquired bool
if err := conn.QueryRow(ctx, "SELECT pg_try_advisory_lock($1)", sweepLockKey).Scan(&acquired); err != nil {
conn.Release()
return nil, false, fmt.Errorf("acquire sweep lock: %w", err)
}
if !acquired {
conn.Release()
return nil, false, nil
}
release := func() {
unlockCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", sweepLockKey)
conn.Release()
}
return release, true, nil
}
func (s *Store) timeout(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return context.WithCancel(ctx)
}
return context.WithTimeout(ctx, s.queryTimeout)
}