add match result reporting to game-server
This commit is contained in:
@@ -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
|
||||
//
|
||||
// "<unix timestamp>.<path>.<raw body>"
|
||||
//
|
||||
// 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/<match_id>/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 "<timestamp>.<path>.<body>" 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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user