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
+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]
}