diff --git a/game-server/README.md b/game-server/README.md index c5d9cd6..4086995 100644 --- a/game-server/README.md +++ b/game-server/README.md @@ -8,7 +8,7 @@ WebSocket-сервер партий морского боя. Принимает ```sh go build ./cmd/server -JWT_SECRET=... PUBLIC_ADDR=ws://localhost:8081/ws ./server +JWT_SECRET=... PUBLIC_ADDR=ws://localhost:8081/ws MAIN_SERVER_URL=http://localhost:3000 ./server ``` Конфигурация через переменные окружения: @@ -17,7 +17,8 @@ JWT_SECRET=... PUBLIC_ADDR=ws://localhost:8081/ws ./server |--------------------|--------------|----------| | `LISTEN_ADDR` | `:8081` | Адрес, на котором открывается HTTP/WebSocket-сервер (может быть за reverse proxy). | | `PUBLIC_ADDR` | — (обяз.) | Публичный адрес сервера, например `ws://localhost:8081/ws`. Используется **только** для идентификации: сравнивается строго (побайтово) с полем `game_server` игрового токена. Main-server должен подписывать в токены ровно эту строку. | -| `JWT_SECRET` | — (обяз.) | Общий с main-server HS256-секрет (`secret_key_base`). Им подписаны и игровой, и пользовательский токены. | +| `JWT_SECRET` | — (обяз.) | Общий с main-server HS256-секрет (`secret_key_base`). Им подписаны и игровой, и пользовательский токены, а также HMAC-подпись отчётов об итогах матчей. | +| `MAIN_SERVER_URL` | — (обяз.) | Базовый URL HTTP API main-server (например, `http://localhost:3000`). Используется для отправки итогов завершённых матчей. | | `JOIN_TIMEOUT` | `2m` | Сколько первый игрок ждёт второго, прежде чем партия будет отменена. Go-duration (`90s`, `2m`) или число секунд. | | `ALLOWED_ORIGINS` | `*` | Список Origin-паттернов через запятую для проверки заголовка `Origin`; `*` отключает проверку. | @@ -79,6 +80,10 @@ JWT_SECRET=... PUBLIC_ADDR=ws://localhost:8081/ws ./server После отправки сообщения END сервер сразу закрывает WebSocket-соединение с кодом 1000 (нормальное завершение). Сохранённое сообщение END хранится в реестре завершённых партий и автоматически воспроизводится игроку при повторном подключении перед закрытием соединения. +Перед рассылкой END сервер отправляет итоги матча на main-server (см. раздел +[«Отчёт об итогах матча»](#отчёт-об-итогах-матча)); клиент может запрашивать +подробности матча с main-server сразу после получения END. + ### STATE (3) Переход игры в новое состояние. Код состояния всегда отсылается **с точки @@ -195,6 +200,35 @@ JWT_SECRET=... PUBLIC_ADDR=ws://localhost:8081/ws ./server | 3 | `sunk` (корабль потоплен) | Корабль полностью уничтожен последним выстрелом. Все палубы корабля и все окружающие его клетки (включая диагональные) помечаются как поражённые. Если все корабли соперника уничтожены, партия завершается победой (рассылается сообщение END и соединение сразу закрывается). В противном случае право хода остаётся у стрелявшего игрока. | | 4 | `invalid_position` (неверная позиция) | Координаты выходят за пределы поля `10x10` либо указанная клетка уже была поражена ранее. Право хода остаётся у игрока. | +## Отчёт об итогах матча + +Когда партия завершается (победа, таймаут подключения соперника или технический +сбой), `game-server` **до рассылки игрокам END** сообщает итоги на main-server: + +``` +POST /api/internal/matches//result +Content-Type: application/json +X-Request-Timestamp: +X-Request-Signature: sha256= + +{"status": "player1_won", "duration_seconds": 125} +``` + +- `status` — `player1_won`, `player2_won`, `draw` или `abandoned`. Победа + определяется по коду END (`victory` у победителя); таймаут подключения и + техническое завершение (`EndMatch`) репортятся как `abandoned`. +- `duration_seconds` — время от создания матча (первого JOIN) до его завершения. + +Подпись: `hex(HMAC-SHA256(JWT_SECRET, ".."))`, где +`path` — путь без query string. Секрет по сети не передаётся; main-server +отклоняет запросы с расхождением времени больше 5 минут и подписи, не +привязанные к этому пути и телу. + +Отчёт выполняется **до** отправки END и является best-effort: при ошибке или +не-2xx ответе делается до 3 попыток с небольшой паузой, после чего ошибка +логируется, а END всё равно рассылается игрокам (матч не должен «зависнуть» +из-за недоступности main-server). Отчёт идемпотентен на стороне main-server. + ## Коды закрытия соединения | Код | Значение | @@ -248,7 +282,9 @@ internal/config/ — конфигурация из env internal/protocol/ — опкоды, коды состояний/завершения, сборка/разбор сообщений internal/auth/ — разбор и валидация JWT (HS256, exp обязателен) internal/game/ — менеджер партий: слоты игроков, очереди неподтверждённых - сообщений, таймер присоединения, реестр завершённых партий + сообщений, таймер присоединения, реестр завершённых партий, + отчёт об итогах +internal/mainserver/ — HTTP-клиент main-server: HMAC-подпись и отправка итогов матча internal/ws/ — websocket-эндпоинт: апгрейд, JOIN, read-цикл, ping ``` @@ -260,12 +296,12 @@ go test -race ./... Покрыты: валидация токенов, разбор/сборка сообщений (включая расстановку кораблей), сценарии менеджера (ожидание, старт, таймаут, повторный вход, замена соединения, ACK, -расстановка кораблей с переходами состояний) и сквозные интеграционные тесты через настоящий websocket. +расстановка кораблей с переходами состояний, отчёт об итогах матча до отправки END +и устойчивость к ошибкам отчёта), HMAC-подпись и HTTP-клиент отчётов (включая +повторные попытки) и сквозные интеграционные тесты через настоящий websocket. ## TODO (следующие этапы) -- игровая логика стрельбы/ходов (расстановка кораблей и переходы к фазе ходов уже реализованы); -- завершение партии по итогам игры с персонифицированными кодами - победы/поражения; -- репорт итогов партии на main-server (реестр завершённых партий уже - гарантирует, что партия завершается ровно один раз). +- пересчёт рейтинга на main-server по итогам матча (сейчас поля дельты + рейтинга остаются нулевыми); +- история матчей и расширенная статистика игрока. diff --git a/game-server/cmd/server/main.go b/game-server/cmd/server/main.go index 866b81c..8821a6f 100644 --- a/game-server/cmd/server/main.go +++ b/game-server/cmd/server/main.go @@ -12,6 +12,7 @@ import ( "github.com/ruby-sea-battle/game-server/internal/config" "github.com/ruby-sea-battle/game-server/internal/game" + "github.com/ruby-sea-battle/game-server/internal/mainserver" "github.com/ruby-sea-battle/game-server/internal/ws" _ "github.com/joho/godotenv/autoload" @@ -26,7 +27,13 @@ func main() { os.Exit(1) } - manager := game.NewManager(cfg.JoinTimeout) + reporter, err := mainserver.NewReporter(cfg.MainServerURL, cfg.JWTSecret, log) + if err != nil { + log.Error("configuration error", "err", err) + os.Exit(1) + } + + manager := game.NewManager(cfg.JoinTimeout, reporter) handler := ws.NewHandler(manager, cfg.JWTSecret, cfg.PublicAddr, cfg.AllowedOrigins, log) mux := http.NewServeMux() @@ -49,6 +56,7 @@ func main() { log.Info("game server listening", "listen_addr", cfg.ListenAddr, "public_addr", cfg.PublicAddr, + "main_server", cfg.MainServerURL, "join_timeout", cfg.JoinTimeout, ) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { diff --git a/game-server/internal/config/config.go b/game-server/internal/config/config.go index b6c8c85..4a704c3 100644 --- a/game-server/internal/config/config.go +++ b/game-server/internal/config/config.go @@ -21,8 +21,13 @@ type Config struct { // string into the tokens it issues. PublicAddr string // JWTSecret is the HS256 secret shared with the main server; both the - // game token and the user token are verified with it. + // game token and the user token are verified with it. The same secret is + // used to sign match result reports sent back to the main server. JWTSecret []byte + // MainServerURL is the base URL of the main server's HTTP API + // (e.g. "http://localhost:3000"). Match results are reported to it + // when a match ends. + MainServerURL string // JoinTimeout is how long the first player waits for the second one // before the match is cancelled. JoinTimeout time.Duration @@ -47,6 +52,11 @@ func Load() (Config, error) { } cfg.JWTSecret = []byte(secret) + cfg.MainServerURL = os.Getenv("MAIN_SERVER_URL") + if cfg.MainServerURL == "" { + return cfg, fmt.Errorf("MAIN_SERVER_URL is required (base URL of the main server, e.g. http://localhost:3000)") + } + joinTimeout, err := parseDuration(getenv("JOIN_TIMEOUT", "2m")) if err != nil { return cfg, fmt.Errorf("invalid JOIN_TIMEOUT: %w", err) diff --git a/game-server/internal/game/manager.go b/game-server/internal/game/manager.go index 77928c1..194a446 100644 --- a/game-server/internal/game/manager.go +++ b/game-server/internal/game/manager.go @@ -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() { diff --git a/game-server/internal/game/manager_test.go b/game-server/internal/game/manager_test.go index ed716d1..e98bd64 100644 --- a/game-server/internal/game/manager_test.go +++ b/game-server/internal/game/manager_test.go @@ -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] +} diff --git a/game-server/internal/mainserver/reporter.go b/game-server/internal/mainserver/reporter.go new file mode 100644 index 0000000..7bcb99b --- /dev/null +++ b/game-server/internal/mainserver/reporter.go @@ -0,0 +1,152 @@ +// Package mainserver reports match results back to the main-server's +// internal HTTP API. +// +// Requests are authenticated with HMAC-SHA256 over +// +// ".." +// +// using the same shared secret that is used for JWTs, so no additional +// configuration is required. The signature is sent in the +// X-Request-Signature header ("sha256=" + hex digest) together with the +// X-Request-Timestamp header; the secret itself never travels over the wire. +package mainserver + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/ruby-sea-battle/game-server/internal/game" +) + +const ( + requestTimeout = 3 * time.Second + maxAttempts = 3 + retryBackoff = 300 * time.Millisecond +) + +// Match result statuses accepted by the main-server. +const ( + StatusPlayer1Won = "player1_won" + StatusPlayer2Won = "player2_won" + StatusDraw = "draw" + StatusAbandoned = "abandoned" +) + +// reportPayload is the JSON body of the result report. Field order matters: +// it is part of the signed payload and must stay in sync with the tests of +// both servers. +type reportPayload struct { + Status string `json:"status"` + DurationSeconds int64 `json:"duration_seconds"` +} + +// Reporter posts match results to the main-server. +type Reporter struct { + origin string // scheme + host, e.g. "http://localhost:3000" + basePath string // optional path prefix from MAIN_SERVER_URL, no trailing slash + secret []byte + client *http.Client + log *slog.Logger +} + +// NewReporter creates a Reporter for the main-server at the given base URL. +// An optional path prefix (e.g. "https://example.com/main") is kept and +// included in the signed path. +func NewReporter(baseURL string, secret []byte, log *slog.Logger) (*Reporter, error) { + u, err := url.Parse(baseURL) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return nil, fmt.Errorf("invalid MAIN_SERVER_URL %q: must be an absolute http(s) URL", baseURL) + } + if u.RawQuery != "" || u.Fragment != "" { + return nil, fmt.Errorf("invalid MAIN_SERVER_URL %q: query and fragment are not allowed", baseURL) + } + if log == nil { + log = slog.Default() + } + return &Reporter{ + origin: u.Scheme + "://" + u.Host, + basePath: strings.TrimSuffix(u.Path, "/"), + secret: secret, + client: &http.Client{Timeout: requestTimeout}, + log: log, + }, nil +} + +// Result is the outcome of a single match. It is an alias so that +// *Reporter implements game.Reporter without converting types. +type Result = game.MatchResult + +// ReportMatchResult POSTs the result to +// /api/internal/matches//result. It retries up to maxAttempts +// times on transport errors and non-2xx responses. +func (r *Reporter) ReportMatchResult(ctx context.Context, result Result) error { + body, err := json.Marshal(reportPayload{Status: result.Status, DurationSeconds: result.DurationSeconds}) + if err != nil { + return fmt.Errorf("marshal report: %w", err) + } + path := r.basePath + "/api/internal/matches/" + url.PathEscape(result.MatchID) + "/result" + + var lastErr error + for attempt := 1; attempt <= maxAttempts; attempt++ { + lastErr = r.post(ctx, path, body) + if lastErr == nil { + return nil + } + r.log.Warn("match result report failed", + "match", result.MatchID, "attempt", attempt, "err", lastErr) + if attempt < maxAttempts { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(retryBackoff): + } + } + } + return fmt.Errorf("reporting match result after %d attempts: %w", maxAttempts, lastErr) +} + +func (r *Reporter) post(ctx context.Context, path string, body []byte) error { + timestamp := time.Now().Unix() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.origin+path, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Request-Timestamp", strconv.FormatInt(timestamp, 10)) + req.Header.Set("X-Request-Signature", "sha256="+Sign(timestamp, path, body, r.secret)) + + resp, err := r.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + data, _ := io.ReadAll(io.LimitReader(resp.Body, 4*1024)) + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return fmt.Errorf("main-server returned %d: %s", resp.StatusCode, bytes.TrimSpace(data)) + } + return nil +} + +// Sign computes the hex HMAC-SHA256 of ".." with the +// shared secret. It must match InternalSignatureService on the main-server. +func Sign(timestamp int64, path string, body []byte, secret []byte) string { + mac := hmac.New(sha256.New, secret) + mac.Write([]byte(strconv.FormatInt(timestamp, 10))) + mac.Write([]byte(".")) + mac.Write([]byte(path)) + mac.Write([]byte(".")) + mac.Write(body) + return hex.EncodeToString(mac.Sum(nil)) +} diff --git a/game-server/internal/mainserver/reporter_test.go b/game-server/internal/mainserver/reporter_test.go new file mode 100644 index 0000000..14467f6 --- /dev/null +++ b/game-server/internal/mainserver/reporter_test.go @@ -0,0 +1,146 @@ +package mainserver + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strconv" + "sync/atomic" + "testing" + "time" +) + +const testSecret = "test-secret-key-base" + +// known vector shared with the main-server (Ruby) test suite +const testVector = "e0a7f8b5508639b1afe604b41f00070dd282d02b6444db5b4856959f175e8361" + +func TestSignMatchesSharedVector(t *testing.T) { + body := `{"status":"player1_won","duration_seconds":42}` + path := "/api/internal/matches/abc/result" + got := Sign(1_700_000_000, path, []byte(body), []byte(testSecret)) + if got != testVector { + t.Fatalf("Sign = %q, want %q", got, testVector) + } +} + +func newTestReporter(t *testing.T, baseURL string) *Reporter { + t.Helper() + rep, err := NewReporter(baseURL, []byte(testSecret), slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewReporter: %v", err) + } + return rep +} + +func TestReportMatchResult(t *testing.T) { + var gotPath, gotTS, gotSig, gotBody string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, _ := io.ReadAll(r.Body) + gotPath = r.URL.Path + gotTS = r.Header.Get("X-Request-Timestamp") + gotSig = r.Header.Get("X-Request-Signature") + gotBody = string(data) + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + rep := newTestReporter(t, srv.URL) + err := rep.ReportMatchResult(context.Background(), Result{ + MatchID: "abc", + Status: StatusPlayer1Won, + DurationSeconds: 42, + }) + if err != nil { + t.Fatalf("ReportMatchResult: %v", err) + } + + if gotPath != "/api/internal/matches/abc/result" { + t.Fatalf("path = %q", gotPath) + } + if gotBody != `{"status":"player1_won","duration_seconds":42}` { + t.Fatalf("body = %q", gotBody) + } + ts, err := strconv.ParseInt(gotTS, 10, 64) + if err != nil { + t.Fatalf("timestamp header = %q: %v", gotTS, err) + } + if now := time.Now().Unix(); ts < now-60 || ts > now+60 { + t.Fatalf("timestamp = %d, want close to %d", ts, now) + } + want := "sha256=" + Sign(ts, gotPath, []byte(gotBody), []byte(testSecret)) + if gotSig != want { + t.Fatalf("signature = %q, want %q", gotSig, want) + } +} + +func TestReportMatchResultRetriesUntilSuccess(t *testing.T) { + var attempts atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if attempts.Add(1) < 3 { + w.WriteHeader(http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + rep := newTestReporter(t, srv.URL) + err := rep.ReportMatchResult(context.Background(), Result{MatchID: "abc", Status: StatusDraw}) + if err != nil { + t.Fatalf("ReportMatchResult: %v", err) + } + if got := attempts.Load(); got != 3 { + t.Fatalf("attempts = %d, want 3", got) + } +} + +func TestReportMatchResultFailsAfterRetries(t *testing.T) { + var attempts atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempts.Add(1) + w.WriteHeader(http.StatusConflict) + })) + defer srv.Close() + + rep := newTestReporter(t, srv.URL) + err := rep.ReportMatchResult(context.Background(), Result{MatchID: "abc", Status: StatusAbandoned}) + if err == nil { + t.Fatal("expected an error after all attempts failed") + } + if got := attempts.Load(); got != 3 { + t.Fatalf("attempts = %d, want 3", got) + } +} + +func TestNewReporterRejectsInvalidURL(t *testing.T) { + for _, url := range []string{"", "localhost:3000", "http://", "::", "ftp://example.com", "http://example.com/?a=b"} { + if _, err := NewReporter(url, []byte(testSecret), nil); err == nil { + t.Fatalf("NewReporter(%q): expected an error", url) + } + } +} + +func TestReportMatchResultWithPathPrefix(t *testing.T) { + var gotPath string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + rep := newTestReporter(t, srv.URL+"/main/") + err := rep.ReportMatchResult(context.Background(), Result{ + MatchID: "abc", + Status: StatusPlayer1Won, + DurationSeconds: 1, + }) + if err != nil { + t.Fatalf("ReportMatchResult: %v", err) + } + if gotPath != "/main/api/internal/matches/abc/result" { + t.Fatalf("path = %q, want /main/api/internal/matches/abc/result", gotPath) + } +}