feat: gamemaster
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
// Package reportget implements the per-player turn-report hot-path
|
||||
// service owned by Game Master. It accepts a verified `(game_id, user_id,
|
||||
// turn)` envelope from Edge Gateway, authorises the caller against the
|
||||
// membership cache, resolves `race_name` from `player_mappings`, and
|
||||
// forwards `GET /api/v1/report?player={race_name}&turn={turn}` to the
|
||||
// engine.
|
||||
//
|
||||
// Lifecycle and error semantics follow `gamemaster/README.md §Hot Path →
|
||||
// Reports`. Unlike commandexecute and orderput, the report service does
|
||||
// not require `runtime_records.status = running`: reports may be served
|
||||
// against any runtime that exists in the table, allowing post-finish
|
||||
// inspection. Design rationale (decision D1) is captured in
|
||||
// `gamemaster/docs/stage16-membership-cache-and-invalidation.md`.
|
||||
package reportget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"galaxy/gamemaster/internal/domain/operation"
|
||||
"galaxy/gamemaster/internal/domain/playermapping"
|
||||
"galaxy/gamemaster/internal/domain/runtime"
|
||||
"galaxy/gamemaster/internal/logging"
|
||||
"galaxy/gamemaster/internal/ports"
|
||||
"galaxy/gamemaster/internal/service/membership"
|
||||
"galaxy/gamemaster/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
engineCallOp = "report"
|
||||
|
||||
membershipStatusActive = "active"
|
||||
)
|
||||
|
||||
// Input stores the per-call arguments for one report-get operation.
|
||||
type Input struct {
|
||||
// GameID identifies the platform game whose report is being read.
|
||||
GameID string
|
||||
|
||||
// UserID identifies the platform user submitting the request. The
|
||||
// service derives `race_name` from this value via `player_mappings`
|
||||
// before calling the engine.
|
||||
UserID string
|
||||
|
||||
// Turn identifies the turn number to read. Must be non-negative;
|
||||
// zero requests the initial state report.
|
||||
Turn int
|
||||
}
|
||||
|
||||
// Validate reports whether input carries the structural invariants the
|
||||
// service requires before any store is touched.
|
||||
func (input Input) Validate() error {
|
||||
if strings.TrimSpace(input.GameID) == "" {
|
||||
return fmt.Errorf("game id must not be empty")
|
||||
}
|
||||
if strings.TrimSpace(input.UserID) == "" {
|
||||
return fmt.Errorf("user id must not be empty")
|
||||
}
|
||||
if input.Turn < 0 {
|
||||
return fmt.Errorf("turn must not be negative, got %d", input.Turn)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Result stores the deterministic outcome of one Handle call.
|
||||
type Result struct {
|
||||
// Outcome reports whether the operation completed (success) or
|
||||
// produced a stable failure code.
|
||||
Outcome operation.Outcome
|
||||
|
||||
// ErrorCode stores the stable error code on failure. Empty on
|
||||
// success.
|
||||
ErrorCode string
|
||||
|
||||
// ErrorMessage stores the operator-readable detail on failure.
|
||||
// Empty on success.
|
||||
ErrorMessage string
|
||||
|
||||
// RawResponse stores the engine response body. Populated on success
|
||||
// and on `engine_validation_error`. Empty on every other terminal
|
||||
// branch.
|
||||
RawResponse json.RawMessage
|
||||
}
|
||||
|
||||
// IsSuccess reports whether the result represents a successful operation.
|
||||
func (result Result) IsSuccess() bool {
|
||||
return result.Outcome == operation.OutcomeSuccess
|
||||
}
|
||||
|
||||
// Dependencies groups the collaborators required by Service.
|
||||
type Dependencies struct {
|
||||
// RuntimeRecords loads the engine endpoint.
|
||||
RuntimeRecords ports.RuntimeRecordStore
|
||||
|
||||
// PlayerMappings resolves `(game_id, user_id) → race_name`.
|
||||
PlayerMappings ports.PlayerMappingStore
|
||||
|
||||
// Membership authorises the caller.
|
||||
Membership *membership.Cache
|
||||
|
||||
// Engine forwards `GET /api/v1/report` calls.
|
||||
Engine ports.EngineClient
|
||||
|
||||
// Telemetry records the per-outcome counter and the engine-call
|
||||
// latency histogram.
|
||||
Telemetry *telemetry.Runtime
|
||||
|
||||
// Logger records structured service-level events. Defaults to
|
||||
// `slog.Default()` when nil.
|
||||
Logger *slog.Logger
|
||||
|
||||
// Clock supplies the wall-clock used for engine-call latency.
|
||||
// Defaults to `time.Now` when nil.
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service executes the report-get hot-path operation.
|
||||
type Service struct {
|
||||
runtimeRecords ports.RuntimeRecordStore
|
||||
playerMappings ports.PlayerMappingStore
|
||||
membership *membership.Cache
|
||||
engine ports.EngineClient
|
||||
telemetry *telemetry.Runtime
|
||||
logger *slog.Logger
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService constructs one Service from deps.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
switch {
|
||||
case deps.RuntimeRecords == nil:
|
||||
return nil, errors.New("new report get service: nil runtime records")
|
||||
case deps.PlayerMappings == nil:
|
||||
return nil, errors.New("new report get service: nil player mappings")
|
||||
case deps.Membership == nil:
|
||||
return nil, errors.New("new report get service: nil membership cache")
|
||||
case deps.Engine == nil:
|
||||
return nil, errors.New("new report get service: nil engine client")
|
||||
case deps.Telemetry == nil:
|
||||
return nil, errors.New("new report get service: nil telemetry runtime")
|
||||
}
|
||||
|
||||
clock := deps.Clock
|
||||
if clock == nil {
|
||||
clock = time.Now
|
||||
}
|
||||
logger := deps.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
logger = logger.With("service", "gamemaster.reportget")
|
||||
|
||||
return &Service{
|
||||
runtimeRecords: deps.RuntimeRecords,
|
||||
playerMappings: deps.PlayerMappings,
|
||||
membership: deps.Membership,
|
||||
engine: deps.Engine,
|
||||
telemetry: deps.Telemetry,
|
||||
logger: logger,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes one report-get operation end-to-end. The Go-level error
|
||||
// return is reserved for non-business failures (nil context, nil
|
||||
// receiver). Every business outcome flows through Result.
|
||||
func (service *Service) Handle(ctx context.Context, input Input) (Result, error) {
|
||||
if service == nil {
|
||||
return Result{}, errors.New("report get: nil service")
|
||||
}
|
||||
if ctx == nil {
|
||||
return Result{}, errors.New("report get: nil context")
|
||||
}
|
||||
|
||||
if err := input.Validate(); err != nil {
|
||||
return service.recordFailure(ctx, input, ErrorCodeInvalidRequest, err.Error(), nil), nil
|
||||
}
|
||||
|
||||
record, result, ok := service.loadRecord(ctx, input)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
mapping, result, ok := service.authorise(ctx, input)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
body, engineErr := service.callEngine(ctx, record.EngineEndpoint, mapping.RaceName, input.Turn)
|
||||
if engineErr != nil {
|
||||
errorCode := classifyEngineError(engineErr)
|
||||
message := fmt.Sprintf("engine report: %s", engineErr.Error())
|
||||
var bodyForCaller json.RawMessage
|
||||
if errorCode == ErrorCodeEngineValidationError {
|
||||
bodyForCaller = body
|
||||
}
|
||||
return service.recordFailure(ctx, input, errorCode, message, bodyForCaller), nil
|
||||
}
|
||||
|
||||
service.telemetry.RecordReportGetOutcome(ctx,
|
||||
string(operation.OutcomeSuccess), "")
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"user_id", input.UserID,
|
||||
"actor", mapping.RaceName,
|
||||
"turn", input.Turn,
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.InfoContext(ctx, "report get succeeded", logArgs...)
|
||||
|
||||
return Result{
|
||||
Outcome: operation.OutcomeSuccess,
|
||||
RawResponse: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadRecord reads the runtime record and maps store errors to
|
||||
// orchestrator outcomes. ok=false means the flow stops with the returned
|
||||
// Result. Reports tolerate any non-deleted runtime status; the running
|
||||
// guard from commandexecute / orderput is intentionally absent.
|
||||
func (service *Service) loadRecord(ctx context.Context, input Input) (runtime.RuntimeRecord, Result, bool) {
|
||||
record, err := service.runtimeRecords.Get(ctx, input.GameID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return record, Result{}, true
|
||||
case errors.Is(err, runtime.ErrNotFound):
|
||||
return runtime.RuntimeRecord{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeRuntimeNotFound, "runtime record does not exist", nil), false
|
||||
default:
|
||||
return runtime.RuntimeRecord{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get runtime record: %s", err.Error()), nil), false
|
||||
}
|
||||
}
|
||||
|
||||
// authorise resolves the membership status and the player mapping for
|
||||
// the caller. ok=false means the flow stops with the returned Result.
|
||||
func (service *Service) authorise(ctx context.Context, input Input) (playermapping.PlayerMapping, Result, bool) {
|
||||
status, err := service.membership.Resolve(ctx, input.GameID, input.UserID)
|
||||
if err != nil {
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("resolve membership: %s", err.Error()), nil), false
|
||||
}
|
||||
if status != membershipStatusActive {
|
||||
message := fmt.Sprintf("membership status %q does not authorise reports", status)
|
||||
if status == "" {
|
||||
message = "user is not a member of the game"
|
||||
}
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeForbidden, message, nil), false
|
||||
}
|
||||
|
||||
mapping, err := service.playerMappings.Get(ctx, input.GameID, input.UserID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return mapping, Result{}, true
|
||||
case errors.Is(err, playermapping.ErrNotFound):
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeForbidden, "player mapping not installed for active member", nil), false
|
||||
default:
|
||||
return playermapping.PlayerMapping{}, service.recordFailure(ctx, input,
|
||||
ErrorCodeServiceUnavailable, fmt.Sprintf("get player mapping: %s", err.Error()), nil), false
|
||||
}
|
||||
}
|
||||
|
||||
// callEngine forwards the read to the engine and records the wall-clock
|
||||
// latency under the `report` op label.
|
||||
func (service *Service) callEngine(ctx context.Context, baseURL, raceName string, turn int) (json.RawMessage, error) {
|
||||
start := service.clock()
|
||||
body, err := service.engine.GetReport(ctx, baseURL, raceName, turn)
|
||||
service.telemetry.RecordEngineCall(ctx, engineCallOp, service.clock().Sub(start))
|
||||
return body, err
|
||||
}
|
||||
|
||||
// classifyEngineError maps the engine port sentinels to the report-get
|
||||
// stable error codes.
|
||||
func classifyEngineError(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ports.ErrEngineValidation):
|
||||
return ErrorCodeEngineValidationError
|
||||
case errors.Is(err, ports.ErrEngineProtocolViolation):
|
||||
return ErrorCodeEngineProtocolViolation
|
||||
case errors.Is(err, ports.ErrEngineUnreachable):
|
||||
return ErrorCodeEngineUnreachable
|
||||
default:
|
||||
return ErrorCodeEngineUnreachable
|
||||
}
|
||||
}
|
||||
|
||||
// recordFailure emits the service-level outcome counter and a structured
|
||||
// log entry, then returns the Result the caller surfaces.
|
||||
func (service *Service) recordFailure(ctx context.Context, input Input, errorCode, errorMessage string, rawResponse json.RawMessage) Result {
|
||||
service.telemetry.RecordReportGetOutcome(ctx,
|
||||
string(operation.OutcomeFailure), errorCode)
|
||||
logArgs := []any{
|
||||
"game_id", input.GameID,
|
||||
"user_id", input.UserID,
|
||||
"turn", input.Turn,
|
||||
"error_code", errorCode,
|
||||
"error_message", errorMessage,
|
||||
}
|
||||
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
|
||||
service.logger.WarnContext(ctx, "report get rejected", logArgs...)
|
||||
return Result{
|
||||
Outcome: operation.OutcomeFailure,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
RawResponse: rawResponse,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user