153 lines
4.7 KiB
Go
153 lines
4.7 KiB
Go
// 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))
|
|
}
|