refactor(game): lock-free storage, remove /command, flatten engine wrapper
Three-stage refactor of the game-engine plumbing (game logic untouched): Stage 1 — lock-free persistence + admin serialisation. Remove the file lock from repo/fs (the .lock file, the Read/Write-vs-*Safe duality and the dead ReadSafe polling) and replace the two-step rename with a single atomic rename so concurrent reads are torn-free without a lock. Serialise the state-mutating admin writers (init/turn/banish) with one shared router LimitMiddleware, rewritten to block on the request context instead of a racy shared 100ms timer. Stage 2 — remove the obsolete immediate-command path end to end. Players submit through PUT /api/v1/order; the legacy PUT /api/v1/command path is deleted across game (route, handler, 24 command factories, Ctrl), backend (Commands handler/route, engineclient.ExecuteCommands), gateway (dispatch + executeUserGamesCommand + routing entry), the FlatBuffers/model contract (UserGamesCommand[Response]) and transcoder, plus every affected OpenAPI/README/FUNCTIONAL/ARCHITECTURE doc. The integration proxy test is converted to the order path. Stage 3 — flatten the REST->engine wrapper. Replace the executor adapter, the controller package functions and RepoController with one concrete controller.Service; drop the single-implementation Repo and Storage interfaces (repo.Repo / fs.FS are now concrete). Handlers depend on a thin handler.Engine seam and own the domain->REST projection; storage is resolved once at startup instead of per request. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -22,8 +22,7 @@
|
||||
// Game-state runtime rejections that depend on the current state
|
||||
// snapshot: entity-not-found, not-owned, in-use, ships-busy,
|
||||
// insufficient resources, send/upgrade/cargo dependencies. These
|
||||
// surface as per-command `cmdErrorCode` on PUT /api/v1/order
|
||||
// (and only escape as HTTP 400 from PUT /api/v1/command).
|
||||
// surface as per-command `cmdErrorCode` on PUT /api/v1/order.
|
||||
//
|
||||
// Code 0 represents "applied without error" and is reserved as the
|
||||
// successful per-command outcome on CommandMeta.Result. Code -1
|
||||
@@ -115,8 +114,7 @@ func IsInputCode(code int) bool { return code >= 2000 && code < 3000 }
|
||||
|
||||
// IsGameStateCode reports whether code belongs to the game-state /
|
||||
// per-command rejection shelf (3xxx). On PUT /api/v1/order these are
|
||||
// recorded into CommandMeta.CmdErrCode; on PUT /api/v1/command they
|
||||
// map to HTTP 400.
|
||||
// recorded into CommandMeta.CmdErrCode.
|
||||
func IsGameStateCode(code int) bool { return code >= 3000 && code < 4000 }
|
||||
|
||||
func GenericErrorText(code int) string {
|
||||
|
||||
@@ -6,12 +6,6 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MessageTypeUserGamesCommand is the authenticated gateway message type
|
||||
// used to send a batch of in-game commands to the engine through
|
||||
// `POST /api/v1/user/games/{game_id}/commands`. The signed payload is
|
||||
// a FlatBuffers `order.UserGamesCommand`.
|
||||
const MessageTypeUserGamesCommand = "user.games.command"
|
||||
|
||||
// MessageTypeUserGamesOrder is the authenticated gateway message type
|
||||
// used to validate / store a batch of in-game orders through
|
||||
// `POST /api/v1/user/games/{game_id}/orders`. The signed payload is a
|
||||
@@ -24,22 +18,12 @@ const MessageTypeUserGamesOrder = "user.games.order"
|
||||
// signed payload is a FlatBuffers `order.UserGamesOrderGet`.
|
||||
const MessageTypeUserGamesOrderGet = "user.games.order.get"
|
||||
|
||||
// UserGamesCommand is the typed payload of MessageTypeUserGamesCommand.
|
||||
// `GameID` selects the running engine container; `Commands` is the
|
||||
// player command batch executed atomically by the engine. The `Actor`
|
||||
// field present in the engine's JSON shape is rebuilt by backend from
|
||||
// the runtime player mapping — clients never carry it.
|
||||
type UserGamesCommand struct {
|
||||
// GameID identifies the running game for this batch.
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
|
||||
// Commands is the player command batch.
|
||||
Commands []DecodableCommand `json:"cmd"`
|
||||
}
|
||||
|
||||
// UserGamesOrder is the typed payload of MessageTypeUserGamesOrder.
|
||||
// Mirrors `UserGamesCommand` plus an `UpdatedAt` field that lets the
|
||||
// engine reject stale order submissions.
|
||||
// `GameID` selects the running engine container; `Commands` is the
|
||||
// player order batch; `UpdatedAt` lets the engine reject stale order
|
||||
// submissions. The `Actor` field present in the engine's JSON shape is
|
||||
// rebuilt by backend from the runtime player mapping — clients never
|
||||
// carry it.
|
||||
type UserGamesOrder struct {
|
||||
// GameID identifies the running game for this batch.
|
||||
GameID uuid.UUID `json:"game_id"`
|
||||
|
||||
@@ -4,13 +4,10 @@ import "encoding/json"
|
||||
|
||||
type Command struct {
|
||||
Actor string `json:"actor" binding:"notblank"`
|
||||
// Commands carries the engine-bound payload for either the
|
||||
// command (`PUT /api/v1/command`, immediate) or the order
|
||||
// (`PUT /api/v1/order`, validate-and-store) path. The order
|
||||
// path treats an empty array as "the player has no orders for
|
||||
// this turn" and stores it. The command handler still rejects
|
||||
// an empty array by hand because immediate execution of a
|
||||
// no-op makes no sense.
|
||||
// Commands carries the engine-bound payload for the order
|
||||
// (`PUT /api/v1/order`, validate-and-store) path. An empty array
|
||||
// means "the player has no orders for this turn" and is stored
|
||||
// as-is.
|
||||
Commands []json.RawMessage `json:"cmd"`
|
||||
}
|
||||
|
||||
|
||||
@@ -201,31 +201,15 @@ table CommandItem {
|
||||
cmd_error_message: string;
|
||||
}
|
||||
|
||||
// UserGamesCommand is the signed-gRPC request payload for
|
||||
// `MessageTypeUserGamesCommand`. game_id selects the target running
|
||||
// game; gateway re-encodes commands into the engine JSON shape and
|
||||
// forwards through `POST /api/v1/user/games/{game_id}/commands`.
|
||||
table UserGamesCommand {
|
||||
game_id: common.UUID (required);
|
||||
commands: [CommandItem];
|
||||
}
|
||||
|
||||
// UserGamesOrder is the signed-gRPC request payload for
|
||||
// `MessageTypeUserGamesOrder`. Identical to UserGamesCommand but
|
||||
// carries `updated_at` so the order-validate path can reject stale
|
||||
// submissions.
|
||||
// `MessageTypeUserGamesOrder`. game_id selects the target running game;
|
||||
// `updated_at` lets the order-validate path reject stale submissions.
|
||||
table UserGamesOrder {
|
||||
game_id: common.UUID (required);
|
||||
updated_at: int64;
|
||||
commands: [CommandItem];
|
||||
}
|
||||
|
||||
// UserGamesCommandResponse is the success acknowledgement returned
|
||||
// for `MessageTypeUserGamesCommand`. The engine answers with
|
||||
// `204 No Content` on success, so the FB shape is intentionally empty
|
||||
// — kept as a typed envelope for future extension.
|
||||
table UserGamesCommandResponse {}
|
||||
|
||||
// UserGamesOrderResponse mirrors the engine's `PUT /api/v1/order`
|
||||
// success body: it echoes the stored order back to the caller with
|
||||
// the engine-assigned `updated_at` timestamp and per-command
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||
|
||||
package order
|
||||
|
||||
import (
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
|
||||
common "galaxy/schema/fbs/common"
|
||||
)
|
||||
|
||||
type UserGamesCommand struct {
|
||||
_tab flatbuffers.Table
|
||||
}
|
||||
|
||||
func GetRootAsUserGamesCommand(buf []byte, offset flatbuffers.UOffsetT) *UserGamesCommand {
|
||||
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||
x := &UserGamesCommand{}
|
||||
x.Init(buf, n+offset)
|
||||
return x
|
||||
}
|
||||
|
||||
func FinishUserGamesCommandBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||
builder.Finish(offset)
|
||||
}
|
||||
|
||||
func GetSizePrefixedRootAsUserGamesCommand(buf []byte, offset flatbuffers.UOffsetT) *UserGamesCommand {
|
||||
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||
x := &UserGamesCommand{}
|
||||
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||
return x
|
||||
}
|
||||
|
||||
func FinishSizePrefixedUserGamesCommandBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||
builder.FinishSizePrefixed(offset)
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommand) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||
rcv._tab.Bytes = buf
|
||||
rcv._tab.Pos = i
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommand) Table() flatbuffers.Table {
|
||||
return rcv._tab
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommand) GameId(obj *common.UUID) *common.UUID {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
|
||||
if o != 0 {
|
||||
x := o + rcv._tab.Pos
|
||||
if obj == nil {
|
||||
obj = new(common.UUID)
|
||||
}
|
||||
obj.Init(rcv._tab.Bytes, x)
|
||||
return obj
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommand) Commands(obj *CommandItem, j int) bool {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||
if o != 0 {
|
||||
x := rcv._tab.Vector(o)
|
||||
x += flatbuffers.UOffsetT(j) * 4
|
||||
x = rcv._tab.Indirect(x)
|
||||
obj.Init(rcv._tab.Bytes, x)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommand) CommandsLength() int {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||
if o != 0 {
|
||||
return rcv._tab.VectorLen(o)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func UserGamesCommandStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(2)
|
||||
}
|
||||
func UserGamesCommandAddGameId(builder *flatbuffers.Builder, gameId flatbuffers.UOffsetT) {
|
||||
builder.PrependStructSlot(0, flatbuffers.UOffsetT(gameId), 0)
|
||||
}
|
||||
func UserGamesCommandAddCommands(builder *flatbuffers.Builder, commands flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(commands), 0)
|
||||
}
|
||||
func UserGamesCommandStartCommandsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
|
||||
return builder.StartVector(4, numElems, 4)
|
||||
}
|
||||
func UserGamesCommandEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
|
||||
|
||||
package order
|
||||
|
||||
import (
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
)
|
||||
|
||||
type UserGamesCommandResponse struct {
|
||||
_tab flatbuffers.Table
|
||||
}
|
||||
|
||||
func GetRootAsUserGamesCommandResponse(buf []byte, offset flatbuffers.UOffsetT) *UserGamesCommandResponse {
|
||||
n := flatbuffers.GetUOffsetT(buf[offset:])
|
||||
x := &UserGamesCommandResponse{}
|
||||
x.Init(buf, n+offset)
|
||||
return x
|
||||
}
|
||||
|
||||
func FinishUserGamesCommandResponseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||
builder.Finish(offset)
|
||||
}
|
||||
|
||||
func GetSizePrefixedRootAsUserGamesCommandResponse(buf []byte, offset flatbuffers.UOffsetT) *UserGamesCommandResponse {
|
||||
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
|
||||
x := &UserGamesCommandResponse{}
|
||||
x.Init(buf, n+offset+flatbuffers.SizeUint32)
|
||||
return x
|
||||
}
|
||||
|
||||
func FinishSizePrefixedUserGamesCommandResponseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
|
||||
builder.FinishSizePrefixed(offset)
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommandResponse) Init(buf []byte, i flatbuffers.UOffsetT) {
|
||||
rcv._tab.Bytes = buf
|
||||
rcv._tab.Pos = i
|
||||
}
|
||||
|
||||
func (rcv *UserGamesCommandResponse) Table() flatbuffers.Table {
|
||||
return rcv._tab
|
||||
}
|
||||
|
||||
func UserGamesCommandResponseStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(0)
|
||||
}
|
||||
func UserGamesCommandResponseEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
+3
-88
@@ -931,72 +931,6 @@ func cloneStringPointer(value *string) *string {
|
||||
return &cloned
|
||||
}
|
||||
|
||||
// UserGamesCommandToPayload converts model.UserGamesCommand to
|
||||
// FlatBuffers bytes suitable for the authenticated gateway transport.
|
||||
// `GameID` is required.
|
||||
func UserGamesCommandToPayload(req *model.UserGamesCommand) ([]byte, error) {
|
||||
if req == nil {
|
||||
return nil, errors.New("encode user games command payload: request is nil")
|
||||
}
|
||||
|
||||
builder := flatbuffers.NewBuilder(1024)
|
||||
commandsVec, err := encodeCommandItemVector(builder, req.Commands, "user games command")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fbs.UserGamesCommandStart(builder)
|
||||
hi, lo := uuidToHiLo(req.GameID)
|
||||
fbs.UserGamesCommandAddGameId(builder, commonfbs.CreateUUID(builder, hi, lo))
|
||||
if commandsVec != 0 {
|
||||
fbs.UserGamesCommandAddCommands(builder, commandsVec)
|
||||
}
|
||||
offset := fbs.UserGamesCommandEnd(builder)
|
||||
fbs.FinishUserGamesCommandBuffer(builder, offset)
|
||||
|
||||
return builder.FinishedBytes(), nil
|
||||
}
|
||||
|
||||
// PayloadToUserGamesCommand converts FlatBuffers payload bytes into
|
||||
// model.UserGamesCommand.
|
||||
func PayloadToUserGamesCommand(data []byte) (result *model.UserGamesCommand, err error) {
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("decode user games command payload: data is empty")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
result = nil
|
||||
err = fmt.Errorf("decode user games command payload: panic recovered: %v", recovered)
|
||||
}
|
||||
}()
|
||||
|
||||
flat := fbs.GetRootAsUserGamesCommand(data, 0)
|
||||
gameID := flat.GameId(nil)
|
||||
if gameID == nil {
|
||||
return nil, errors.New("decode user games command payload: game_id is missing")
|
||||
}
|
||||
out := &model.UserGamesCommand{
|
||||
GameID: uuidFromHiLo(gameID.Hi(), gameID.Lo()),
|
||||
}
|
||||
count := flat.CommandsLength()
|
||||
if count > 0 {
|
||||
out.Commands = make([]model.DecodableCommand, count)
|
||||
flatCommand := new(fbs.CommandItem)
|
||||
for i := 0; i < count; i++ {
|
||||
if !flat.Commands(flatCommand, i) {
|
||||
return nil, fmt.Errorf("decode user games command %d: command item is missing", i)
|
||||
}
|
||||
cmd, decodeErr := decodeOrderCommand(flatCommand, i)
|
||||
if decodeErr != nil {
|
||||
return nil, decodeErr
|
||||
}
|
||||
out.Commands[i] = cmd
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UserGamesOrderToPayload converts model.UserGamesOrder to FlatBuffers
|
||||
// bytes suitable for the authenticated gateway transport.
|
||||
func UserGamesOrderToPayload(req *model.UserGamesOrder) ([]byte, error) {
|
||||
@@ -1068,19 +1002,6 @@ func PayloadToUserGamesOrder(data []byte) (result *model.UserGamesOrder, err err
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// EmptyUserGamesCommandResponsePayload returns a FlatBuffers-encoded
|
||||
// empty `UserGamesCommandResponse` buffer. Used by gateway to ack a
|
||||
// successful `MessageTypeUserGamesCommand` even though the engine
|
||||
// returns 204 No Content — the typed envelope keeps the message-type
|
||||
// contract symmetric with other authenticated routes.
|
||||
func EmptyUserGamesCommandResponsePayload() []byte {
|
||||
builder := flatbuffers.NewBuilder(16)
|
||||
fbs.UserGamesCommandResponseStart(builder)
|
||||
offset := fbs.UserGamesCommandResponseEnd(builder)
|
||||
fbs.FinishUserGamesCommandResponseBuffer(builder, offset)
|
||||
return builder.FinishedBytes()
|
||||
}
|
||||
|
||||
// UserGamesOrderResponseToPayload encodes the engine's response body
|
||||
// for `PUT /api/v1/order` into the wire FlatBuffers envelope expected
|
||||
// for `MessageTypeUserGamesOrder`. The engine populates per-command
|
||||
@@ -1298,9 +1219,8 @@ func PayloadToUserGamesOrderGetResponse(data []byte) (order *model.UserGamesOrde
|
||||
}
|
||||
|
||||
// encodeCommandItemVector serialises a slice of DecodableCommand into a
|
||||
// FlatBuffers vector of CommandItem. Used by UserGamesCommandToPayload
|
||||
// and UserGamesOrderToPayload to keep the per-command encoding logic in
|
||||
// one place.
|
||||
// FlatBuffers vector of CommandItem. Used by UserGamesOrderToPayload to
|
||||
// keep the per-command encoding logic in one place.
|
||||
func encodeCommandItemVector(builder *flatbuffers.Builder, commands []model.DecodableCommand, opLabel string) (flatbuffers.UOffsetT, error) {
|
||||
offsets := make([]flatbuffers.UOffsetT, len(commands))
|
||||
for i := range commands {
|
||||
@@ -1331,12 +1251,7 @@ func encodeCommandItemVector(builder *flatbuffers.Builder, commands []model.Deco
|
||||
if len(offsets) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
// `UserGamesCommandStartCommandsVector` and the corresponding
|
||||
// `UserGamesOrderStartCommandsVector` are identical helpers (both
|
||||
// expand to `builder.StartVector(4, numElems, 4)`); we use the
|
||||
// command flavour for both message types so the helper has a
|
||||
// single dependency point.
|
||||
fbs.UserGamesCommandStartCommandsVector(builder, len(offsets))
|
||||
fbs.UserGamesOrderStartCommandsVector(builder, len(offsets))
|
||||
for i := len(offsets) - 1; i >= 0; i-- {
|
||||
builder.PrependUOffsetT(offsets[i])
|
||||
}
|
||||
|
||||
@@ -10,32 +10,6 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestUserGamesCommandPayloadRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
source := &model.UserGamesCommand{
|
||||
GameID: uuid.MustParse("11111111-2222-3333-4444-555555555555"),
|
||||
Commands: []model.DecodableCommand{
|
||||
&model.CommandRaceVote{CommandMeta: commandMeta("cmd-01", model.CommandTypeRaceVote, nil, nil), Acceptor: "race-a"},
|
||||
&model.CommandShipGroupSend{CommandMeta: commandMeta("cmd-02", model.CommandTypeShipGroupSend, nil, nil), ID: "group-1", Destination: 7},
|
||||
},
|
||||
}
|
||||
|
||||
payload, err := UserGamesCommandToPayload(source)
|
||||
if err != nil {
|
||||
t.Fatalf("encode user games command: %v", err)
|
||||
}
|
||||
|
||||
decoded, err := PayloadToUserGamesCommand(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("decode user games command: %v", err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(source, decoded) {
|
||||
t.Fatalf("round-trip mismatch\nsource: %#v\ndecoded:%#v", source, decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserGamesOrderPayloadRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -62,15 +36,9 @@ func TestUserGamesOrderPayloadRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserGamesCommandRejectsNilAndEmpty(t *testing.T) {
|
||||
func TestUserGamesOrderRejectsNilAndEmpty(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := UserGamesCommandToPayload(nil); err == nil {
|
||||
t.Fatalf("expected error encoding nil user games command")
|
||||
}
|
||||
if _, err := PayloadToUserGamesCommand(nil); err == nil {
|
||||
t.Fatalf("expected error decoding empty user games command")
|
||||
}
|
||||
if _, err := UserGamesOrderToPayload(nil); err == nil {
|
||||
t.Fatalf("expected error encoding nil user games order")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user