Files
galaxy-game/gamemaster/internal/service/orderput/service.go
T
2026-05-03 07:59:03 +02:00

362 lines
12 KiB
Go

// Package orderput implements the player-order hot-path service owned by
// Game Master. It accepts a verified `(game_id, user_id, payload)`
// envelope from Edge Gateway, authorises the caller against the membership
// cache, resolves `actor=race_name` from `player_mappings`, reshapes the
// payload to the engine `CommandRequest{actor, cmd}` schema, and forwards
// the call to the engine `/api/v1/order` endpoint.
//
// Lifecycle and error semantics follow `gamemaster/README.md §Hot Path →
// Player commands and orders`. Design rationale is captured in
// `gamemaster/docs/stage16-membership-cache-and-invalidation.md`.
package orderput
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 = "order"
membershipStatusActive = "active"
payloadCommandsKey = "commands"
payloadCmdKey = "cmd"
payloadActorKey = "actor"
)
// Input stores the per-call arguments for one order-put operation. The
// shape mirrors `PutOrdersRequest` from
// `gamemaster/api/internal-openapi.yaml` plus the verified user identity
// captured from the `X-User-ID` header by the Stage 19 handler.
type Input struct {
// GameID identifies the platform game the order targets.
GameID string
// UserID identifies the platform user submitting the order. The
// service derives `actor=race_name` from this value via
// `player_mappings`.
UserID string
// Payload stores the raw `PutOrdersRequest` body. The service
// rewrites it to the engine `CommandRequest{actor, cmd}` shape
// before forwarding.
Payload json.RawMessage
}
// 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 len(input.Payload) == 0 {
return fmt.Errorf("payload must not be empty")
}
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 and the runtime status.
RuntimeRecords ports.RuntimeRecordStore
// PlayerMappings resolves `(game_id, user_id) → race_name`.
PlayerMappings ports.PlayerMappingStore
// Membership authorises the caller. Hot-path services share one
// cache instance with `commandexecute` and `reportget`.
Membership *membership.Cache
// Engine forwards the reshaped payload to `/api/v1/order`.
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 order-put 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 order put service: nil runtime records")
case deps.PlayerMappings == nil:
return nil, errors.New("new order put service: nil player mappings")
case deps.Membership == nil:
return nil, errors.New("new order put service: nil membership cache")
case deps.Engine == nil:
return nil, errors.New("new order put service: nil engine client")
case deps.Telemetry == nil:
return nil, errors.New("new order put 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.orderput")
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 order-put 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("order put: nil service")
}
if ctx == nil {
return Result{}, errors.New("order put: 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
}
if record.Status != runtime.StatusRunning {
message := fmt.Sprintf("runtime status is %q, expected %q", record.Status, runtime.StatusRunning)
return service.recordFailure(ctx, input, ErrorCodeRuntimeNotRunning, message, nil), nil
}
mapping, result, ok := service.authorise(ctx, input)
if !ok {
return result, nil
}
payload, err := rewriteOrderPayload(input.Payload, mapping.RaceName)
if err != nil {
return service.recordFailure(ctx, input, ErrorCodeInvalidRequest, err.Error(), nil), nil
}
body, engineErr := service.callEngine(ctx, record.EngineEndpoint, payload)
if engineErr != nil {
errorCode := classifyEngineError(engineErr)
message := fmt.Sprintf("engine order: %s", engineErr.Error())
var bodyForCaller json.RawMessage
if errorCode == ErrorCodeEngineValidationError {
bodyForCaller = body
}
return service.recordFailure(ctx, input, errorCode, message, bodyForCaller), nil
}
service.telemetry.RecordOrderPutOutcome(ctx,
string(operation.OutcomeSuccess), "")
logArgs := []any{
"game_id", input.GameID,
"user_id", input.UserID,
"actor", mapping.RaceName,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.InfoContext(ctx, "order put 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.
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 orders", 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 reshaped payload to the engine and records the
// wall-clock latency under the `order` op label.
func (service *Service) callEngine(ctx context.Context, baseURL string, payload json.RawMessage) (json.RawMessage, error) {
start := service.clock()
body, err := service.engine.PutOrders(ctx, baseURL, payload)
service.telemetry.RecordEngineCall(ctx, engineCallOp, service.clock().Sub(start))
return body, err
}
// classifyEngineError maps the engine port sentinels to the order-put
// 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.RecordOrderPutOutcome(ctx,
string(operation.OutcomeFailure), errorCode)
logArgs := []any{
"game_id", input.GameID,
"user_id", input.UserID,
"error_code", errorCode,
"error_message", errorMessage,
}
logArgs = append(logArgs, logging.ContextAttrs(ctx)...)
service.logger.WarnContext(ctx, "order put rejected", logArgs...)
return Result{
Outcome: operation.OutcomeFailure,
ErrorCode: errorCode,
ErrorMessage: errorMessage,
RawResponse: rawResponse,
}
}
// rewriteOrderPayload reshapes the GM `PutOrdersRequest` body
// (`{commands:[…]}`) to the engine `CommandRequest` body
// (`{actor:<raceName>, cmd:[…]}`). Every other top-level key is
// discarded; GM never trusts caller-supplied envelope fields per the
// README §Hot Path rule. Returns an error when the payload is not a JSON
// object or the `commands` field is missing or not an array.
func rewriteOrderPayload(payload json.RawMessage, raceName string) (json.RawMessage, error) {
var fields map[string]json.RawMessage
if err := json.Unmarshal(payload, &fields); err != nil {
return nil, fmt.Errorf("payload must decode as a JSON object: %w", err)
}
commands, ok := fields[payloadCommandsKey]
if !ok {
return nil, fmt.Errorf("payload missing required %q field", payloadCommandsKey)
}
var commandList []json.RawMessage
if err := json.Unmarshal(commands, &commandList); err != nil {
return nil, fmt.Errorf("payload %q field must decode as an array: %w", payloadCommandsKey, err)
}
actor, err := json.Marshal(raceName)
if err != nil {
return nil, fmt.Errorf("marshal actor: %w", err)
}
out := map[string]json.RawMessage{
payloadActorKey: actor,
payloadCmdKey: commands,
}
encoded, err := json.Marshal(out)
if err != nil {
return nil, fmt.Errorf("marshal engine payload: %w", err)
}
_ = commandList // ensure the array shape is validated before forwarding
return encoded, nil
}