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() {
+215
View File
@@ -3,6 +3,7 @@ package game
import (
"context"
"encoding/json"
"errors"
"sync"
"testing"
"time"
@@ -984,3 +985,217 @@ func TestFireAckAndReplay(t *testing.T) {
}
}
// fakeReporter records result reports and can be told to fail.
type fakeReporter struct {
mu sync.Mutex
results []MatchResult
err error
onReport func()
}
func (f *fakeReporter) ReportMatchResult(_ context.Context, result MatchResult) error {
f.mu.Lock()
f.results = append(f.results, result)
cb := f.onReport
err := f.err
f.mu.Unlock()
if cb != nil {
cb()
}
return err
}
func (f *fakeReporter) calls() []MatchResult {
f.mu.Lock()
defer f.mu.Unlock()
out := make([]MatchResult, len(f.results))
copy(out, f.results)
return out
}
func setupStartedGameWithReporter(t *testing.T, rep Reporter) (*Manager, *Match, *fakeConn, *fakeConn) {
t.Helper()
m := NewManager(time.Minute, rep)
gc := claims(time.Now().Add(time.Hour))
c1, c2 := &fakeConn{}, &fakeConn{}
match, _, err := m.Join(context.Background(), c1, gc, gc.Player1ID)
if err != nil {
t.Fatalf("join p1: %v", err)
}
if _, _, err := m.Join(context.Background(), c2, gc, gc.Player2ID); err != nil {
t.Fatalf("join p2: %v", err)
}
ships := validTestShips()
if err := m.PlaceShips(context.Background(), match, 0, ships); err != nil {
t.Fatalf("p1 place ships: %v", err)
}
if err := m.PlaceShips(context.Background(), match, 1, ships); err != nil {
t.Fatalf("p2 place ships: %v", err)
}
return m, match, c1, c2
}
// sinkAllOpponentShips lets player 1 destroy every ship of player 2, which
// ends the match with player 1 as the winner.
func sinkAllOpponentShips(t *testing.T, m *Manager, match *Match) {
t.Helper()
for i, ship := range validTestShips() {
cells := ship.Cells()
for j, c := range cells {
res, err := m.Fire(context.Background(), match, 0, c.X, c.Y)
if err != nil {
t.Fatalf("ship %d cell %d fire: %v", i, j, err)
}
if j == len(cells)-1 && res != protocol.FireResultSunk {
t.Fatalf("ship %d last cell: res = %d, want Sunk", i, res)
}
}
}
}
func TestFinishGameReportsResultBeforeEnd(t *testing.T) {
rep := &fakeReporter{}
m, match, c1, c2 := setupStartedGameWithReporter(t, rep)
// The report must happen before the END messages reach the players.
rep.onReport = func() {
for i, c := range []*fakeConn{c1, c2} {
for _, msg := range c.messages() {
if parseMsg(t, msg)[0] == float64(protocol.OpEnd) {
t.Errorf("player %d received END before the result was reported", i)
}
}
}
}
sinkAllOpponentShips(t, m, match)
results := rep.calls()
if len(results) != 1 {
t.Fatalf("reported %d results, want 1", len(results))
}
if results[0].MatchID != match.ID {
t.Fatalf("match id = %q, want %q", results[0].MatchID, match.ID)
}
if results[0].Status != "player1_won" {
t.Fatalf("status = %q, want player1_won", results[0].Status)
}
if results[0].DurationSeconds < 0 {
t.Fatalf("duration = %d, want >= 0", results[0].DurationSeconds)
}
// END is still delivered after the report.
c1End := parseMsg(t, lastMessage(t, c1))
if c1End[0] != float64(protocol.OpEnd) || c1End[2] != float64(protocol.EndCodeVictory) {
t.Fatalf("p1 got %v, want END victory", c1End)
}
}
func TestFinishGameReportsPlayer2Win(t *testing.T) {
rep := &fakeReporter{}
m, match, _, _ := setupStartedGameWithReporter(t, rep)
// Player 1 misses so the turn passes to player 2, who then sinks all
// ships of player 1.
if _, err := m.Fire(context.Background(), match, 0, 9, 9); err != nil {
t.Fatalf("p1 miss: %v", err)
}
for i, ship := range validTestShips() {
cells := ship.Cells()
for j, c := range cells {
if _, err := m.Fire(context.Background(), match, 1, c.X, c.Y); err != nil {
t.Fatalf("ship %d cell %d fire: %v", i, j, err)
}
}
}
results := rep.calls()
if len(results) != 1 {
t.Fatalf("reported %d results, want 1", len(results))
}
if results[0].Status != "player2_won" {
t.Fatalf("status = %q, want player2_won", results[0].Status)
}
}
func TestJoinTimeoutReportsAbandoned(t *testing.T) {
rep := &fakeReporter{}
m := NewManager(50*time.Millisecond, rep)
gc := claims(time.Now().Add(time.Hour))
c1 := &fakeConn{}
if _, _, err := m.Join(context.Background(), c1, gc, gc.Player1ID); err != nil {
t.Fatalf("join: %v", err)
}
deadline := time.Now().Add(2 * time.Second)
for {
if results := rep.calls(); len(results) > 0 {
break
}
if time.Now().After(deadline) {
t.Fatal("timed out waiting for the result report")
}
time.Sleep(10 * time.Millisecond)
}
results := rep.calls()
if len(results) != 1 || results[0].Status != "abandoned" {
t.Fatalf("results = %+v, want one abandoned report", results)
}
}
func TestEndMatchReportsAbandoned(t *testing.T) {
rep := &fakeReporter{}
m, match, _, _ := setupStartedGameWithReporter(t, rep)
m.EndMatch(match.ID, 0, "game completed")
results := rep.calls()
if len(results) != 1 {
t.Fatalf("reported %d results, want 1", len(results))
}
if results[0].Status != "abandoned" {
t.Fatalf("status = %q, want abandoned", results[0].Status)
}
}
func TestReportFailureStillEndsMatch(t *testing.T) {
rep := &fakeReporter{err: errors.New("main-server is down")}
m, match, c1, c2 := setupStartedGameWithReporter(t, rep)
gc := claims(time.Now().Add(time.Hour))
sinkAllOpponentShips(t, m, match)
if len(rep.calls()) != 1 {
t.Fatalf("reported %d results, want 1", len(rep.calls()))
}
// Even though reporting failed, both players get END and the match is
// recorded as finished (a late join replays END).
if v := parseMsg(t, lastMessage(t, c1)); v[0] != float64(protocol.OpEnd) || v[2] != float64(protocol.EndCodeVictory) {
t.Fatalf("p1 got %v, want END victory", v)
}
if v := parseMsg(t, lastMessage(t, c2)); v[0] != float64(protocol.OpEnd) || v[2] != float64(protocol.EndCodeDefeat) {
t.Fatalf("p2 got %v, want END defeat", v)
}
late := &fakeConn{}
if _, _, err := m.Join(context.Background(), late, gc, gc.Player1ID); err != ErrMatchFinished {
t.Fatalf("late join err = %v, want ErrMatchFinished", err)
}
if v := parseMsg(t, lastMessage(t, late)); v[0] != float64(protocol.OpEnd) {
t.Fatalf("late join got %v, want replayed END", v)
}
}
func lastMessage(t *testing.T, c *fakeConn) []byte {
t.Helper()
msgs := c.messages()
if len(msgs) == 0 {
t.Fatal("connection received no messages")
}
return msgs[len(msgs)-1]
}