feat: use postgres
This commit is contained in:
@@ -0,0 +1,310 @@
|
||||
// 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(¤t); 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)
|
||||
@@ -0,0 +1,194 @@
|
||||
package applicationstore_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"galaxy/lobby/internal/adapters/postgres/applicationstore"
|
||||
"galaxy/lobby/internal/adapters/postgres/gamestore"
|
||||
"galaxy/lobby/internal/adapters/postgres/internal/pgtest"
|
||||
"galaxy/lobby/internal/domain/application"
|
||||
"galaxy/lobby/internal/domain/common"
|
||||
"galaxy/lobby/internal/domain/game"
|
||||
"galaxy/lobby/internal/ports"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { pgtest.RunMain(m) }
|
||||
|
||||
func newStores(t *testing.T) (*gamestore.Store, *applicationstore.Store) {
|
||||
t.Helper()
|
||||
pgtest.TruncateAll(t)
|
||||
gs, err := gamestore.New(gamestore.Config{
|
||||
DB: pgtest.Ensure(t).Pool(), OperationTimeout: pgtest.OperationTimeout,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
as, err := applicationstore.New(applicationstore.Config{
|
||||
DB: pgtest.Ensure(t).Pool(), OperationTimeout: pgtest.OperationTimeout,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return gs, as
|
||||
}
|
||||
|
||||
func seedGame(t *testing.T, gs *gamestore.Store, id string) game.Game {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 4, 23, 12, 0, 0, 0, time.UTC)
|
||||
g, err := game.New(game.NewGameInput{
|
||||
GameID: common.GameID(id),
|
||||
GameName: "Game " + id,
|
||||
GameType: game.GameTypePublic,
|
||||
MinPlayers: 2,
|
||||
MaxPlayers: 8,
|
||||
StartGapHours: 12,
|
||||
StartGapPlayers: 2,
|
||||
EnrollmentEndsAt: now.Add(7 * 24 * time.Hour),
|
||||
TurnSchedule: "0 18 * * *",
|
||||
TargetEngineVersion: "v1.0.0",
|
||||
Now: now,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, gs.Save(context.Background(), g))
|
||||
return g
|
||||
}
|
||||
|
||||
func newApplication(t *testing.T, id, gameID, userID string) application.Application {
|
||||
t.Helper()
|
||||
a, err := application.New(application.NewApplicationInput{
|
||||
ApplicationID: common.ApplicationID(id),
|
||||
GameID: common.GameID(gameID),
|
||||
ApplicantUserID: userID,
|
||||
RaceName: "Pilot " + id,
|
||||
Now: time.Date(2026, 4, 23, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return a
|
||||
}
|
||||
|
||||
func TestSaveAndGet(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
|
||||
rec := newApplication(t, "application-001", "game-001", "user-a")
|
||||
require.NoError(t, as.Save(ctx, rec))
|
||||
|
||||
got, err := as.Get(ctx, rec.ApplicationID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, rec.ApplicationID, got.ApplicationID)
|
||||
assert.Equal(t, application.StatusSubmitted, got.Status)
|
||||
assert.Equal(t, "user-a", got.ApplicantUserID)
|
||||
assert.Nil(t, got.DecidedAt)
|
||||
}
|
||||
|
||||
func TestSaveRejectsNonSubmittedRecord(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
|
||||
rec := newApplication(t, "application-001", "game-001", "user-a")
|
||||
rec.Status = application.StatusApproved
|
||||
require.Error(t, as.Save(ctx, rec))
|
||||
}
|
||||
|
||||
func TestSavePartialUniqueRejectsSecondActiveForSameUserGame(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
|
||||
a1 := newApplication(t, "application-001", "game-001", "user-a")
|
||||
require.NoError(t, as.Save(ctx, a1))
|
||||
|
||||
// second submission by the same user against the same game must fail.
|
||||
a2 := newApplication(t, "application-002", "game-001", "user-a")
|
||||
err := as.Save(ctx, a2)
|
||||
require.ErrorIs(t, err, application.ErrConflict)
|
||||
}
|
||||
|
||||
func TestSavePartialUniqueAllowsResubmitAfterRejection(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
|
||||
a1 := newApplication(t, "application-001", "game-001", "user-a")
|
||||
require.NoError(t, as.Save(ctx, a1))
|
||||
|
||||
require.NoError(t, as.UpdateStatus(ctx, ports.UpdateApplicationStatusInput{
|
||||
ApplicationID: a1.ApplicationID,
|
||||
ExpectedFrom: application.StatusSubmitted,
|
||||
To: application.StatusRejected,
|
||||
At: a1.CreatedAt.Add(time.Minute),
|
||||
}))
|
||||
|
||||
// after rejection a new submission for the same (user, game) is allowed.
|
||||
a2 := newApplication(t, "application-002", "game-001", "user-a")
|
||||
require.NoError(t, as.Save(ctx, a2))
|
||||
}
|
||||
|
||||
func TestUpdateStatusReturnsConflictOnExpectedFromMismatch(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
|
||||
rec := newApplication(t, "application-001", "game-001", "user-a")
|
||||
require.NoError(t, as.Save(ctx, rec))
|
||||
|
||||
// First, transition the row to approved.
|
||||
require.NoError(t, as.UpdateStatus(ctx, ports.UpdateApplicationStatusInput{
|
||||
ApplicationID: rec.ApplicationID,
|
||||
ExpectedFrom: application.StatusSubmitted,
|
||||
To: application.StatusApproved,
|
||||
At: rec.CreatedAt.Add(time.Minute),
|
||||
}))
|
||||
|
||||
// Second attempt claims status is still submitted: (submitted, rejected)
|
||||
// is a valid domain transition, but the row is already approved, so the
|
||||
// adapter must surface ErrConflict on the row-level mismatch.
|
||||
err := as.UpdateStatus(ctx, ports.UpdateApplicationStatusInput{
|
||||
ApplicationID: rec.ApplicationID,
|
||||
ExpectedFrom: application.StatusSubmitted,
|
||||
To: application.StatusRejected,
|
||||
At: rec.CreatedAt.Add(2 * time.Minute),
|
||||
})
|
||||
require.ErrorIs(t, err, application.ErrConflict)
|
||||
}
|
||||
|
||||
func TestUpdateStatusReturnsNotFoundForMissing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, as := newStores(t)
|
||||
err := as.UpdateStatus(ctx, ports.UpdateApplicationStatusInput{
|
||||
ApplicationID: common.ApplicationID("application-missing"),
|
||||
ExpectedFrom: application.StatusSubmitted,
|
||||
To: application.StatusApproved,
|
||||
At: time.Now().UTC(),
|
||||
})
|
||||
require.ErrorIs(t, err, application.ErrNotFound)
|
||||
}
|
||||
|
||||
func TestGetByGameAndGetByUser(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gs, as := newStores(t)
|
||||
seedGame(t, gs, "game-001")
|
||||
seedGame(t, gs, "game-002")
|
||||
|
||||
require.NoError(t, as.Save(ctx, newApplication(t, "application-001", "game-001", "user-a")))
|
||||
require.NoError(t, as.Save(ctx, newApplication(t, "application-002", "game-001", "user-b")))
|
||||
require.NoError(t, as.Save(ctx, newApplication(t, "application-003", "game-002", "user-a")))
|
||||
|
||||
g1, err := as.GetByGame(ctx, common.GameID("game-001"))
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, g1, 2)
|
||||
|
||||
userA, err := as.GetByUser(ctx, "user-a")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, userA, 2)
|
||||
}
|
||||
|
||||
func TestGetMissingReturnsNotFound(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, as := newStores(t)
|
||||
_, err := as.Get(ctx, common.ApplicationID("application-missing"))
|
||||
require.ErrorIs(t, err, application.ErrNotFound)
|
||||
}
|
||||
Reference in New Issue
Block a user