postgres

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package postgres contains PostgreSQL adapters for the generic lobby domain. Importing it has no connection or migration side effects.

Index

Constants

This section is empty.

Variables

View Source
var SchemaTables = []string{
	"lobby_players",
	"lobby_sessions",
	"lobby_rooms",
	"lobby_teams",
	"lobby_memberships",
	"lobby_leases",
	"lobby_start_roster",
	"lobby_create_requests",
	"lobby_watchers",
	"lobby_accounts",
}

SchemaTables is the complete generic-lobby schema, independent of game tables.

Functions

func BindOnce

func BindOnce[Result any](database *gorm.DB, constraint string, load func(*gorm.DB) (*Result, error), create func(*gorm.DB) (Result, error)) (Result, error)

BindOnce runs game-specific lookup and creation in one transaction. Load must return nil only when no game exists, and reject incomplete persisted bindings. Create must use the supplied transaction for all writes. Both callbacks must be free of external side effects. The database carries the request context.

A concurrent creation is replayed only for the named unique lobby-link constraint. Unrelated database errors are returned without retrying.

func Migrate

func Migrate(ctx context.Context, db *gorm.DB) error

Migrate brings the generic lobby schema to the latest version and may safely be called more than once, including concurrently. It does not open a connection.

Types

type AccountRecord added in v0.6.0

type AccountRecord struct {
	ID             string    `gorm:"column:id;type:uuid;primaryKey"`
	GoogleSubject  string    `gorm:"column:google_subject;not null"`
	DisplayName    string    `gorm:"column:display_name;not null"`
	DisplayNameKey string    `gorm:"column:display_name_key;not null"`
	CreatedAt      time.Time `gorm:"column:created_at;not null"`
	UpdatedAt      time.Time `gorm:"column:updated_at;not null"`
}

AccountRecord is migration 0012's account of a person who signed in. It holds Google's subject and the display name the person chose, whose case-folded key is unique, and nothing else of Google's.

func (AccountRecord) TableName added in v0.6.0

func (AccountRecord) TableName() string

type CreateRequestRecord

type CreateRequestRecord struct {
	PlayerID     string         `gorm:"column:player_id;type:uuid;primaryKey"`
	RequestID    string         `gorm:"column:request_id;type:uuid;primaryKey"`
	LobbyID      *string        `gorm:"column:lobby_id;type:uuid"`
	PayloadHash  []byte         `gorm:"column:payload_hash;type:bytea;not null"`
	ResponseJSON datatypes.JSON `gorm:"column:response_json;type:jsonb;not null"`
	CreatedAt    time.Time      `gorm:"column:created_at;not null"`
}

CreateRequestRecord retains the original representation used to answer an idempotent create retry. LobbyID, from migration 0004, names the lobby it created, so the request is deleted with that lobby; it is null only for requests that an older build stored.

func (CreateRequestRecord) TableName

func (CreateRequestRecord) TableName() string

type IdentityStore

type IdentityStore struct {
	// contains filtered or unexported fields
}

IdentityStore persists players, guests and those of accounts, their single v1 session, and accounts. It has no connection or migration side effects; callers own database setup.

func NewIdentityStore

func NewIdentityStore(db *gorm.DB) (*IdentityStore, error)

func (*IdentityStore) AccountByID added in v0.6.0

func (store *IdentityStore) AccountByID(ctx context.Context, id string) (*domain.Account, error)

func (*IdentityStore) AccountBySubject added in v0.6.0

func (store *IdentityStore) AccountBySubject(ctx context.Context, subject string) (*domain.Account, error)

func (*IdentityStore) CreateAccountSession added in v0.6.0

func (store *IdentityStore) CreateAccountSession(ctx context.Context, account domain.Account, subject string, create bool, player domain.Player, session domain.Session) error

func (*IdentityStore) CreateGuest

func (store *IdentityStore) CreateGuest(ctx context.Context, player domain.Player, session domain.Session) error

CreateGuest commits the player and its session together. The session unique constraint is still retained at the database layer for direct callers.

func (*IdentityStore) DeleteAccount added in v0.6.0

func (store *IdentityStore) DeleteAccount(ctx context.Context, accountID string) error

func (*IdentityStore) LookupByBearerHash

func (store *IdentityStore) LookupByBearerHash(ctx context.Context, hash domain.CredentialHash) (*domain.SessionVerification, error)

func (*IdentityStore) LookupByPlayer

func (store *IdentityStore) LookupByPlayer(ctx context.Context, playerID string) (*domain.SessionVerification, error)

func (*IdentityStore) RenameAccount added in v0.6.0

func (store *IdentityStore) RenameAccount(ctx context.Context, accountID, playerID, displayName string, updatedAt time.Time) error

type LeaseRecord

type LeaseRecord struct {
	LobbyID          string     `gorm:"column:lobby_id;type:uuid;primaryKey"`
	PlayerID         string     `gorm:"column:player_id;type:uuid;primaryKey"`
	Generation       int64      `gorm:"column:generation;primaryKey"`
	ClientInstanceID string     `gorm:"column:client_instance_id;type:uuid;primaryKey"`
	ExpiresAt        time.Time  `gorm:"column:expires_at;not null"`
	ReleasedAt       *time.Time `gorm:"column:released_at"`
}

LeaseRecord's composite identity keeps old generations available for grace calculation and audit after a membership is reactivated.

func (LeaseRecord) TableName

func (LeaseRecord) TableName() string

type MembershipRecord

type MembershipRecord struct {
	ID                string     `gorm:"column:id;type:uuid;primaryKey"`
	LobbyID           string     `gorm:"column:lobby_id;type:uuid;not null"`
	PlayerID          string     `gorm:"column:player_id;type:uuid;not null"`
	DisplayName       string     `gorm:"column:display_name;not null"`
	Generation        int64      `gorm:"column:generation;not null"`
	Active            bool       `gorm:"column:active;not null"`
	TeamID            *string    `gorm:"column:team_id;type:uuid"`
	Ready             bool       `gorm:"column:ready;not null"`
	JoinedAt          time.Time  `gorm:"column:joined_at;not null"`
	JoinSequence      int64      `gorm:"column:join_sequence;not null"`
	DisconnectedUntil *time.Time `gorm:"column:disconnected_until"`
	Kind              string     `gorm:"column:kind;not null;default:human"`
	SeatSettings      []byte     `gorm:"column:seat_settings;type:json"`
	SeatRequestID     *string    `gorm:"column:seat_request_id;type:uuid"`
	MemberSettings    []byte     `gorm:"column:member_settings;type:jsonb"`
	AccountID         *string    `gorm:"column:account_id;type:uuid"`
}

MembershipRecord.Kind and SeatSettings are migration 0005's: a seat that no person plays is kind "seat" with the game's settings, and a person is "human" with null settings. SeatRequestID is the request ID that added the seat, unique within its lobby, or null. All are written once, when the row is created. MemberSettings is migration 0010's: the person's own settings for the game, or null until they set some. AccountID is migration 0013's: the account of a person who had signed in when they joined, or null.

func (MembershipRecord) TableName

func (MembershipRecord) TableName() string

type MigrationSet

type MigrationSet struct {
	// HistoryTable records applied versions. Its name also keys the advisory
	// lock that serializes runs of this set and prefixes the set's errors.
	HistoryTable string
	// Files holds the migrations at its root, named NNNN_description.sql and
	// numbered from 0001 without gaps. An applied file must never change.
	Files fs.FS
	// Adopt lets the set take over a database created before versioning.
	// When the history is empty and every table migration 1 creates already
	// exists with at least the columns migration 1 gives it, migration 1 is
	// recorded as adopted instead of being run. When only some of those
	// tables exist, or one lacks a column, Apply fails instead of guessing.
	Adopt bool
}

MigrationSet is an ordered list of SQL migrations recorded in its own history table. The lobby has one set; a host game can version its own tables with another set without sharing history with the lobby.

func Migrations

func Migrations() MigrationSet

Migrations returns the versioned lobby schema, recorded in lobby_schema_migrations. Change the schema by adding the next numbered file to postgres/migrations; never edit an applied one.

func (MigrationSet) Apply

func (set MigrationSet) Apply(ctx context.Context, database *gorm.DB) error

Apply runs every pending migration in one READ COMMITTED transaction that holds an advisory lock, so a concurrent run waits, then reads the history the first run committed and finds nothing to do. A failure leaves the database unchanged. Migrations therefore cannot use statements PostgreSQL refuses inside a transaction, such as CREATE INDEX CONCURRENTLY.

Apply fails when an applied migration's file has changed. Versions newer than this build's files are left alone with a warning, so an older build can still start.

func (MigrationSet) Current

func (set MigrationSet) Current(ctx context.Context, database *gorm.DB) (bool, error)

Current reports whether database has every migration of the set applied: its history table exists and records the newest version of the set's files, or a newer one. It changes nothing and takes no lock. A host that is about to rely on the set's schema, such as one that drops an older copy of it elsewhere, checks it first.

type PlayerRecord

type PlayerRecord struct {
	ID          string    `gorm:"column:id;type:uuid;primaryKey"`
	DisplayName string    `gorm:"column:display_name;not null"`
	CreatedAt   time.Time `gorm:"column:created_at;not null"`
	AccountID   *string   `gorm:"column:account_id;type:uuid"`
}

PlayerRecord is the durable identity label used by lobby sessions and members. AccountID is migration 0012's: the account a signed-in player belongs to, null for a guest and once the account is deleted.

func (PlayerRecord) TableName

func (PlayerRecord) TableName() string

type RetentionStore

type RetentionStore struct {
	// contains filtered or unexported fields
}

RetentionStore deletes lobby data past its retention period. It touches only lobby tables.

func NewRetentionStore

func NewRetentionStore(db *gorm.DB) (*RetentionStore, error)

func (*RetentionStore) DeleteExpired

func (store *RetentionStore) DeleteExpired(ctx context.Context, cutoffs domain.RetentionCutoffs) (domain.RetentionResult, error)

DeleteExpired deletes create requests, then sessions, then lobbies, then the players that nothing references any more, so a player freed by an earlier step goes in the same pass. Each step is one transaction that locks and deletes at most cutoffs.BatchSize rows of its kind. The steps are independent: a step that fails is reported in the joined error, and the later steps still run, so a row that can't be deleted never blocks the rest.

type RoomRecord

type RoomRecord struct {
	ID               string    `gorm:"column:id;type:uuid;primaryKey"`
	GameKey          string    `gorm:"column:game_key;not null"`
	Name             string    `gorm:"column:name;not null"`
	JoinCode         string    `gorm:"column:join_code;not null"`
	Capacity         int       `gorm:"column:capacity;not null"`
	Phase            string    `gorm:"column:phase;not null"`
	Round            int64     `gorm:"column:round;not null;default:1"`
	Version          int64     `gorm:"column:version;not null"`
	HostPlayerID     *string   `gorm:"column:host_player_id;type:uuid"`
	CreatedAt        time.Time `gorm:"column:created_at;not null"`
	NextJoinSequence int64     `gorm:"column:next_join_sequence;not null"`
	GameSettings     []byte    `gorm:"column:game_settings;type:json"`
	LastConnectedAt  time.Time `gorm:"column:last_connected_at;not null"`
	RoundStartedAt   time.Time `gorm:"column:round_started_at;not null"`
	BoundRound       int64     `gorm:"column:bound_round;not null;default:0"`
}

RoomRecord.GameSettings is written once at creation into the json column that migration 0003 adds; rooms created before it hold an empty object. LastConnectedAt is migration 0004's; it decides when an idle room is deleted. Capacity is the room's number of teams, which migration 0007 set for rooms created before a team held one member. Round is migration 0008's: the lobby's round, from 1, which goes up each time the lobby is reopened after a game; rooms created before it are in round 1, and a record created without a round gets that default. RoundStartedAt is migration 0009's: when the current round began, which the maximum age of retention counts from; rooms created before it have their creation time. BoundRound is migration 0011's: the last round whose game the game's start hook confirmed, or 0.

func (RoomRecord) TableName

func (RoomRecord) TableName() string

type SessionRecord

type SessionRecord struct {
	ID         string    `gorm:"column:id;type:uuid;primaryKey"`
	PlayerID   string    `gorm:"column:player_id;type:uuid;not null"`
	BearerHash []byte    `gorm:"column:bearer_hash;type:bytea;not null"`
	CreatedAt  time.Time `gorm:"column:created_at;not null"`
	ExpiresAt  time.Time `gorm:"column:expires_at;not null"`
}

SessionRecord deliberately stores only a digest of the bearer credential.

func (SessionRecord) TableName

func (SessionRecord) TableName() string

type StartRosterRecord

type StartRosterRecord struct {
	LobbyID   string `gorm:"column:lobby_id;type:uuid;primaryKey"`
	PlayerID  string `gorm:"column:player_id;type:uuid;not null"`
	TeamID    string `gorm:"column:team_id;type:uuid;not null"`
	MemberID  string `gorm:"column:member_id;type:uuid;primaryKey"`
	TeamOrder int    `gorm:"column:team_order;not null"`
}

StartRosterRecord is the roster a start froze. It never changes while the lobby is started; reopening the lobby after the game deletes its rows, and the next start writes new ones. Its stable key is the room and source membership identity rather than a synthetic ID.

func (StartRosterRecord) TableName

func (StartRosterRecord) TableName() string

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store implements aggregate transactions. It holds only state: pushing a committed change to Centrifugo happens outside this adapter.

func NewStore

func NewStore(db *gorm.DB, clock domain.Clock) (*Store, error)

func (*Store) Create

func (store *Store) Create(ctx context.Context, principal domain.Principal, request domain.CreateRequest, aggregate domain.Aggregate) (domain.Snapshot, error)

func (*Store) Read

func (store *Store) Read(ctx context.Context, scope domain.Scope) (domain.Aggregate, error)

func (*Store) ResolveCode

func (store *Store) ResolveCode(ctx context.Context, gameKey, code string) (domain.Scope, error)

func (*Store) Transact

func (store *Store) Transact(ctx context.Context, scope domain.Scope, mutation domain.Mutation) (domain.Aggregate, error)

type TeamRecord

type TeamRecord struct {
	ID             string `gorm:"column:id;type:uuid;primaryKey"`
	LobbyID        string `gorm:"column:lobby_id;type:uuid;not null"`
	Name           string `gorm:"column:name;not null"`
	NormalizedName string `gorm:"column:normalized_name;not null"`
	TeamOrder      int    `gorm:"column:team_order;not null"`
}

func (TeamRecord) TableName

func (TeamRecord) TableName() string

type WatcherRecord

type WatcherRecord struct {
	LobbyID     string     `gorm:"column:lobby_id;type:uuid;primaryKey"`
	PlayerID    string     `gorm:"column:player_id;type:uuid;primaryKey"`
	DisplayName string     `gorm:"column:display_name;not null"`
	JoinedAt    time.Time  `gorm:"column:joined_at;not null"`
	KickedAt    *time.Time `gorm:"column:kicked_at"`
}

WatcherRecord is migration 0006's: a person who watches the lobby with its join code, outside its members. A watcher who leaves is deleted; one the host kicked keeps the row with KickedAt set. DisplayName is copied when they start watching, as a membership's is.

func (WatcherRecord) TableName

func (WatcherRecord) TableName() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL