diff --git a/README.md b/README.md index 566e8dd..49575a6 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,24 @@ at the quota gets 409. `DELETE /v1/private-servers/{id}` drains the server. An i World persistence is spec only for now: a later version snapshots the instance directory to a template on stop and restores it on the next start. +## Region cells + +A pool with a `sharding` section splits its world into cells (`cells[]` with chunk bounds `minX/minZ/maxX/maxZ`, +inclusive; `cellSize` in chunks defaults to 32 and is only used once cells are generated). The controller gives +each cell to exactly one Ready instance of the pool and stores it as the instance label `grus.olf/cells`. An +assignment stays while its instance is Ready; cells of a failed or lost instance move to the Ready instance with +the fewest cells. Every change publishes `pool.cells`. Splitting and merging cells with the load is spec only. + +```sh +grus cells world +curl -H "Authorization: Bearer $TOKEN" "$GRUS_URL/v1/pools/world/cells/at?x=520&z=10" +``` + +`GET /v1/pools/{pool}/cells` lists cell, bounds, instance and address; `GET /v1/pools/{pool}/cells/at?x=&z=` takes +block coordinates (chunk = block >> 4) and answers with the owning cell (404 when no cell covers the block, 409 +while the cell has no Ready instance). The Velocity plugin adds `/region ` (permission `grus.region`) for +the pool named in `GRUS_SHARD_POOL`. + ## License Apache License 2.0. See [LICENSE](LICENSE). diff --git a/api/openapi.yaml b/api/openapi.yaml index 98d6107..5a80c71 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -8,6 +8,78 @@ components: format: int64 type: integer type: object + Cell: + additionalProperties: false + properties: + maxX: + description: Largest chunk x of the cell + format: int64 + type: integer + maxZ: + description: Largest chunk z of the cell + format: int64 + type: integer + minX: + description: Smallest chunk x of the cell + format: int64 + type: integer + minZ: + description: Smallest chunk z of the cell + format: int64 + type: integer + name: + description: Cell name; assigned to exactly one Ready instance + type: string + required: + - name + - minX + - minZ + - maxX + - maxZ + type: object + CellBounds: + additionalProperties: false + properties: + maxX: + format: int64 + type: integer + maxZ: + format: int64 + type: integer + minX: + format: int64 + type: integer + minZ: + format: int64 + type: integer + required: + - minX + - minZ + - maxX + - maxZ + type: object + CellInfo: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/CellInfo.json + format: uri + readOnly: true + type: string + address: + type: string + bounds: + $ref: "#/components/schemas/CellBounds" + cell: + type: string + instance: + type: string + required: + - cell + - bounds + type: object Command: additionalProperties: false properties: @@ -860,13 +932,13 @@ components: additionalProperties: false properties: cellSize: - description: Cell edge length in chunks + description: Cell edge length in chunks, used when cells are generated (default 32) format: int64 type: integer cells: - description: Explicit cell names + description: Static cell list; bounds are chunk coordinates items: - type: string + $ref: "#/components/schemas/Cell" type: - array - "null" @@ -1758,6 +1830,101 @@ paths: security: - bearer: [] summary: Create or replace a pool + /v1/pools/{pool}/cells: + get: + operationId: list-pool-cells + parameters: + - description: Pool name + in: path + name: pool + required: true + schema: + description: Pool name + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/CellInfo" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: List the cells of a sharded pool with the instance that serves each + /v1/pools/{pool}/cells/at: + get: + description: 404 when no cell covers the block, 409 when the cell has no Ready instance yet. + operationId: get-pool-cell-at + parameters: + - description: Pool name + in: path + name: pool + required: true + schema: + description: Pool name + type: string + - description: Block x coordinate + explode: false + in: query + name: x + required: true + schema: + description: Block x coordinate + format: int64 + type: integer + - description: Block z coordinate + explode: false + in: query + name: z + required: true + schema: + description: Block z coordinate + format: int64 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/CellInfo" + description: OK + "404": + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Not Found + "409": + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Conflict + "422": + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Unprocessable Entity + "500": + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Internal Server Error + security: + - bearer: [] + summary: Find the cell and instance that own a block position /v1/pools/{pool}/maintenance: put: operationId: set-pool-maintenance diff --git a/deploy/crds/pools.grus.onelitefeather.net.yaml b/deploy/crds/pools.grus.onelitefeather.net.yaml index adca039..57b2d98 100644 --- a/deploy/crds/pools.grus.onelitefeather.net.yaml +++ b/deploy/crds/pools.grus.onelitefeather.net.yaml @@ -76,7 +76,15 @@ spec: cellSize: {type: integer} cells: type: array - items: {type: string} + items: + type: object + required: [name, minX, minZ, maxX, maxZ] + properties: + name: {type: string} + minX: {type: integer} + minZ: {type: integer} + maxX: {type: integer} + maxZ: {type: integer} private: type: object properties: diff --git a/internal/api/cells_test.go b/internal/api/cells_test.go new file mode 100644 index 0000000..bba27d1 --- /dev/null +++ b/internal/api/cells_test.go @@ -0,0 +1,86 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/controller" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +func cellFixture(t *testing.T) fixture { + fx := newFixture(t, Config{}, nil) + fx.svc.cells = []model.CellInfo{{Cell: "r0", Bounds: model.CellBounds{MinX: 0, MinZ: 0, MaxX: 31, MaxZ: 31}, Instance: "world-a", Address: "10.0.0.1:25565"}} + return fx +} + +func TestListPoolCellsReturnsTheAssignment(t *testing.T) { + fx := cellFixture(t) + + rec := fx.call(t, http.MethodGet, "/v1/pools/world/cells", adminToken, "", "") + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body) + } + var got []model.CellInfo + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || len(got) != 1 || got[0].Instance != "world-a" || got[0].Bounds.MaxX != 31 { + t.Fatalf("body = %s (%v), want the cell r0 owned by world-a", rec.Body, err) + } + if fx.svc.cellsPool != "world" { + t.Errorf("pool = %q, want world", fx.svc.cellsPool) + } +} + +func TestCellAtPassesBlockCoordinates(t *testing.T) { + fx := cellFixture(t) + + rec := fx.call(t, http.MethodGet, "/v1/pools/world/cells/at?x=-100&z=250", adminToken, "", "") + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body) + } + if fx.svc.cellX != -100 || fx.svc.cellZ != 250 { + t.Errorf("service got x=%d z=%d, want -100 and 250", fx.svc.cellX, fx.svc.cellZ) + } +} + +func TestCellAtRequiresBothCoordinates(t *testing.T) { + fx := cellFixture(t) + + rec := fx.call(t, http.MethodGet, "/v1/pools/world/cells/at?x=1", adminToken, "", "") + + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("status = %d, want 422", rec.Code) + } +} + +func TestCellAtMapsServiceErrors(t *testing.T) { + for _, tc := range []struct { + err error + want int + }{ + {controller.ErrNotFound, http.StatusNotFound}, + {fmt.Errorf("%w: cell r0 has no ready instance", controller.ErrInvalidState), http.StatusConflict}, + } { + fx := cellFixture(t) + fx.svc.cellsErr = tc.err + + rec := fx.call(t, http.MethodGet, "/v1/pools/world/cells/at?x=1&z=1", adminToken, "", "") + + if rec.Code != tc.want { + t.Errorf("%v: status = %d, want %d", tc.err, rec.Code, tc.want) + } + } +} + +func TestProxyTokenMayResolveCells(t *testing.T) { + fx := cellFixture(t) + + rec := fx.call(t, http.MethodGet, "/v1/pools/world/cells/at?x=1&z=1", proxyToken, "", "") + + if rec.Code != http.StatusOK { + t.Fatalf("proxy token status = %d, want 200 (instances:read)", rec.Code) + } +} diff --git a/internal/api/fakes_test.go b/internal/api/fakes_test.go index 01ecaa6..d7fc7e7 100644 --- a/internal/api/fakes_test.go +++ b/internal/api/fakes_test.go @@ -60,6 +60,11 @@ type fakeService struct { privateErr error privateCreated bool privateOwnerFilter string + + cells []model.CellInfo + cellsErr error + cellsPool string + cellX, cellZ int } func newFakeService() *fakeService { @@ -178,6 +183,19 @@ func (f *fakeService) StopPrivateServer(_ context.Context, id string) (model.Ins return model.Instance{ID: id}, f.stopErr } +func (f *fakeService) PoolCells(_ context.Context, pool string) ([]model.CellInfo, error) { + f.cellsPool = pool + return f.cells, f.cellsErr +} + +func (f *fakeService) CellAt(_ context.Context, pool string, x, z int) (model.CellInfo, error) { + f.cellsPool, f.cellX, f.cellZ = pool, x, z + if f.cellsErr != nil || len(f.cells) == 0 { + return model.CellInfo{}, f.cellsErr + } + return f.cells[0], nil +} + func (f *fakeService) Command(context.Context, string, string) error { return nil } func (f *fakeService) AuthenticateInstance(_ context.Context, token string) (model.Instance, error) { diff --git a/internal/api/pools.go b/internal/api/pools.go index 52f446b..1ea82e5 100644 --- a/internal/api/pools.go +++ b/internal/api/pools.go @@ -31,6 +31,20 @@ type deletePoolInput struct { Drain bool `query:"drain" doc:"Drain the instances before the pool is removed"` } +type cellsOutput struct { + Body []model.CellInfo +} + +type cellOutput struct { + Body model.CellInfo +} + +type cellAtInput struct { + Pool string `path:"pool" doc:"Pool name"` + X int `query:"x" required:"true" doc:"Block x coordinate"` + Z int `query:"z" required:"true" doc:"Block z coordinate"` +} + type maintenanceInput struct { Pool string `path:"pool" doc:"Pool name"` Body maintenanceBody @@ -95,4 +109,29 @@ func (s *server) registerPools(api huma.API) { } return &poolOutput{Body: pool}, nil }) + + // Proxies resolve cells, so these routes need only instances:read, which instance tokens have. + huma.Register(api, operation(scopeInstancesRead, huma.Operation{ + OperationID: "list-pool-cells", Method: http.MethodGet, Path: "/v1/pools/{pool}/cells", + Summary: "List the cells of a sharded pool with the instance that serves each", + }), func(ctx context.Context, in *poolPath) (*cellsOutput, error) { + cells, err := s.svc.PoolCells(ctx, in.Pool) + if err != nil { + return nil, mapError(s.log, err) + } + return &cellsOutput{Body: cells}, nil + }) + + huma.Register(api, operation(scopeInstancesRead, huma.Operation{ + OperationID: "get-pool-cell-at", Method: http.MethodGet, Path: "/v1/pools/{pool}/cells/at", + Summary: "Find the cell and instance that own a block position", + Description: "404 when no cell covers the block, 409 when the cell has no Ready instance yet.", + Errors: []int{http.StatusNotFound, http.StatusConflict}, + }), func(ctx context.Context, in *cellAtInput) (*cellOutput, error) { + cell, err := s.svc.CellAt(ctx, in.Pool, in.X, in.Z) + if err != nil { + return nil, mapError(s.log, err) + } + return &cellOutput{Body: cell}, nil + }) } diff --git a/internal/cli/cells.go b/internal/cli/cells.go new file mode 100644 index 0000000..8c66c91 --- /dev/null +++ b/internal/cli/cells.go @@ -0,0 +1,36 @@ +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +var cellColumns = []column{ + {"CELL", field("cell")}, + {"BOUNDS", func(o object) string { + return fmt.Sprintf("x %s..%s, z %s..%s", field("bounds", "minX")(o), field("bounds", "maxX")(o), + field("bounds", "minZ")(o), field("bounds", "maxZ")(o)) + }}, + {"INSTANCE", field("instance")}, {"ADDRESS", field("address")}, +} + +func newCellsCmd(env *Env, o *opts) *cobra.Command { + return &cobra.Command{ + Use: "cells ", + Short: "Show the region cells of a sharded pool and the instance that serves each (bounds in chunks)", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + cells, err := c.Cells(cmdContext(cmd), args[0]) + if err != nil { + return err + } + return printList(cmd, o.output, cells, cellColumns) + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "pools")), + } +} diff --git a/internal/cli/cells_test.go b/internal/cli/cells_test.go new file mode 100644 index 0000000..b44703b --- /dev/null +++ b/internal/cli/cells_test.go @@ -0,0 +1,38 @@ +package cli + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestCellsShowsBoundsAndOwner(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/pools/world/cells", func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `[{"cell":"r0","bounds":{"minX":0,"minZ":0,"maxX":31,"maxZ":31},"instance":"world-a","address":"10.0.0.1:25565"}, +{"cell":"r1","bounds":{"minX":32,"minZ":0,"maxX":63,"maxZ":31}}]`) + }) + h := newHarness(t, mux) + + out := h.ok("", "cells", "world") + + for _, want := range []string{"CELL", "r0", "x 0..31, z 0..31", "world-a", "10.0.0.1:25565", "r1"} { + if !strings.Contains(out, want) { + t.Errorf("table lacks %q:\n%s", want, out) + } + } +} + +func TestCellsOfAnUnshardedPoolFails(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/pools/lobby/cells", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, `{"title":"Not Found","detail":"not found"}`) + }) + h := newHarness(t, mux) + + if _, _, err := h.run("", "cells", "lobby"); err == nil || !strings.Contains(err.Error(), "404") { + t.Fatalf("err = %v, want the controller's 404", err) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 70cc95d..9a82f8d 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -51,7 +51,7 @@ func newRoot(env *Env, defaults opts, inShell bool) *cobra.Command { root.AddCommand( newGetCmd(env, &o), newDescribeCmd(env, &o), newApplyCmd(env, &o), newScaleCmd(env, &o), newStopCmd(env, &o), newLogsCmd(env, &o), newExecCmd(env, &o), newEventsCmd(env, &o), - newNetworkCmd(env, &o), newPrivateCmd(env, &o), newLoginCmd(env), newConfigCmd(env), + newNetworkCmd(env, &o), newPrivateCmd(env, &o), newCellsCmd(env, &o), newLoginCmd(env), newConfigCmd(env), ) if inShell { root.AddCommand(newExitCmd(env)) diff --git a/internal/client/client.go b/internal/client/client.go index 24406fa..8620a25 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -332,3 +332,10 @@ func (c *Client) PrivateServers(ctx context.Context, owner string) ([]Object, er } return out, err } + +// Cells lists the cells of a sharded pool with the instance that serves each. +func (c *Client) Cells(ctx context.Context, pool string) ([]Object, error) { + var out []Object + err := c.call(ctx, http.MethodGet, "/v1/pools/"+url.PathEscape(pool)+"/cells", nil, nil, &out) + return out, err +} diff --git a/internal/controller/cells.go b/internal/controller/cells.go new file mode 100644 index 0000000..83683ee --- /dev/null +++ b/internal/controller/cells.go @@ -0,0 +1,200 @@ +package controller + +import ( + "context" + "fmt" + "slices" + "sort" + "strings" + + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +// cellsOf returns the cell names of the grus.olf/cells label of an instance. +func cellsOf(inst model.Instance) []string { + v := inst.Labels[model.LabelCells] + if v == "" { + return nil + } + return strings.Split(v, ",") +} + +// assignCells gives every cell of every sharded pool to exactly one Ready instance of the pool and stores the +// result as the label grus.olf/cells. The assignment is stable: a cell stays with its instance while that +// instance is Ready. Cells of instances that are not Ready (failed, lost, stopping) and cells without owner +// go to the Ready instance with the fewest cells. pool.cells is published when the assignment changed. +// +// Spec only: splitting a hot cell and merging idle neighbours with the load; see model.Sharding. +// Callers hold c.mu. +func (c *Controller) assignCells(ctx context.Context, insts []model.Instance, specs map[string]model.PoolSpec, unlisted map[string]bool) []error { + var errs []error + names := make([]string, 0, len(specs)) + for name, spec := range specs { + if spec.Sharding != nil { + names = append(names, name) + } + } + sort.Strings(names) + for _, name := range names { + if err := c.assignPoolCells(ctx, name, specs[name].Sharding, insts, unlisted); err != nil { + errs = append(errs, fmt.Errorf("assign cells of pool %s: %w", name, err)) + } + } + return errs +} + +func (c *Controller) assignPoolCells(ctx context.Context, pool string, sh *model.Sharding, all []model.Instance, unlisted map[string]bool) error { + var insts []model.Instance + for _, inst := range all { + if inst.Pool == pool && !inst.State.Terminal() { + insts = append(insts, inst) + } + } + slices.SortFunc(insts, func(a, b model.Instance) int { return strings.Compare(a.ID, b.ID) }) + + eligible := func(inst model.Instance) bool { return inst.State == model.StateReady } + declared := make(map[string]bool, len(sh.Cells)) + for _, cell := range sh.Cells { + declared[cell.Name] = true + } + + before := make(map[string]string) // cell -> instance as stored + assigned := make(map[string]string) // cell -> instance after this cycle + count := make(map[string]int) // instance -> number of cells + for _, inst := range insts { + for _, cell := range cellsOf(inst) { + before[cell] = inst.ID + if !declared[cell] || !eligible(inst) || assigned[cell] != "" { + continue // removed from the spec, instance not Ready, or already held by another instance + } + assigned[cell] = inst.ID + count[inst.ID]++ + } + } + var ready []model.Instance + for _, inst := range insts { + if eligible(inst) && !unlisted[hostOf(inst)] { + ready = append(ready, inst) + } + } + if len(ready) > 0 { + for _, cell := range sh.Cells { + if assigned[cell.Name] != "" { + continue + } + best := ready[0] + for _, inst := range ready[1:] { + if count[inst.ID] < count[best.ID] { + best = inst + } + } + assigned[cell.Name] = best.ID + count[best.ID]++ + } + } + + changed := false + for _, inst := range insts { + var mine []string + for cell, id := range assigned { + if id == inst.ID { + mine = append(mine, cell) + } + } + sort.Strings(mine) + want := strings.Join(mine, ",") + if inst.Labels[model.LabelCells] == want { + continue + } + labels := make(map[string]string, len(inst.Labels)+1) + for k, v := range inst.Labels { + labels[k] = v + } + if want == "" { + delete(labels, model.LabelCells) + } else { + labels[model.LabelCells] = want + } + inst.Labels = labels + if err := c.st.UpdateInstance(ctx, inst); err != nil { + return fmt.Errorf("persist instance %s: %w", inst.ID, err) + } + changed = true + } + if !changed && sameAssignment(before, assigned) { + return nil + } + data := model.PoolCellsData{Pool: pool, Cells: make([]model.CellOwner, 0, len(sh.Cells))} + for _, cell := range sh.Cells { + data.Cells = append(data.Cells, model.CellOwner{Cell: cell.Name, Instance: assigned[cell.Name]}) + } + c.pub.Publish(model.EventPoolCells, data) + return nil +} + +func sameAssignment(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if b[k] != v { + return false + } + } + return true +} + +// PoolCells lists the cells of a sharded pool with the instance that serves each. +func (c *Controller) PoolCells(ctx context.Context, pool string) ([]model.CellInfo, error) { + p, err := c.st.GetPool(ctx, pool) + if err != nil { + return nil, mapErr(err) + } + if p.Spec.Sharding == nil { + return nil, fmt.Errorf("%w: pool %s has no sharding", ErrNotFound, pool) + } + insts, err := c.st.ListInstances(ctx, store.InstanceFilter{Pool: pool}) + if err != nil { + return nil, mapErr(err) + } + owner := make(map[string]model.Instance) + for _, inst := range insts { + if inst.State != model.StateReady { + continue + } + for _, cell := range cellsOf(inst) { + owner[cell] = inst + } + } + out := make([]model.CellInfo, 0, len(p.Spec.Sharding.Cells)) + for _, cell := range p.Spec.Sharding.Cells { + info := model.CellInfo{Cell: cell.Name, Bounds: model.CellBounds{MinX: cell.MinX, MinZ: cell.MinZ, MaxX: cell.MaxX, MaxZ: cell.MaxZ}} + if inst, ok := owner[cell.Name]; ok { + info.Instance, info.Address = inst.ID, inst.Address + } + out = append(out, info) + } + return out, nil +} + +// CellAt returns the cell that contains the block (x, z) and its instance. ErrNotFound when no cell covers the +// block, ErrInvalidState when the cell has no Ready instance yet. +func (c *Controller) CellAt(ctx context.Context, pool string, x, z int) (model.CellInfo, error) { + cells, err := c.PoolCells(ctx, pool) + if err != nil { + return model.CellInfo{}, err + } + cx, cz := model.ChunkOf(x), model.ChunkOf(z) + for _, info := range cells { + b := info.Bounds + if cx < b.MinX || cx > b.MaxX || cz < b.MinZ || cz > b.MaxZ { + continue + } + if info.Instance == "" { + return model.CellInfo{}, fmt.Errorf("%w: cell %s has no ready instance", ErrInvalidState, info.Cell) + } + return info, nil + } + return model.CellInfo{}, fmt.Errorf("%w: no cell covers block %d,%d", ErrNotFound, x, z) +} diff --git a/internal/controller/cells_test.go b/internal/controller/cells_test.go new file mode 100644 index 0000000..51bb0db --- /dev/null +++ b/internal/controller/cells_test.go @@ -0,0 +1,196 @@ +package controller + +import ( + "errors" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +func shardedSpec(min int, cells ...model.Cell) model.PoolSpec { + s := dynamicSpec(min, 0) + s.Sharding = &model.Sharding{Cells: cells} + return s +} + +var ( + cellR0 = model.Cell{Name: "r0", MinX: 0, MinZ: 0, MaxX: 31, MaxZ: 31} + cellR1 = model.Cell{Name: "r1", MinX: 32, MinZ: 0, MaxX: 63, MaxZ: 31} + cellR2 = model.Cell{Name: "r2", MinX: 0, MinZ: 32, MaxX: 31, MaxZ: 63} +) + +// readyInstances starts the pool's instances and brings all of them to Ready before the next reconcile, so +// the cells are spread over all of them (the first Ready instance would otherwise take every cell and keep it). +func (f *fixture) readyInstances(pool string, n int) []string { + f.t.Helper() + f.reconcile() + var ids []string + for i, s := range f.drv.Started() { + if s.Instance.Pool == pool { + f.drv.SetPhase(s.Instance.ID, driver.PhaseRunning, "10.0.0."+string(rune('1'+i))+":25565") + ids = append(ids, s.Instance.ID) + } + } + if len(ids) != n { + f.t.Fatalf("started %d instances, want %d", len(ids), n) + } + f.reconcile() + for _, id := range ids { + if _, err := f.c.SelfReady(f.ctx, id); err != nil { + f.t.Fatalf("self ready %s: %v", id, err) + } + } + f.reconcile() + return ids +} + +func (f *fixture) cellOwners() map[string]string { + f.t.Helper() + out := map[string]string{} + for _, inst := range f.instancesOf("world") { + for _, cell := range cellsOf(inst) { + out[cell] = inst.ID + } + } + return out +} + +func TestCellsAreSpreadOverReadyInstances(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(2, cellR0, cellR1, cellR2)) + f.readyInstances("world", 2) + + owners := f.cellOwners() + + if len(owners) != 3 { + t.Fatalf("assigned cells = %v, want all three", owners) + } + per := map[string]int{} + for _, id := range owners { + per[id]++ + } + if len(per) != 2 { + t.Errorf("cells per instance = %v, want both instances to serve cells", per) + } + if n := f.pub.count(model.EventPoolCells); n == 0 { + t.Errorf("no pool.cells event published") + } +} + +func TestCellsStayWithTheirInstanceAndNoEventWithoutChange(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(2, cellR0, cellR1, cellR2)) + f.readyInstances("world", 2) + before := f.cellOwners() + events := f.pub.count(model.EventPoolCells) + + f.reconcile() + f.reconcile() + + after := f.cellOwners() + for cell, id := range before { + if after[cell] != id { + t.Errorf("cell %s moved from %s to %s while the instance stayed Ready", cell, id, after[cell]) + } + } + if n := f.pub.count(model.EventPoolCells); n != events { + t.Errorf("pool.cells events = %d, want %d: nothing changed", n, events) + } +} + +func TestCellsOfALostInstanceMoveToTheOneWithFewestCells(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(2, cellR0, cellR1, cellR2)) + ids := f.readyInstances("world", 2) + before := f.cellOwners() + var lost, kept string + for _, id := range ids { + n := 0 + for _, o := range before { + if o == id { + n++ + } + } + if n == 2 { + kept = id + } else { + lost = id + } + } + events := f.pub.count(model.EventPoolCells) + + f.drv.SetPhase(lost, driver.PhaseFailed, "") + f.reconcile() + + after := f.cellOwners() + for cell, id := range after { + if id != kept { + t.Errorf("cell %s is on %s, want the only Ready instance %s", cell, id, kept) + } + } + if len(after) != 3 { + t.Errorf("assigned cells = %v, want all three on %s", after, kept) + } + if f.pub.count(model.EventPoolCells) <= events { + t.Errorf("no pool.cells event after the reassignment") + } +} + +func TestACellWithoutAReadyInstanceStaysUnassigned(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(1, cellR0)) + f.reconcile() // the instance is only Requested/Preparing + + if owners := f.cellOwners(); len(owners) != 0 { + t.Fatalf("assigned cells = %v, want none before an instance is Ready", owners) + } + if _, err := f.c.CellAt(f.ctx, "world", 5, 5); !errors.Is(err, ErrInvalidState) { + t.Fatalf("cell at without an instance = %v, want ErrInvalidState", err) + } +} + +func TestPoolCellsAndCellAtResolveBlockCoordinates(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(2, cellR0, cellR1)) + f.readyInstances("world", 2) + + cells, err := f.c.PoolCells(f.ctx, "world") + if err != nil || len(cells) != 2 || cells[0].Instance == "" || cells[0].Address == "" { + t.Fatalf("cells = %+v (%v), want two assigned cells with addresses", cells, err) + } + // Block 520 is chunk 32, the first chunk of r1. + at, err := f.c.CellAt(f.ctx, "world", 520, 10) + if err != nil || at.Cell != "r1" { + t.Fatalf("cell at block 520,10 = %+v (%v), want r1", at, err) + } + // Block -1 is chunk -1: outside every cell. + if _, err := f.c.CellAt(f.ctx, "world", -1, 0); !errors.Is(err, ErrNotFound) { + t.Fatalf("cell at block -1,0 = %v, want ErrNotFound", err) + } +} + +func TestPoolCellsOfAnUnshardedPoolIsNotFound(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("lobby", dynamicSpec(1, 0)) + + if _, err := f.c.PoolCells(f.ctx, "lobby"); !errors.Is(err, ErrNotFound) { + t.Fatalf("cells of an unsharded pool = %v, want ErrNotFound", err) + } + if _, err := f.c.PoolCells(f.ctx, "nope"); !errors.Is(err, ErrNotFound) { + t.Fatalf("cells of an unknown pool = %v, want ErrNotFound", err) + } +} + +func TestRemovedCellsLoseTheirLabel(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("world", shardedSpec(1, cellR0, cellR1)) + f.readyInstances("world", 1) + + f.putPool("world", shardedSpec(1, cellR1)) + f.reconcile() + + if owners := f.cellOwners(); len(owners) != 1 || owners["r1"] == "" { + t.Fatalf("owners = %v, want only r1", owners) + } +} diff --git a/internal/controller/reconcile.go b/internal/controller/reconcile.go index 81f2c8f..054c24b 100644 --- a/internal/controller/reconcile.go +++ b/internal/controller/reconcile.go @@ -126,6 +126,12 @@ func (c *Controller) ReconcileOnce(ctx context.Context) error { } errs = append(errs, c.stopIdlePrivate(ctx, insts, specs, unlisted, now)...) + // 3c. Region cells of sharded pools. + if insts, err = c.listAll(ctx); err != nil { + return err + } + errs = append(errs, c.assignCells(ctx, insts, specs, unlisted)...) + // 4. Autoscaling per pool. if insts, err = c.listAll(ctx); err != nil { return err diff --git a/internal/controller/service.go b/internal/controller/service.go index 249f7d5..3a3f1ad 100644 --- a/internal/controller/service.go +++ b/internal/controller/service.go @@ -90,6 +90,11 @@ type Service interface { // StopPrivateServer drains a private instance: it stops as soon as its players left. StopPrivateServer(ctx context.Context, id string) (model.Instance, error) + // PoolCells lists the cells of a sharded pool with the instance serving each (ErrNotFound without sharding). + PoolCells(ctx context.Context, pool string) ([]model.CellInfo, error) + // CellAt resolves the block coordinates (x, z) to the cell and instance that own them. + CellAt(ctx context.Context, pool string, x, z int) (model.CellInfo, error) + // AuthenticateInstance maps a plain per-instance token to its live (non-terminal) instance. AuthenticateInstance(ctx context.Context, token string) (model.Instance, error) SelfReady(ctx context.Context, id string) (model.Instance, error) diff --git a/internal/model/model.go b/internal/model/model.go index c384ca5..8c30d0c 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -5,9 +5,13 @@ package model import ( "encoding/json" "fmt" + "regexp" "time" ) +// cellNameRE keeps cell names usable in the comma separated grus.olf/cells label. +var cellNameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`) + // Role says what an instance is for the network. Proxies register game instances. type Role string @@ -136,10 +140,59 @@ type Placement struct { Host string `json:"host,omitempty"` } -// Sharding splits a pool's world into cells (spec only; behaviour follows later). +// Cell is one region of a sharded world. The bounds are chunk coordinates and inclusive. +type Cell struct { + Name string `json:"name" doc:"Cell name; assigned to exactly one Ready instance"` + MinX int `json:"minX" doc:"Smallest chunk x of the cell"` + MinZ int `json:"minZ" doc:"Smallest chunk z of the cell"` + MaxX int `json:"maxX" doc:"Largest chunk x of the cell"` + MaxZ int `json:"maxZ" doc:"Largest chunk z of the cell"` +} + +// Contains reports whether the chunk (x, z) lies inside the cell. +func (c Cell) Contains(x, z int) bool { + return x >= c.MinX && x <= c.MaxX && z >= c.MinZ && z <= c.MaxZ +} + +// CellBounds is the chunk rectangle of a cell as the cells API reports it. +type CellBounds struct { + MinX int `json:"minX"` + MinZ int `json:"minZ"` + MaxX int `json:"maxX"` + MaxZ int `json:"maxZ"` +} + +// Sharding splits a pool's world into cells, each served by one Ready instance of the pool. For the prototype the +// cells are a static list. Later versions derive the cells from CellSize and split or merge them with the load +// (spec only: a cell whose instance is above the target utilisation is cut in two along its longer edge and +// the halves are assigned to different instances; neighbours of two idle instances are merged again). type Sharding struct { - CellSize int `json:"cellSize,omitempty" doc:"Cell edge length in chunks"` - Cells []string `json:"cells,omitempty" doc:"Explicit cell names"` + CellSize int `json:"cellSize,omitempty" doc:"Cell edge length in chunks, used when cells are generated (default 32)"` + Cells []Cell `json:"cells,omitempty" doc:"Static cell list; bounds are chunk coordinates"` +} + +// ChunkOf returns the chunk coordinate of a block coordinate. +func ChunkOf(block int) int { return block >> 4 } + +// CellInfo describes one cell with the instance that serves it. Instance and Address are empty while no +// Ready instance owns the cell. +type CellInfo struct { + Cell string `json:"cell"` + Bounds CellBounds `json:"bounds"` + Instance string `json:"instance,omitempty"` + Address string `json:"address,omitempty"` +} + +// PoolCellsData is the payload of pool.cells: the whole assignment of a pool after a change. +type PoolCellsData struct { + Pool string `json:"pool"` + Cells []CellOwner `json:"cells"` +} + +// CellOwner maps a cell to its instance; Instance is empty when the cell is unassigned. +type CellOwner struct { + Cell string `json:"cell"` + Instance string `json:"instance,omitempty"` } // Private lets owners run their own instance of a pool. A pool with Private set is never autoscaled: its @@ -187,6 +240,7 @@ const ( DefaultGracePeriod = 30 * time.Second DefaultHeartbeatTimeout = 15 * time.Second DefaultStartTimeout = 5 * time.Minute + DefaultCellSize = 32 DefaultQuotaPerOwner = 1 DefaultPrivateIdle = 10 * time.Minute ) @@ -195,6 +249,7 @@ const ( const ( LabelPrefix = "grus.olf/" LabelOwner = LabelPrefix + "owner" + LabelCells = LabelPrefix + "cells" ) // WithDefaults returns a copy with every empty optional field set to its default. @@ -223,6 +278,13 @@ func (s PoolSpec) WithDefaults() PoolSpec { if s.Lifecycle.StartTimeout == 0 { s.Lifecycle.StartTimeout = Duration(DefaultStartTimeout) } + if s.Sharding != nil { + sh := *s.Sharding + if sh.CellSize == 0 { + sh.CellSize = DefaultCellSize + } + s.Sharding = &sh + } if s.Private != nil { p := *s.Private if p.QuotaPerOwner == 0 { @@ -292,6 +354,9 @@ func (s PoolSpec) Validate() []FieldError { if s.Scaling.TargetUtilization <= 0 || s.Scaling.TargetUtilization > 1 { add("scaling.targetUtilization", "must be in (0, 1]") } + if sh := s.Sharding; sh != nil { + errs = append(errs, sh.validate()...) + } if p := s.Private; p != nil { if p.QuotaPerOwner < 0 { add("private.quotaPerOwner", "must not be negative") @@ -323,6 +388,39 @@ func (s PoolSpec) Validate() []FieldError { return errs } +func (sh Sharding) validate() []FieldError { + var errs []FieldError + add := func(f, m string) { errs = append(errs, FieldError{Field: f, Message: m}) } + if sh.CellSize < 0 { + add("sharding.cellSize", "must not be negative") + } + seen := map[string]bool{} + for i, c := range sh.Cells { + field := fmt.Sprintf("sharding.cells[%d]", i) + switch { + case c.Name == "": + add(field+".name", "is required") + case !cellNameRE.MatchString(c.Name): + add(field+".name", "must match "+cellNameRE.String()) + case seen[c.Name]: + add(field+".name", "is used twice") + } + seen[c.Name] = true + if c.MaxX < c.MinX || c.MaxZ < c.MinZ { + add(field, "max must not be smaller than min") + continue + } + for j := 0; j < i; j++ { + o := sh.Cells[j] + if c.MinX <= o.MaxX && o.MinX <= c.MaxX && c.MinZ <= o.MaxZ && o.MinZ <= c.MaxZ { + add(field, "overlaps cell "+o.Name) + break + } + } + } + return errs +} + // EffectivePlacement returns the placement with the v1 driver filled in when placement.driver is empty. func (s PoolSpec) EffectivePlacement() Placement { p := s.Placement @@ -379,6 +477,7 @@ const ( EventNetworkPlayers = "network.players" EventPoolCondition = "pool.condition" EventPrivateIdleStop = "private.idle-stop" + EventPoolCells = "pool.cells" EventResync = "resync" ) diff --git a/internal/model/private_test.go b/internal/model/private_test.go index a3921a9..c29164a 100644 --- a/internal/model/private_test.go +++ b/internal/model/private_test.go @@ -53,3 +53,45 @@ func TestPrivatePoolValidation(t *testing.T) { } } } + +func TestShardingValidation(t *testing.T) { + spec := privatePool() + spec.Private = nil + spec.Sharding = &Sharding{Cells: []Cell{ + {Name: "r0", MinX: 0, MinZ: 0, MaxX: 31, MaxZ: 31}, + {Name: "r0", MinX: 40, MinZ: 0, MaxX: 50, MaxZ: 5}, + {Name: "r2", MinX: 30, MinZ: 30, MaxX: 40, MaxZ: 40}, + {Name: "bad,name", MinX: 100, MinZ: 0, MaxX: 90, MaxZ: 5}, + }} + + got := fieldsOf(spec.WithDefaults().Validate()) + + for _, f := range []string{"sharding.cells[1].name", "sharding.cells[2]", "sharding.cells[3].name"} { + if !got[f] { + t.Errorf("no error for %s in %v", f, got) + } + } +} + +func TestShardingDefaultsAndValidSpec(t *testing.T) { + spec := privatePool() + spec.Private = nil + spec.Sharding = &Sharding{Cells: []Cell{{Name: "r0", MaxX: 31, MaxZ: 31}, {Name: "r1", MinX: 32, MaxX: 63, MaxZ: 31}}} + + got := spec.WithDefaults() + + if got.Sharding.CellSize != 32 || spec.Sharding.CellSize != 0 { + t.Errorf("cellSize = %d (input %d), want 32 without touching the input", got.Sharding.CellSize, spec.Sharding.CellSize) + } + if errs := got.Validate(); len(errs) != 0 { + t.Errorf("valid sharding rejected: %v", errs) + } +} + +func TestChunkOfFloorsNegativeBlocks(t *testing.T) { + for block, want := range map[int]int{0: 0, 15: 0, 16: 1, -1: -1, -16: -1, -17: -2} { + if got := ChunkOf(block); got != want { + t.Errorf("ChunkOf(%d) = %d, want %d", block, got, want) + } + } +} diff --git a/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java index 678994b..4b16ef7 100644 --- a/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java +++ b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java @@ -130,6 +130,19 @@ public Instance shutdown() { return read(send("POST", "/v1/self/shutdown", Map.of(), null), Instance.class); } + /** + * Sends an authenticated {@code GET} and returns the response body, for endpoints that have no typed method + * here yet. + * + * @param path absolute path such as {@code /v1/pools/world/cells/at} + * @param query query parameters, encoded by this method + * @throws GrusException when the controller does not answer 2xx + */ + public String get(String path, Map query) { + Objects.requireNonNull(path, "path"); + return send("GET", path, query, null); + } + private String send(String method, String path, Map query, byte[] json) { HttpRequest.BodyPublisher publisher = json == null ? HttpRequest.BodyPublishers.noBody() diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java index 0c93e1b..96fb6cb 100644 --- a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java @@ -37,6 +37,7 @@ * {@code GRUS_INSTANCE}, {@code GRUS_POOL}, {@code GRUS_ROLE}). Without {@code GRUS_URL} and * {@code GRUS_TOKEN} the plugin does nothing. {@code GRUS_FALLBACK_POOL} (default {@code lobby}) names the * pool that players fall back to, and {@code GRUS_MAX_PLAYERS} (default 500) is the proxy capacity. + * {@code GRUS_SHARD_POOL} enables {@code /region } for that sharded pool. */ @Plugin( id = "grus", @@ -48,6 +49,8 @@ public final class GrusVelocity { static final String ENV_FALLBACK_POOL = "GRUS_FALLBACK_POOL"; static final String DEFAULT_FALLBACK_POOL = "lobby"; + /** Pool whose region cells {@code /region} resolves; without it the command is not registered. */ + static final String ENV_SHARD_POOL = "GRUS_SHARD_POOL"; static final String ENV_MAX_PLAYERS = "GRUS_MAX_PLAYERS"; static final int DEFAULT_MAX_PLAYERS = 500; /** Ready calls before giving up; with the default backoff this covers several minutes of controller outage. */ @@ -81,6 +84,7 @@ public void onInitialize(ProxyInitializeEvent event) { EventStream stream = EventStream.start(config.get(), List.of("instance.*", NetworkStatus.EVENT_TYPE), new Listener(client, servers, network), Backoff.defaults()); + registerRegionCommand(client); Thread.ofVirtual().name("grus-ready").start(() -> reportReady(client)); reporter.start(); @@ -150,6 +154,17 @@ private Optional fallback( .flatMap(instance -> proxy.getServer(instance.id())); } + private void registerRegionCommand(GrusClient client) { + String pool = System.getenv(ENV_SHARD_POOL); + if (pool == null || pool.isBlank()) { + return; + } + var manager = proxy.getCommandManager(); + manager.register(manager.metaBuilder("region").plugin(this).build(), + new RegionCommand(proxy, new RegionLookup(client, pool.trim()), logger)); + logger.info("Grus /region command enabled for pool {}", pool.trim()); + } + private void reportReady(GrusClient client) { try { client.readyWithRetry(Backoff.defaults(), READY_ATTEMPTS); diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionCommand.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionCommand.java new file mode 100644 index 0000000..e7bc3e4 --- /dev/null +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionCommand.java @@ -0,0 +1,79 @@ +package net.onelitefeather.grus.velocity; + +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import net.kyori.adventure.text.Component; +import net.onelitefeather.grus.sdk.GrusException; +import org.slf4j.Logger; + +import java.util.List; +import java.util.OptionalInt; + +/** + * {@code /region } connects the player to the server that owns the block position in the sharded pool + * named by {@code GRUS_SHARD_POOL}. + */ +public final class RegionCommand implements SimpleCommand { + + static final String PERMISSION = "grus.region"; + + private final ProxyServer proxy; + private final RegionLookup lookup; + private final Logger logger; + + public RegionCommand(ProxyServer proxy, RegionLookup lookup, Logger logger) { + this.proxy = proxy; + this.lookup = lookup; + this.logger = logger; + } + + @Override + public boolean hasPermission(Invocation invocation) { + return invocation.source().hasPermission(PERMISSION); + } + + @Override + public void execute(Invocation invocation) { + if (!(invocation.source() instanceof Player player)) { + invocation.source().sendMessage(Component.text("Only players can use /region.")); + return; + } + String[] args = invocation.arguments(); + OptionalInt x = args.length == 2 ? parseCoordinate(args[0]) : OptionalInt.empty(); + OptionalInt z = args.length == 2 ? parseCoordinate(args[1]) : OptionalInt.empty(); + if (x.isEmpty() || z.isEmpty()) { + player.sendMessage(Component.text("Usage: /region (block coordinates)")); + return; + } + // The controller call blocks, so it must not run on Velocity's command thread. + Thread.ofVirtual().name("grus-region").start(() -> connect(player, x.getAsInt(), z.getAsInt())); + } + + private void connect(Player player, int x, int z) { + try { + lookup.find(x, z).ifPresentOrElse( + owner -> proxy.getServer(owner.instance()).ifPresentOrElse( + server -> player.createConnectionRequest(server).fireAndForget(), + () -> player.sendMessage(Component.text("The server of that region is not available yet."))), + () -> player.sendMessage(Component.text("No server serves that position right now."))); + } catch (GrusException e) { + logger.warn("Grus region lookup failed with status {}: {}", e.status(), e.getMessage()); + player.sendMessage(Component.text("The region lookup failed, try again later.")); + } + } + + @Override + public List suggest(Invocation invocation) { + return List.of(); + } + + /** Parses a block coordinate; empty when the text is not an integer. */ + static OptionalInt parseCoordinate(String text) { + try { + return OptionalInt.of(Integer.parseInt(text.trim())); + } catch (NumberFormatException e) { + return OptionalInt.empty(); + } + } +} diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionLookup.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionLookup.java new file mode 100644 index 0000000..9567a4b --- /dev/null +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/RegionLookup.java @@ -0,0 +1,82 @@ +package net.onelitefeather.grus.velocity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.onelitefeather.grus.sdk.GrusClient; +import net.onelitefeather.grus.sdk.GrusException; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * Asks the controller which instance serves a block position of a sharded pool + * ({@code GET /v1/pools/{pool}/cells/at?x=&z=}). + */ +public final class RegionLookup { + + private static final ObjectMapper MAPPER = new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + /** The cell that owns a position and the instance that serves it. */ + @JsonIgnoreProperties(ignoreUnknown = true) + public record Owner(String cell, String instance, String address) { + } + + private final GrusClient client; + private final String pool; + + public RegionLookup(GrusClient client, String pool) { + this.client = Objects.requireNonNull(client, "client"); + this.pool = Objects.requireNonNull(pool, "pool"); + } + + /** + * Resolves block coordinates. + * + * @return the owner, or empty when no cell covers the position (404) or its cell has no Ready instance yet (409) + * @throws GrusException on any other controller error + */ + public Optional find(int x, int z) { + try { + return Optional.of(parse(client.get(path(pool), query(x, z)))); + } catch (GrusException e) { + if (e.status() == 404 || e.status() == 409) { + return Optional.empty(); + } + throw e; + } + } + + /** Path of the cell lookup of a pool; the pool name is percent-encoded. */ + static String path(String pool) { + return "/v1/pools/" + URLEncoder.encode(pool, StandardCharsets.UTF_8).replace("+", "%20") + "/cells/at"; + } + + /** Query parameters of the lookup. Coordinates are block coordinates; the controller converts to chunks. */ + static Map query(int x, int z) { + return Map.of("x", Integer.toString(x), "z", Integer.toString(z)); + } + + /** + * Parses the answer of the lookup. + * + * @throws IllegalArgumentException when the body is not a cell with an instance + */ + static Owner parse(String body) { + Owner owner; + try { + owner = MAPPER.readValue(body, Owner.class); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("not a cell answer: " + e.getOriginalMessage(), e); + } + if (owner == null || owner.instance() == null || owner.instance().isBlank()) { + throw new IllegalArgumentException("cell answer has no instance"); + } + return owner; + } +} diff --git a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/RegionLookupTest.java b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/RegionLookupTest.java new file mode 100644 index 0000000..aab2006 --- /dev/null +++ b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/RegionLookupTest.java @@ -0,0 +1,59 @@ +package net.onelitefeather.grus.velocity; + +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.OptionalInt; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class RegionLookupTest { + + @Test + void pathNamesThePoolAndTheLookupRoute() { + assertEquals("/v1/pools/world/cells/at", RegionLookup.path("world"), + "the lookup must use the cells/at route of the pool"); + } + + @Test + void pathEncodesUnusualPoolNames() { + assertEquals("/v1/pools/a%20b%2Fc/cells/at", RegionLookup.path("a b/c"), + "spaces and slashes in the pool name must be percent-encoded"); + } + + @Test + void queryCarriesNegativeBlockCoordinatesAsGiven() { + assertEquals(Map.of("x", "-100", "z", "250"), RegionLookup.query(-100, 250), + "x and z must be sent as plain integers, the controller converts them to chunks"); + } + + @Test + void parseReadsCellInstanceAndAddress() { + RegionLookup.Owner owner = RegionLookup.parse(""" + {"cell":"r1","bounds":{"minX":32,"minZ":0,"maxX":63,"maxZ":31}, + "instance":"world-ab12c","address":"10.0.0.7:25565"}"""); + + assertEquals(new RegionLookup.Owner("r1", "world-ab12c", "10.0.0.7:25565"), owner, + "the answer must be mapped, unknown fields such as bounds ignored"); + } + + @Test + void parseRejectsAnAnswerWithoutInstance() { + assertThrows(IllegalArgumentException.class, () -> RegionLookup.parse("{\"cell\":\"r1\"}"), + "a cell without an instance cannot be connected to"); + } + + @Test + void parseRejectsInvalidJson() { + assertThrows(IllegalArgumentException.class, () -> RegionLookup.parse(""), + "a body that is not JSON must be rejected"); + } + + @Test + void parseCoordinateAcceptsIntegersOnly() { + assertEquals(OptionalInt.of(-42), RegionCommand.parseCoordinate("-42"), "negative integers are valid"); + assertEquals(OptionalInt.empty(), RegionCommand.parseCoordinate("4.5"), "decimals are not block coordinates"); + assertEquals(OptionalInt.empty(), RegionCommand.parseCoordinate("abc"), "words are not coordinates"); + } +} diff --git a/web/app/types/grus-api.d.ts b/web/app/types/grus-api.d.ts index 5b6abee..893d35e 100644 --- a/web/app/types/grus-api.d.ts +++ b/web/app/types/grus-api.d.ts @@ -392,6 +392,43 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/pools/{pool}/cells": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List the cells of a sharded pool with the instance that serves each */ + get: operations["list-pool-cells"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/pools/{pool}/cells/at": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Find the cell and instance that own a block position + * @description 404 when no cell covers the block, 409 when the cell has no Ready instance yet. + */ + get: operations["get-pool-cell-at"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/pools/{pool}/maintenance": { parameters: { query?: never; @@ -614,6 +651,52 @@ export interface components { */ memoryMiB?: number; }; + Cell: { + /** + * Format: int64 + * @description Largest chunk x of the cell + */ + maxX: number; + /** + * Format: int64 + * @description Largest chunk z of the cell + */ + maxZ: number; + /** + * Format: int64 + * @description Smallest chunk x of the cell + */ + minX: number; + /** + * Format: int64 + * @description Smallest chunk z of the cell + */ + minZ: number; + /** @description Cell name; assigned to exactly one Ready instance */ + name: string; + }; + CellBounds: { + /** Format: int64 */ + maxX: number; + /** Format: int64 */ + maxZ: number; + /** Format: int64 */ + minX: number; + /** Format: int64 */ + minZ: number; + }; + CellInfo: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/CellInfo.json + */ + readonly $schema?: string; + address?: string; + bounds: components["schemas"]["CellBounds"]; + cell: string; + instance?: string; + }; Command: { instance: string; line: string; @@ -1070,11 +1153,11 @@ export interface components { Sharding: { /** * Format: int64 - * @description Cell edge length in chunks + * @description Cell edge length in chunks, used when cells are generated (default 32) */ cellSize?: number; - /** @description Explicit cell names */ - cells?: string[] | null; + /** @description Static cell list; bounds are chunk coordinates */ + cells?: components["schemas"]["Cell"][] | null; }; StatusUpdate: { /** @@ -2058,6 +2141,102 @@ export interface operations { }; }; }; + "list-pool-cells": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Pool name */ + pool: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CellInfo"][] | null; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "get-pool-cell-at": { + parameters: { + query: { + /** @description Block x coordinate */ + x: number; + /** @description Block z coordinate */ + z: number; + }; + header?: never; + path: { + /** @description Pool name */ + pool: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CellInfo"]; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + /** @description Conflict */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + /** @description Unprocessable Entity */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + /** @description Internal Server Error */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "set-pool-maintenance": { parameters: { query?: never;