Files
galaxy-game/game/internal/router/router.go
T
Ilia Denisov 601970b028
Tests · Go / test (push) Successful in 2m27s
Tests · UI / test (push) Waiting to run
Tests · Integration / integration (pull_request) Successful in 1m45s
Tests · Go / test (pull_request) Successful in 3m13s
Tests · UI / test (pull_request) Successful in 3m8s
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>
2026-05-30 13:37:07 +02:00

102 lines
3.1 KiB
Go

package router
import (
"fmt"
"io"
"net/http"
"os"
"galaxy/game/internal/router/handler"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
const (
ISO8601 = "2006-01-02 15:04:05.0 -07:00"
)
type Router struct {
r *gin.Engine
}
func (r Router) Run() error {
return r.r.Run()
}
// NewRouter builds the HTTP router around the supplied engine.
func NewRouter(engine handler.Engine) Router {
gin.SetMode(gin.ReleaseMode)
return Router{r: setupRouter(engine)}
}
func setupRouter(engine handler.Engine) *gin.Engine {
r := gin.New()
// Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
logConfig := &gin.LoggerConfig{Formatter: logFormatter}
if gin.Mode() != gin.DebugMode {
logConfig.Output = io.Discard
}
r.Use(gin.LoggerWithConfig(*logConfig))
// Recovery middleware recovers from any panics and writes a 500 if there was one.
r.Use(gin.CustomRecovery(recoveryHandler))
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
if err := v.RegisterValidation("notblank", notBlankStringValidator); err != nil {
panic(err)
}
if err := v.RegisterValidation("ammoWeapons", armamentWithWeaponsValidator); err != nil {
panic(err)
}
if err := v.RegisterValidation("entity", entityNameStringValidator); err != nil {
panic(err)
}
if err := v.RegisterValidation("subject", productionTypeStringValidator); err != nil {
panic(err)
}
}
r.GET("/healthz", handler.HealthzHandler)
groupV1 := r.Group("/api/v1")
// One shared limiter serialises every operation that mutates the
// canonical game state file (state.json): there is at most one such
// write in flight at a time. Orders write independent per-player files
// and stay unsynchronised; reads are lock-free.
stateMutationLimit := LimitMiddleware(1)
groupAdmin := groupV1.Group("/admin")
groupAdmin.GET("/status", func(ctx *gin.Context) { handler.StatusHandler(ctx, engine) })
groupAdmin.POST("/init", stateMutationLimit, func(ctx *gin.Context) { handler.InitHandler(ctx, engine) })
groupAdmin.PUT("/turn", stateMutationLimit, func(ctx *gin.Context) { handler.TurnHandler(ctx, engine) })
groupAdmin.POST("/race/banish", stateMutationLimit, func(ctx *gin.Context) { handler.BanishHandler(ctx, engine) })
groupV1.GET("/report", func(ctx *gin.Context) { handler.ReportHandler(ctx, engine) })
groupV1.PUT("/order", func(ctx *gin.Context) { handler.PutOrderHandler(ctx, engine) })
groupV1.GET("/order", func(ctx *gin.Context) { handler.GetOrderHandler(ctx, engine) })
groupV1.GET("/battle/:turn/:uuid", func(ctx *gin.Context) { handler.BattleHandler(ctx, engine) })
return r
}
func logFormatter(param gin.LogFormatterParams) string {
return fmt.Sprintf("[%s] \"%s %s %s %d %s\"\n",
param.TimeStamp.Format(ISO8601),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
)
}
func recoveryHandler(c *gin.Context, recovered any) {
if err, ok := recovered.(string); ok {
fmt.Fprintf(os.Stderr, "recovered: %s", err)
}
c.AbortWithStatus(http.StatusInternalServerError)
}