Files
galaxy-game/lobby/internal/adapters/postgres/applicationstore/store.go
T
2026-04-26 20:34:39 +02:00

311 lines
9.6 KiB
Go

// Package applicationstore implements the PostgreSQL-backed adapter for
// `ports.ApplicationStore`.
//
// PG_PLAN.md §6A migrates Game Lobby Service away from Redis-backed durable
// application records; see `galaxy/lobby/docs/postgres-migration.md` for
// the full decision record.
package applicationstore
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"galaxy/lobby/internal/adapters/postgres/internal/sqlx"
pgtable "galaxy/lobby/internal/adapters/postgres/jet/lobby/table"
"galaxy/lobby/internal/domain/application"
"galaxy/lobby/internal/domain/common"
"galaxy/lobby/internal/ports"
pg "github.com/go-jet/jet/v2/postgres"
)
// Config configures one PostgreSQL-backed application store instance.
type Config struct {
// DB stores the connection pool the store uses for every query.
DB *sql.DB
// OperationTimeout bounds one round trip.
OperationTimeout time.Duration
}
// Store persists Game Lobby application records in PostgreSQL.
type Store struct {
db *sql.DB
operationTimeout time.Duration
}
// New constructs one PostgreSQL-backed application store from cfg.
func New(cfg Config) (*Store, error) {
if cfg.DB == nil {
return nil, errors.New("new postgres application store: db must not be nil")
}
if cfg.OperationTimeout <= 0 {
return nil, errors.New("new postgres application store: operation timeout must be positive")
}
return &Store{
db: cfg.DB,
operationTimeout: cfg.OperationTimeout,
}, nil
}
// applicationSelectColumns is the canonical SELECT list for the applications
// table, matching scanApplication's column order.
var applicationSelectColumns = pg.ColumnList{
pgtable.Applications.ApplicationID,
pgtable.Applications.GameID,
pgtable.Applications.ApplicantUserID,
pgtable.Applications.RaceName,
pgtable.Applications.Status,
pgtable.Applications.CreatedAt,
pgtable.Applications.DecidedAt,
}
// Save persists a new submitted application record. The single-active
// constraint is enforced by the partial unique index
// `applications_active_per_user_game_uidx`.
func (store *Store) Save(ctx context.Context, record application.Application) error {
if store == nil || store.db == nil {
return errors.New("save application: nil store")
}
if err := record.Validate(); err != nil {
return fmt.Errorf("save application: %w", err)
}
if record.Status != application.StatusSubmitted {
return fmt.Errorf(
"save application: status must be %q, got %q",
application.StatusSubmitted, record.Status,
)
}
operationCtx, cancel, err := sqlx.WithTimeout(ctx, "save application", store.operationTimeout)
if err != nil {
return err
}
defer cancel()
stmt := pgtable.Applications.INSERT(
pgtable.Applications.ApplicationID,
pgtable.Applications.GameID,
pgtable.Applications.ApplicantUserID,
pgtable.Applications.RaceName,
pgtable.Applications.Status,
pgtable.Applications.CreatedAt,
pgtable.Applications.DecidedAt,
).VALUES(
record.ApplicationID.String(),
record.GameID.String(),
record.ApplicantUserID,
record.RaceName,
string(record.Status),
record.CreatedAt.UTC(),
sqlx.NullableTimePtr(record.DecidedAt),
)
query, args := stmt.Sql()
if _, err := store.db.ExecContext(operationCtx, query, args...); err != nil {
if sqlx.IsUniqueViolation(err) {
return fmt.Errorf("save application: %w", application.ErrConflict)
}
return fmt.Errorf("save application: %w", err)
}
return nil
}
// Get returns the record identified by applicationID. It returns
// application.ErrNotFound when no record exists.
func (store *Store) Get(ctx context.Context, applicationID common.ApplicationID) (application.Application, error) {
if store == nil || store.db == nil {
return application.Application{}, errors.New("get application: nil store")
}
if err := applicationID.Validate(); err != nil {
return application.Application{}, fmt.Errorf("get application: %w", err)
}
operationCtx, cancel, err := sqlx.WithTimeout(ctx, "get application", store.operationTimeout)
if err != nil {
return application.Application{}, err
}
defer cancel()
stmt := pg.SELECT(applicationSelectColumns).
FROM(pgtable.Applications).
WHERE(pgtable.Applications.ApplicationID.EQ(pg.String(applicationID.String())))
query, args := stmt.Sql()
row := store.db.QueryRowContext(operationCtx, query, args...)
record, err := scanApplication(row)
if sqlx.IsNoRows(err) {
return application.Application{}, application.ErrNotFound
}
if err != nil {
return application.Application{}, fmt.Errorf("get application: %w", err)
}
return record, nil
}
// GetByGame returns every application attached to gameID. Sorted by
// created_at ASC then application_id ASC.
func (store *Store) GetByGame(ctx context.Context, gameID common.GameID) ([]application.Application, error) {
if store == nil || store.db == nil {
return nil, errors.New("get applications by game: nil store")
}
if err := gameID.Validate(); err != nil {
return nil, fmt.Errorf("get applications by game: %w", err)
}
stmt := pg.SELECT(applicationSelectColumns).
FROM(pgtable.Applications).
WHERE(pgtable.Applications.GameID.EQ(pg.String(gameID.String()))).
ORDER_BY(pgtable.Applications.CreatedAt.ASC(), pgtable.Applications.ApplicationID.ASC())
return store.queryList(ctx, "get applications by game", stmt)
}
// GetByUser returns every application submitted by applicantUserID.
func (store *Store) GetByUser(ctx context.Context, applicantUserID string) ([]application.Application, error) {
if store == nil || store.db == nil {
return nil, errors.New("get applications by user: nil store")
}
trimmed := strings.TrimSpace(applicantUserID)
if trimmed == "" {
return nil, fmt.Errorf("get applications by user: applicant user id must not be empty")
}
stmt := pg.SELECT(applicationSelectColumns).
FROM(pgtable.Applications).
WHERE(pgtable.Applications.ApplicantUserID.EQ(pg.String(trimmed))).
ORDER_BY(pgtable.Applications.CreatedAt.ASC(), pgtable.Applications.ApplicationID.ASC())
return store.queryList(ctx, "get applications by user", stmt)
}
func (store *Store) queryList(ctx context.Context, operation string, stmt pg.SelectStatement) ([]application.Application, error) {
operationCtx, cancel, err := sqlx.WithTimeout(ctx, operation, store.operationTimeout)
if err != nil {
return nil, err
}
defer cancel()
query, args := stmt.Sql()
rows, err := store.db.QueryContext(operationCtx, query, args...)
if err != nil {
return nil, fmt.Errorf("%s: %w", operation, err)
}
defer rows.Close()
records := make([]application.Application, 0)
for rows.Next() {
record, err := scanApplication(rows)
if err != nil {
return nil, fmt.Errorf("%s: scan: %w", operation, err)
}
records = append(records, record)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("%s: %w", operation, err)
}
if len(records) == 0 {
return nil, nil
}
return records, nil
}
// UpdateStatus applies one status transition with compare-and-swap on the
// current status column.
func (store *Store) UpdateStatus(ctx context.Context, input ports.UpdateApplicationStatusInput) error {
if store == nil || store.db == nil {
return errors.New("update application status: nil store")
}
if err := input.Validate(); err != nil {
return fmt.Errorf("update application status: %w", err)
}
if err := application.Transition(input.ExpectedFrom, input.To); err != nil {
return err
}
operationCtx, cancel, err := sqlx.WithTimeout(ctx, "update application status", store.operationTimeout)
if err != nil {
return err
}
defer cancel()
at := input.At.UTC()
stmt := pgtable.Applications.UPDATE(pgtable.Applications.Status, pgtable.Applications.DecidedAt).
SET(string(input.To), at).
WHERE(pg.AND(
pgtable.Applications.ApplicationID.EQ(pg.String(input.ApplicationID.String())),
pgtable.Applications.Status.EQ(pg.String(string(input.ExpectedFrom))),
))
query, args := stmt.Sql()
result, err := store.db.ExecContext(operationCtx, query, args...)
if err != nil {
return fmt.Errorf("update application status: %w", err)
}
affected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("update application status: rows affected: %w", err)
}
if affected == 0 {
probe := pg.SELECT(pgtable.Applications.Status).
FROM(pgtable.Applications).
WHERE(pgtable.Applications.ApplicationID.EQ(pg.String(input.ApplicationID.String())))
probeQuery, probeArgs := probe.Sql()
var current string
row := store.db.QueryRowContext(operationCtx, probeQuery, probeArgs...)
if err := row.Scan(&current); err != nil {
if sqlx.IsNoRows(err) {
return application.ErrNotFound
}
return fmt.Errorf("update application status: probe: %w", err)
}
return fmt.Errorf("update application status: %w", application.ErrConflict)
}
return nil
}
type rowScanner interface {
Scan(dest ...any) error
}
func scanApplication(rs rowScanner) (application.Application, error) {
var (
applicationID string
gameID string
applicantUserID string
raceName string
status string
createdAt time.Time
decidedAt sql.NullTime
)
if err := rs.Scan(
&applicationID,
&gameID,
&applicantUserID,
&raceName,
&status,
&createdAt,
&decidedAt,
); err != nil {
return application.Application{}, err
}
return application.Application{
ApplicationID: common.ApplicationID(applicationID),
GameID: common.GameID(gameID),
ApplicantUserID: applicantUserID,
RaceName: raceName,
Status: application.Status(status),
CreatedAt: createdAt.UTC(),
DecidedAt: sqlx.TimePtrFromNullable(decidedAt),
}, nil
}
// Ensure Store satisfies the ports.ApplicationStore interface at compile
// time.
var _ ports.ApplicationStore = (*Store)(nil)