add match result reporting to game-server

This commit is contained in:
2026-11-10 00:32:54 +03:00
parent dcb76fa570
commit 271daac935
7 changed files with 654 additions and 13 deletions
+76 -2
View File
@@ -6,6 +6,7 @@ package game
import (
"context"
"errors"
"log/slog"
"sync"
"time"
@@ -13,6 +14,10 @@ import (
"github.com/ruby-sea-battle/game-server/internal/protocol"
)
// reportTimeout bounds the whole result report (including retries done by
// the reporter) so END messages are not delayed indefinitely.
const reportTimeout = 10 * time.Second
// ErrMatchFinished is returned by Join when the player tries to join a match
// that has already ended. The stored END message (if any) is replayed to the
// connection before Join returns.
@@ -73,6 +78,20 @@ func playerStatesFor(serverState int) (p1State, p2State int) {
}
}
// MatchResult is the outcome of a finished match, reported to the
// main-server before the players are told the match has ended.
type MatchResult struct {
MatchID string
Status string // "player1_won", "player2_won" or "abandoned"
DurationSeconds int64
}
// Reporter reports match results to the main-server. Implementations must
// bound their own execution time (e.g. with http timeouts and retries).
type Reporter interface {
ReportMatchResult(ctx context.Context, result MatchResult) error
}
// Sender abstracts a player connection so the game logic stays testable and
// independent of the websocket implementation.
type Sender interface {
@@ -115,6 +134,7 @@ type Match struct {
playerIDs [2]int64 // slot 0 = player1, slot 1 = player2 (internal only)
slots [2]*PlayerSlot
created time.Time // when the match was created (first JOIN); used for result reporting
mu sync.Mutex
started bool // both players joined at least once
ended bool
@@ -202,18 +222,26 @@ type finishedMatch struct {
// Manager owns all matches of this server instance.
type Manager struct {
joinTimeout time.Duration
reporter Reporter // nil: do not report match results
mu sync.Mutex
matches map[string]*Match
finished map[string]*finishedMatch
}
func NewManager(joinTimeout time.Duration) *Manager {
return &Manager{
// NewManager creates a Manager. If a Reporter is provided, match results
// are reported to the main-server before END messages are sent to players;
// otherwise (e.g. in tests) reporting is skipped.
func NewManager(joinTimeout time.Duration, reporters ...Reporter) *Manager {
m := &Manager{
joinTimeout: joinTimeout,
matches: make(map[string]*Match),
finished: make(map[string]*finishedMatch),
}
if len(reporters) > 0 {
m.reporter = reporters[0]
}
return m
}
// GetMatch returns the match with the given ID, or nil if not found.
@@ -256,6 +284,7 @@ func (m *Manager) Join(ctx context.Context, conn Sender, gc *auth.GameClaims, us
gameToken: token,
tokenExp: gc.ExpiresAt.Time,
playerIDs: [2]int64{gc.Player1ID, gc.Player2ID},
created: now,
slots: [2]*PlayerSlot{
{UserID: gc.Player1ID},
{UserID: gc.Player2ID},
@@ -685,6 +714,14 @@ func (m *Manager) finishMatchWithEndsLocked(match *Match, endsPerSlot [2]playerE
m.purgeFinishedLocked(now)
m.mu.Unlock()
// Report the result to the main-server before notifying the players:
// the players fetch match details from the main-server after they
// receive END, so the record must exist by then. Reporting is
// best-effort — on failure END is still sent. Done outside of any lock.
if m.reporter != nil {
m.reportResult(match, endsPerSlot)
}
// Network I/O happens outside of any lock.
for _, n := range notify {
_ = n.conn.Send(context.Background(), n.data)
@@ -727,6 +764,43 @@ func (m *Manager) finishGame(matchID string, winnerSlot int) {
m.finishMatchWithEndsLocked(match, endsPerSlot)
}
// reportResult reports the match result to the main-server. Called after the
// match has been torn down but before the END messages reach the players.
// Failures are logged; the END messages are sent regardless.
func (m *Manager) reportResult(match *Match, endsPerSlot [2]playerEnd) {
created := match.created
if created.IsZero() {
created = time.Now()
}
result := MatchResult{
MatchID: match.ID,
Status: outcomeStatus(endsPerSlot),
DurationSeconds: max(0, int64(time.Since(created).Seconds())),
}
ctx, cancel := context.WithTimeout(context.Background(), reportTimeout)
defer cancel()
if err := m.reporter.ReportMatchResult(ctx, result); err != nil {
slog.Error("failed to report match result to the main-server",
"match", match.ID, "status", result.Status, "err", err)
}
}
// outcomeStatus maps the per-player END codes to the match status expected
// by the main-server: the winner is the player who received EndCodeVictory.
// Any other ending (join timeout, technical failure) is reported as
// "abandoned".
func outcomeStatus(endsPerSlot [2]playerEnd) string {
for i, end := range endsPerSlot {
if end.code == protocol.EndCodeVictory {
if i == 0 {
return "player1_won"
}
return "player2_won"
}
}
return "abandoned"
}
// Shutdown closes all active player connections across all matches with code 1001 (going away)
// and stops all pending join timers.
func (m *Manager) Shutdown() {