mirror of
https://github.com/jcreek/CosmicClash.git
synced 2026-09-11 08:23:45 +00:00
fix(multiplayer): complete live results atomically
This commit is contained in:
@@ -33,6 +33,16 @@ FROM matches
|
||||
WHERE match_id = $1 AND server_id = $2
|
||||
FOR UPDATE`
|
||||
|
||||
const ResultMatchPendingSQL = `UPDATE matches
|
||||
SET state = 'RESULT_PENDING', revision = revision + 1
|
||||
WHERE match_id = $1 AND state = 'LIVE'`
|
||||
|
||||
const ResultTicketsPendingSQL = `UPDATE queue_tickets q
|
||||
SET state = 'RESULT_PENDING', revision = revision + 1
|
||||
FROM match_participants mp
|
||||
WHERE mp.match_id = $1 AND q.ticket_id = mp.ticket_id AND q.player_id = mp.player_id
|
||||
AND mp.participation_active AND q.state = 'LIVE'`
|
||||
|
||||
const ResultMatchCompleteSQL = `UPDATE matches
|
||||
SET state = 'COMPLETED', revision = revision + 1, completed_at = $2
|
||||
WHERE match_id = $1 AND state = 'RESULT_PENDING'`
|
||||
@@ -41,6 +51,14 @@ const ResultReceiptCommitSQL = `UPDATE result_receipts
|
||||
SET committed_at = COALESCE(committed_at, $2)
|
||||
WHERE match_id = $1`
|
||||
|
||||
const ResultTicketsCompleteSQL = `UPDATE queue_tickets q
|
||||
SET state = 'COMPLETED', revision = revision + 1
|
||||
FROM match_participants mp
|
||||
WHERE mp.match_id = $1 AND q.ticket_id = mp.ticket_id AND q.player_id = mp.player_id
|
||||
AND mp.participation_active AND q.state = 'RESULT_PENDING'`
|
||||
|
||||
const ResultParticipantCountSQL = `SELECT count(*) FROM match_participants WHERE match_id = $1 AND participation_active`
|
||||
|
||||
const ResultOutboxSQL = `INSERT INTO outbox
|
||||
(event_id, aggregate_type, aggregate_id, revision, event_type, payload)
|
||||
VALUES ($1, 'match', $2, $3, 'match_completed', $4)`
|
||||
@@ -51,11 +69,12 @@ WHERE player_id = ANY($1)
|
||||
ORDER BY player_id
|
||||
FOR UPDATE`
|
||||
|
||||
const MatchParticipantRatingsSQL = `SELECT mp.player_id, mp.team, r.rating, r.deviation,
|
||||
const MatchParticipantRatingsSQL = `SELECT mp.player_id, mp.team, mp.abandoned_at, r.rating, r.deviation,
|
||||
r.volatility, r.ranked_games, r.updated_at
|
||||
FROM match_participants mp
|
||||
JOIN ratings r ON r.player_id = mp.player_id
|
||||
WHERE mp.match_id = $1
|
||||
AND mp.participation_active
|
||||
ORDER BY mp.player_id`
|
||||
|
||||
const RatingValuesSQL = `SELECT player_id, rating, deviation, volatility, ranked_games, updated_at
|
||||
@@ -101,7 +120,7 @@ func CompleteResultWithResult(ctx context.Context, db *sql.DB, receipt domain.Re
|
||||
}
|
||||
|
||||
func completeResult(ctx context.Context, db *sql.DB, receipt domain.ResultReceipt, serverID, eventID string, payload []byte, now time.Time, result *domain.MatchResult) error {
|
||||
if receipt.ResultID == "" || receipt.MatchID == "" || serverID == "" || eventID == "" || len(payload) == 0 {
|
||||
if db == nil || receipt.ResultID == "" || receipt.MatchID == "" || len(receipt.ResultNonce) < 16 || len(receipt.ResultNonce) > 128 || receipt.ReceivedAt.IsZero() || now.IsZero() || serverID == "" || eventID == "" || len(payload) == 0 || (receipt.IntegrityState != domain.IntegrityCertified && receipt.IntegrityState != domain.IntegritySuppressed && receipt.IntegrityState != domain.IntegrityReview) {
|
||||
return fmt.Errorf("invalid result transaction arguments")
|
||||
}
|
||||
return RunSerializable(ctx, db, DefaultSerializableAttempts, func(ctx context.Context, tx *sql.Tx) error {
|
||||
@@ -121,7 +140,7 @@ func completeResult(ctx context.Context, db *sql.DB, receipt domain.ResultReceip
|
||||
return fmt.Errorf("result receipt conflict: %w", err)
|
||||
}
|
||||
if priorID != receipt.ResultID || priorMatch != receipt.MatchID || priorNonce != receipt.ResultNonce || priorIntegrity != string(receipt.IntegrityState) || !bytes.Equal(priorDigest, receipt.PayloadDigest[:]) {
|
||||
return fmt.Errorf("conflicting result receipt")
|
||||
return fmt.Errorf("%w: durable receipt differs", domain.ErrResultConflict)
|
||||
}
|
||||
}
|
||||
var lockedMatch, playlist, state string
|
||||
@@ -133,9 +152,23 @@ func completeResult(ctx context.Context, db *sql.DB, receipt domain.ResultReceip
|
||||
_, err := tx.ExecContext(ctx, ResultReceiptCommitSQL, receipt.MatchID, now)
|
||||
return err
|
||||
}
|
||||
if state == string(domain.Live) {
|
||||
updated, err := tx.ExecContext(ctx, ResultMatchPendingSQL, receipt.MatchID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if changed, err := updated.RowsAffected(); err != nil || changed != 1 {
|
||||
return fmt.Errorf("result-pending transition lost race")
|
||||
}
|
||||
state = string(domain.ResultPending)
|
||||
revision++
|
||||
}
|
||||
if state != "RESULT_PENDING" {
|
||||
return fmt.Errorf("match is not result-pending: %s", state)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, ResultTicketsPendingSQL, receipt.MatchID); err != nil {
|
||||
return err
|
||||
}
|
||||
if result != nil && domain.RatingEligible(receipt) {
|
||||
if err := applyResultRatings(ctx, tx, receipt.MatchID, domain.Playlist(playlist), *result, now); err != nil {
|
||||
return err
|
||||
@@ -152,6 +185,21 @@ func completeResult(ctx context.Context, db *sql.DB, receipt domain.ResultReceip
|
||||
if changed != 1 {
|
||||
return fmt.Errorf("result completion lost race")
|
||||
}
|
||||
completedTickets, err := tx.ExecContext(ctx, ResultTicketsCompleteSQL, receipt.MatchID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var participants int64
|
||||
if err := tx.QueryRowContext(ctx, ResultParticipantCountSQL, receipt.MatchID).Scan(&participants); err != nil {
|
||||
return err
|
||||
}
|
||||
completed, err := completedTickets.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if completed != participants {
|
||||
return fmt.Errorf("result ticket completion mismatch: completed=%d participants=%d", completed, participants)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, ResultReceiptCommitSQL, receipt.MatchID, now); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -165,6 +213,7 @@ type participantRating struct {
|
||||
team int
|
||||
rating domain.Rating
|
||||
rankedGames int
|
||||
abandoned bool
|
||||
}
|
||||
|
||||
func applyResultRatings(ctx context.Context, tx *sql.Tx, matchID string, playlist domain.Playlist, result domain.MatchResult, now time.Time) error {
|
||||
@@ -176,17 +225,29 @@ func applyResultRatings(ctx context.Context, tx *sql.Tx, matchID string, playlis
|
||||
var players []participantRating
|
||||
for rows.Next() {
|
||||
var player participantRating
|
||||
if err := rows.Scan(&player.playerID, &player.team, &player.rating.Value, &player.rating.RD, &player.rating.Volatility, &player.rankedGames, &player.rating.LastRatedAt); err != nil {
|
||||
var abandonedAt sql.NullTime
|
||||
if err := rows.Scan(&player.playerID, &player.team, &abandonedAt, &player.rating.Value, &player.rating.RD, &player.rating.Volatility, &player.rankedGames, &player.rating.LastRatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
player.abandoned = abandonedAt.Valid
|
||||
players = append(players, player)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(players) == 0 {
|
||||
return nil
|
||||
}
|
||||
var participantCount int
|
||||
if err := tx.QueryRowContext(ctx, ResultParticipantCountSQL, matchID).Scan(&participantCount); err != nil {
|
||||
return err
|
||||
}
|
||||
if participantCount != len(players) {
|
||||
return fmt.Errorf("result rating roster is incomplete")
|
||||
}
|
||||
ids := make([]string, len(players))
|
||||
for i := range players {
|
||||
ids[i] = players[i].playerID
|
||||
@@ -239,7 +300,12 @@ func applyResultRatings(ctx context.Context, tx *sql.Tx, matchID string, playlis
|
||||
if err := values.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
outcome := domain.MatchOutcome{Team0Score: result.Team0Score, Team1Score: result.Team1Score}
|
||||
outcome := domain.MatchOutcome{Team0Score: result.Team0Score, Team1Score: result.Team1Score, Abandoners: make(map[string]bool)}
|
||||
for _, player := range players {
|
||||
if player.abandoned {
|
||||
outcome.Abandoners[player.playerID] = true
|
||||
}
|
||||
}
|
||||
for _, player := range players {
|
||||
current, ok := ratings[player.playerID]
|
||||
if !ok {
|
||||
|
||||
Reference in New Issue
Block a user