matchmaker

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTooManyTickets = errors.New("too many tickets for session")
	ErrRateLimited    = errors.New("matchmaker rate limited")
	ErrInvalidTicket  = errors.New("invalid ticket parameters")
	ErrTokenInvalid   = errors.New("match token invalid or expired")
)

Functions

This section is empty.

Types

type CompletionRecord

type CompletionRecord struct {
	MatchID     string    `json:"match_id"`
	CompletedAt time.Time `json:"completed_at"`
	PlayerCount int       `json:"player_count"`
}

CompletionRecord tracks a recently completed match for stats.

type MatchResult

type MatchResult struct {
	MatchID       string            `json:"match_id"`
	PlayerIDs     []string          `json:"player_ids"`
	Usernames     []string          `json:"usernames"`
	Users         []*Presence       `json:"users"`
	MatchedUsers  []MatchedUser     `json:"matched_users,omitempty"`
	TicketIDs     map[string]string `json:"ticket_ids"` // user_id -> ticket_id
	MatchToken    string            `json:"match_token"`
	QueueName     string            `json:"queue_name"`
	Authoritative bool              `json:"authoritative"`
	Module        string            `json:"module"`
}

MatchResult represents a successful matchmaking pairing.

type MatchedUser

type MatchedUser struct {
	UserID            string             `json:"user_id"`
	Username          string             `json:"username"`
	SessionID         string             `json:"session_id"`
	PartyID           string             `json:"party_id,omitempty"`
	TicketID          string             `json:"ticket_id,omitempty"`
	StringProperties  map[string]string  `json:"string_properties,omitempty"`
	NumericProperties map[string]float64 `json:"numeric_properties,omitempty"`
}

MatchedUser is a reference-shaped matchmaker_matched user entry.

type Matchmaker

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

Matchmaker processes matchmaking queues.

func NewMatchmaker

func NewMatchmaker(
	logger *zap.Logger,
	rdb *redis.Client,
	db *sql.DB,
	nk runtime.RuntimeModule,
	hookRegistry *runtime.HookRegistry,
	onMatched func(result MatchResult),
) *Matchmaker

NewMatchmaker creates a new Matchmaker instance.

func (*Matchmaker) Cancel

func (mm *Matchmaker) Cancel(ctx context.Context, ticketID string) error

Cancel removes a ticket from the matchmaking queue.

func (*Matchmaker) Configure

func (mm *Matchmaker) Configure(cfg *MatchmakerConfig)

Configure updates the matchmaking configurations.

func (*Matchmaker) ConsumeMatchToken

func (mm *Matchmaker) ConsumeMatchToken(ctx context.Context, token string) (*MatchResult, error)

ConsumeMatchToken validates and consumes a single-use join token.

func (*Matchmaker) GetQueueStats

func (mm *Matchmaker) GetQueueStats(ctx context.Context, queueName string) (int, int, error)

GetQueueStats retrieves queue statistics.

func (*Matchmaker) GetStats

func (mm *Matchmaker) GetStats(ctx context.Context) Stats

GetStats returns ticket_count, oldest create time, and recent completions.

func (*Matchmaker) GetTicket

func (mm *Matchmaker) GetTicket(ctx context.Context, ticketID string) (*Ticket, error)

GetTicket retrieves a ticket status (either active or historical).

func (*Matchmaker) RemovePartyAll

func (mm *Matchmaker) RemovePartyAll(ctx context.Context, partyID string) error

RemovePartyAll cancels every ticket associated with the given party ID.

func (*Matchmaker) RemoveSessionAll

func (mm *Matchmaker) RemoveSessionAll(ctx context.Context, sessionID string) error

RemoveSessionAll cancels every ticket owned by the session.

func (*Matchmaker) SetDependencies

func (mm *Matchmaker) SetDependencies(db *sql.DB, nk runtime.RuntimeModule, hookRegistry *runtime.HookRegistry)

SetDependencies allows updating dependencies dynamically after initialization.

func (*Matchmaker) SetMatchedCallback

func (mm *Matchmaker) SetMatchedCallback(fn func(result MatchResult))

SetMatchedCallback updates the onMatched notification callback.

func (*Matchmaker) SetOverrideHandler

func (mm *Matchmaker) SetOverrideHandler(fn MatchmakerOverrideHandler)

SetOverrideHandler sets an override that rewrites default candidate groups.

func (*Matchmaker) SetProcessorHandler

func (mm *Matchmaker) SetProcessorHandler(fn MatchmakerProcessorHandler)

SetProcessorHandler sets a processor that replaces default matching.

func (*Matchmaker) SetSpawnMatch

func (mm *Matchmaker) SetSpawnMatch(fn func(result MatchResult))

SetSpawnMatch registers a callback invoked for authoritative matches that should be spawned.

func (*Matchmaker) Start

func (mm *Matchmaker) Start(ctx context.Context, interval time.Duration)

Start runs the matchmaking tick loop.

func (*Matchmaker) Stop

func (mm *Matchmaker) Stop()

Stop halts the matchmaking loop. Safe to call multiple times.

func (*Matchmaker) Submit

func (mm *Matchmaker) Submit(ctx context.Context, t *Ticket) error

Submit adds a ticket to the matchmaking queue.

func (*Matchmaker) SubmitParty

func (mm *Matchmaker) SubmitParty(ctx context.Context, leader *Presence, members []*Presence, ticket *Ticket) error

SubmitParty submits an atomic party ticket listing leader + members.

func (*Matchmaker) Tick

func (mm *Matchmaker) Tick(ctx context.Context)

Tick evaluates candidate tickets for all configured queues.

type MatchmakerConfig

type MatchmakerConfig struct {
	ProcessingIntervalMs int                    `json:"processing_interval_ms" yaml:"processing_interval_ms"`
	TicketExpirySec      int                    `json:"ticket_expiry_sec" yaml:"ticket_expiry_sec"`
	MaxTickets           int                    `json:"max_tickets" yaml:"max_tickets"`
	MaxIntervals         int                    `json:"max_intervals" yaml:"max_intervals"`
	TokenTTLSec          int                    `json:"token_ttl_sec" yaml:"token_ttl_sec"`
	RevPrecision         bool                   `json:"rev_precision" yaml:"rev_precision"`
	UseRedlock           bool                   `json:"use_redlock" yaml:"use_redlock"`
	RateLimitMax         int                    `json:"rate_limit_max" yaml:"rate_limit_max"`
	RateLimitWindowSec   int                    `json:"rate_limit_window_sec" yaml:"rate_limit_window_sec"`
	TokenSecret          string                 `json:"-" yaml:"-"`
	Queues               map[string]QueueConfig `json:"queues" yaml:"queues"`
}

MatchmakerConfig overall configuration for matchmaking service.

func DefaultConfig

func DefaultConfig() *MatchmakerConfig

DefaultConfig returns default matchmaking configurations.

type MatchmakerOverrideHandler

type MatchmakerOverrideHandler func(ctx context.Context, candidates [][]*Ticket) [][]*Ticket

MatchmakerOverrideHandler rewrites candidate groups after default matching.

type MatchmakerProcessorHandler

type MatchmakerProcessorHandler func(ctx context.Context, tickets []*Ticket) [][]*Ticket

MatchmakerProcessorHandler replaces default matching for a queue tick. Return nil to form no matches this tick; otherwise each inner slice is a match group.

type Presence

type Presence struct {
	UserID    string `json:"user_id"`
	Username  string `json:"username"`
	SessionID string `json:"session_id"`
	Node      string `json:"node,omitempty"`
}

Presence is a player bound to a matchmaker ticket.

type QueueConfig

type QueueConfig struct {
	Name             string                 `json:"name" yaml:"name"`
	MinPlayers       int                    `json:"min_players" yaml:"min_players"`
	MaxPlayers       int                    `json:"max_players" yaml:"max_players"`
	CountMultiple    int                    `json:"count_multiple" yaml:"count_multiple"`
	SkillMatch       SkillMatchConfig       `json:"skill_match" yaml:"skill_match"`
	RegionMatch      RegionMatchConfig      `json:"region_match" yaml:"region_match"`
	ReversePrecision ReversePrecisionConfig `json:"reverse_precision" yaml:"reverse_precision"`
}

QueueConfig configuration for an individual matchmaking queue partition.

type RegionMatchConfig

type RegionMatchConfig struct {
	Strict           bool `json:"strict" yaml:"strict"`
	FallbackDelaySec int  `json:"fallback_delay_sec" yaml:"fallback_delay_sec"`
}

RegionMatchConfig configuration for region-based matchmaking.

type ReversePrecisionConfig

type ReversePrecisionConfig struct {
	Enabled               bool `json:"enabled" yaml:"enabled"`
	ReverseThresholdTicks int  `json:"reverse_threshold_ticks" yaml:"reverse_threshold_ticks"`
}

ReversePrecisionConfig configuration for bidirectional validation.

type SkillMatchConfig

type SkillMatchConfig struct {
	Enabled              bool    `json:"enabled" yaml:"enabled"`
	InitialRange         float64 `json:"initial_range" yaml:"initial_range"`
	MaxRange             float64 `json:"max_range" yaml:"max_range"`
	ExpansionIntervalSec int     `json:"expansion_interval_sec" yaml:"expansion_interval_sec"`
	ExpansionStep        float64 `json:"expansion_step" yaml:"expansion_step"`
}

SkillMatchConfig configuration for skill-based matchmaking.

type Stats

type Stats struct {
	TicketCount            int                `json:"ticket_count"`
	OldestTicketCreateTime time.Time          `json:"oldest_ticket_create_time"`
	Completions            []CompletionRecord `json:"completions"`
}

Stats is aggregate matchmaker health information.

type Ticket

type Ticket struct {
	ID                string             `json:"id"`
	UserID            string             `json:"user_id"`
	Username          string             `json:"username"`
	SkillRating       int                `json:"skill_rating"`
	Region            string             `json:"region"`
	CreatedAt         time.Time          `json:"created_at"`
	Query             string             `json:"query"`
	MinCount          int                `json:"min_count"`
	MaxCount          int                `json:"max_count"`
	CountMultiple     int                `json:"count_multiple"`
	Count             int                `json:"count"`
	PartyID           string             `json:"party_id"`
	SessionID         string             `json:"session_id"`
	Presences         []*Presence        `json:"presences,omitempty"`
	Intervals         int                `json:"intervals"`
	StringProperties  map[string]string  `json:"string_properties"`
	NumericProperties map[string]float64 `json:"numeric_properties"`
	ReversePrecision  bool               `json:"reverse_precision"`
	QueueName         string             `json:"queue_name"`
	Status            string             `json:"status"`
	MatchID           string             `json:"match_id"`
	MatchToken        string             `json:"match_token"`
}

Ticket represents a player's (or party's) entry in the matchmaking pool.

Jump to

Keyboard shortcuts

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