diff --git a/README.md b/README.md index a81581c..566e8dd 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,23 @@ With `GRUS_URL` and `GRUS_TOKEN` set, the stub posts `/v1/self/ready` once the l controller accepts it), sends `PUT /v1/self/status` every 5 seconds, and on SIGTERM posts `/v1/self/shutdown` best effort before exiting. +## Private servers + +A pool with a `private` section (`quotaPerOwner`, default 1; `idleTimeout`, default 10m) is not autoscaled: +`scaling.min` and `scaling.buffer` must be 0 and instances are created on demand. + +```sh +grus private create home --owner # starts the server, or shows the one that already runs +grus private list --owner +``` + +`POST /v1/private-servers` returns the owner's live instance in the pool (200) or starts one (201); an owner +at the quota gets 409. `DELETE /v1/private-servers/{id}` drains the server. An instance without players for +`idleTimeout` is stopped and the `private.idle-stop` event is published. + +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. + ## License Apache License 2.0. See [LICENSE](LICENSE). diff --git a/api/openapi.yaml b/api/openapi.yaml index 66d4c62..98d6107 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -744,11 +744,37 @@ components: additionalProperties: false properties: idleTimeout: + description: Stop an instance after this long without players (default 10m) type: string quotaPerOwner: + description: Instances one owner may have at once (default 1) format: int64 type: integer type: object + PrivateServerBody: + additionalProperties: false + properties: + $schema: + description: A URL to the JSON Schema for this object. + examples: + - https://example.com/schemas/PrivateServerBody.json + format: uri + readOnly: true + type: string + owner: + description: Owner of the server, e.g. a player uuid + maxLength: 63 + minLength: 1 + pattern: ^[A-Za-z0-9][A-Za-z0-9._-]*$ + type: string + pool: + description: Private pool (a pool with a private section) + minLength: 1 + type: string + required: + - pool + - owner + type: object RegisterRequest: additionalProperties: false properties: @@ -1765,6 +1791,107 @@ paths: security: - bearer: [] summary: Enable or disable maintenance for a pool + /v1/private-servers: + get: + operationId: list-private-servers + parameters: + - description: Only the private servers of this owner + explode: false + in: query + name: owner + schema: + description: Only the private servers of this owner + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/Instance" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: List private servers, optionally of one owner + post: + description: Answers 201 when an instance was started and 200 when the owner's live instance is returned. 409 when the owner is at the quota of the pool. + operationId: create-private-server + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/PrivateServerBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Instance" + 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: Start a private server for an owner, or return the one the owner already has + /v1/private-servers/{id}: + delete: + operationId: stop-private-server + parameters: + - description: Instance id + in: path + name: id + required: true + schema: + description: Instance id + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Instance" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - bearer: [] + summary: Stop a private server once its players left (drain) /v1/self: get: operationId: get-self diff --git a/internal/api/api.go b/internal/api/api.go index d3d8291..9d6f9a9 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -102,6 +102,7 @@ func build(mux *http.ServeMux, s *server, version string) huma.API { s.registerPools(api) s.registerDeclarations(api) s.registerInstances(api) + s.registerPrivateServers(api) s.registerSelf(api) s.registerTemplates(api) s.registerAgents(api) diff --git a/internal/api/errors.go b/internal/api/errors.go index a054219..76e271e 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -26,7 +26,7 @@ func mapError(log *slog.Logger, err error) huma.StatusError { return huma.Error422UnprocessableEntity(ve.Error(), details...) case errors.Is(err, controller.ErrNotFound), errors.Is(err, store.ErrNotFound), errors.Is(err, templates.ErrNotFound): return huma.Error404NotFound("not found") - case errors.Is(err, controller.ErrHasPlayers), errors.Is(err, controller.ErrInvalidState), errors.Is(err, controller.ErrLimit), errors.Is(err, controller.ErrManagedElsewhere): + case errors.Is(err, controller.ErrHasPlayers), errors.Is(err, controller.ErrInvalidState), errors.Is(err, controller.ErrLimit), errors.Is(err, controller.ErrQuota), errors.Is(err, controller.ErrManagedElsewhere): return huma.Error409Conflict(err.Error()) default: log.Error("api: request failed", "err", err) diff --git a/internal/api/fakes_test.go b/internal/api/fakes_test.go index ee8b92a..01ecaa6 100644 --- a/internal/api/fakes_test.go +++ b/internal/api/fakes_test.go @@ -55,6 +55,11 @@ type fakeService struct { logsFollow bool logsBody string logsErr error + + privatePool, privateOwner string + privateErr error + privateCreated bool + privateOwnerFilter string } func newFakeService() *fakeService { @@ -155,6 +160,24 @@ func (f *fakeService) Logs(_ context.Context, _ string, tail int, follow bool) ( return io.NopCloser(strings.NewReader(f.logsBody)), nil } +func (f *fakeService) CreatePrivateServer(_ context.Context, pool, owner string) (model.Instance, bool, error) { + f.privatePool, f.privateOwner = pool, owner + if f.privateErr != nil { + return model.Instance{}, false, f.privateErr + } + return model.Instance{ID: pool + "-x", Pool: pool, Labels: map[string]string{model.LabelOwner: owner}}, f.privateCreated, nil +} + +func (f *fakeService) ListPrivateServers(_ context.Context, owner string) ([]model.Instance, error) { + f.privateOwnerFilter = owner + return nil, nil +} + +func (f *fakeService) StopPrivateServer(_ context.Context, id string) (model.Instance, error) { + f.stopID = id + return model.Instance{ID: id}, f.stopErr +} + 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/private.go b/internal/api/private.go new file mode 100644 index 0000000..2c5ab83 --- /dev/null +++ b/internal/api/private.go @@ -0,0 +1,73 @@ +package api + +import ( + "context" + "net/http" + + "github.com/danielgtaylor/huma/v2" + + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +type privateServerInput struct { + Body privateServerBody +} + +type privateServerBody struct { + Pool string `json:"pool" minLength:"1" doc:"Private pool (a pool with a private section)"` + Owner string `json:"owner" minLength:"1" maxLength:"63" pattern:"^[A-Za-z0-9][A-Za-z0-9._-]*$" doc:"Owner of the server, e.g. a player uuid"` +} + +type privateServerOutput struct { + Status int + Body model.Instance +} + +type listPrivateServersInput struct { + Owner string `query:"owner" doc:"Only the private servers of this owner"` +} + +func (s *server) registerPrivateServers(api huma.API) { + huma.Register(api, operation(scopeInstancesWrite, huma.Operation{ + OperationID: "create-private-server", Method: http.MethodPost, Path: "/v1/private-servers", + Summary: "Start a private server for an owner, or return the one the owner already has", + Description: "Answers 201 when an instance was started and 200 when the owner's live instance is returned. " + + "409 when the owner is at the quota of the pool.", + Errors: []int{http.StatusNotFound, http.StatusConflict, http.StatusUnprocessableEntity}, + }), func(ctx context.Context, in *privateServerInput) (*privateServerOutput, error) { + inst, created, err := s.svc.CreatePrivateServer(ctx, in.Body.Pool, in.Body.Owner) + if err != nil { + return nil, mapError(s.log, err) + } + status := http.StatusOK + if created { + status = http.StatusCreated + } + return &privateServerOutput{Status: status, Body: inst}, nil + }) + + huma.Register(api, operation(scopeInstancesRead, huma.Operation{ + OperationID: "list-private-servers", Method: http.MethodGet, Path: "/v1/private-servers", + Summary: "List private servers, optionally of one owner", + }), func(ctx context.Context, in *listPrivateServersInput) (*instancesOutput, error) { + list, err := s.svc.ListPrivateServers(ctx, in.Owner) + if err != nil { + return nil, mapError(s.log, err) + } + if list == nil { + list = []model.Instance{} + } + return &instancesOutput{Body: list}, nil + }) + + huma.Register(api, operation(scopeInstancesWrite, huma.Operation{ + OperationID: "stop-private-server", Method: http.MethodDelete, Path: "/v1/private-servers/{id}", + Summary: "Stop a private server once its players left (drain)", + }), func(ctx context.Context, in *instancePath) (*instanceOutput, error) { + inst, err := s.svc.StopPrivateServer(ctx, in.ID) + if err != nil { + return nil, mapError(s.log, err) + } + return &instanceOutput{Body: inst}, nil + }) +} diff --git a/internal/api/private_test.go b/internal/api/private_test.go new file mode 100644 index 0000000..f777ea8 --- /dev/null +++ b/internal/api/private_test.go @@ -0,0 +1,88 @@ +package api + +import ( + "net/http" + "testing" + + "github.com/OneLiteFeatherNET/grus/internal/controller" +) + +const privateBody = `{"pool":"home","owner":"alex"}` + +func TestCreatePrivateServerAnswers201ForANewInstance(t *testing.T) { + fx := newFixture(t, Config{}, nil) + fx.svc.privateCreated = true + + rec := fx.call(t, http.MethodPost, "/v1/private-servers", adminToken, "application/json", privateBody) + + if rec.Code != http.StatusCreated { + t.Fatalf("status = %d, want 201; body %s", rec.Code, rec.Body) + } + if fx.svc.privatePool != "home" || fx.svc.privateOwner != "alex" { + t.Errorf("service got pool %q owner %q", fx.svc.privatePool, fx.svc.privateOwner) + } +} + +func TestCreatePrivateServerAnswers200ForTheExistingInstance(t *testing.T) { + fx := newFixture(t, Config{}, nil) + + rec := fx.call(t, http.MethodPost, "/v1/private-servers", adminToken, "application/json", privateBody) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body) + } +} + +func TestCreatePrivateServerQuotaAnswers409(t *testing.T) { + fx := newFixture(t, Config{}, nil) + fx.svc.privateErr = controller.ErrQuota + + rec := fx.call(t, http.MethodPost, "/v1/private-servers", adminToken, "application/json", privateBody) + + if rec.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409", rec.Code) + } +} + +func TestCreatePrivateServerRejectsABadOwner(t *testing.T) { + fx := newFixture(t, Config{}, nil) + + rec := fx.call(t, http.MethodPost, "/v1/private-servers", adminToken, "application/json", `{"pool":"home","owner":"a b"}`) + + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("status = %d, want 422", rec.Code) + } +} + +func TestListPrivateServersPassesTheOwnerAndReturnsAnArray(t *testing.T) { + fx := newFixture(t, Config{}, nil) + + rec := fx.call(t, http.MethodGet, "/v1/private-servers?owner=alex", adminToken, "", "") + + if rec.Code != http.StatusOK || rec.Body.String() != "[]\n" && rec.Body.String() != "[]" { + t.Fatalf("status %d body %q, want 200 and []", rec.Code, rec.Body) + } + if fx.svc.privateOwnerFilter != "alex" { + t.Errorf("owner filter = %q, want alex", fx.svc.privateOwnerFilter) + } +} + +func TestStopPrivateServerCallsTheService(t *testing.T) { + fx := newFixture(t, Config{}, nil) + + rec := fx.call(t, http.MethodDelete, "/v1/private-servers/home-x", adminToken, "", "") + + if rec.Code != http.StatusOK || fx.svc.stopID != "home-x" { + t.Fatalf("status %d stopID %q, want 200 and home-x", rec.Code, fx.svc.stopID) + } +} + +func TestPrivateServerRoutesNeedAToken(t *testing.T) { + fx := newFixture(t, Config{}, nil) + + rec := fx.call(t, http.MethodPost, "/v1/private-servers", gameToken, "application/json", privateBody) + + if rec.Code != http.StatusForbidden { + t.Fatalf("instance token status = %d, want 403 (no instances:write)", rec.Code) + } +} diff --git a/internal/autoscale/autoscale.go b/internal/autoscale/autoscale.go index 9b561ec..0985167 100644 --- a/internal/autoscale/autoscale.go +++ b/internal/autoscale/autoscale.go @@ -45,6 +45,16 @@ var activeStates = map[model.State]bool{ func Decide(v PoolView, now time.Time) Decision { spec := v.Spec static := spec.Mode == model.ModeStatic + if spec.Private != nil { + // Private pools are created on demand and stopped by the idle rule of the reconciler. + n := 0 + for _, inst := range v.Instances { + if activeStates[inst.State] { + n++ + } + } + return Decision{Desired: n, Current: n, Inputs: map[string]int{"active": n}} + } var ( active int diff --git a/internal/autoscale/autoscale_test.go b/internal/autoscale/autoscale_test.go index 6795437..9d3c8f7 100644 --- a/internal/autoscale/autoscale_test.go +++ b/internal/autoscale/autoscale_test.go @@ -294,3 +294,15 @@ func threeEmptyReady() []model.Instance { inst("young", model.StateReady, 0, t0.Add(-time.Minute)), } } + +func TestPrivatePoolIsNeverScaled(t *testing.T) { + spec := dynamicSpec(0, 5, 0) + spec.Private = &model.Private{} + insts := []model.Instance{inst("home-a", model.StateReady, 0, t0), inst("home-b", model.StateAllocated, 3, t0)} + + d := Decide(PoolView{Name: "home", Spec: spec, Instances: insts}, t0.Add(time.Hour)) + + if d.Start != 0 || len(d.Drain) != 0 || d.Direction != "" { + t.Fatalf("decision for a private pool = %+v, want no start, drain or direction", d) + } +} diff --git a/internal/cli/private.go b/internal/cli/private.go new file mode 100644 index 0000000..cb5a5b1 --- /dev/null +++ b/internal/cli/private.go @@ -0,0 +1,78 @@ +package cli + +import ( + "errors" + "fmt" + + "github.com/spf13/cobra" +) + +var privateColumns = []column{ + {"ID", field("id")}, {"POOL", field("pool")}, {"OWNER", field("labels", "grus.olf/owner")}, + {"STATE", field("state")}, {"PLAYERS", field("players")}, {"ADDRESS", field("address")}, +} + +func newPrivateCmd(env *Env, o *opts) *cobra.Command { + cmd := &cobra.Command{ + Use: "private", + Short: "Start and list private servers (instances owned by one player)", + } + cmd.AddCommand(newPrivateCreateCmd(env, o), newPrivateListCmd(env, o)) + return cmd +} + +func newPrivateCreateCmd(env *Env, o *opts) *cobra.Command { + var owner string + cmd := &cobra.Command{ + Use: "create --owner ", + Short: "Start the private server of an owner, or show the one that already runs", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if owner == "" { + return errors.New("give --owner") + } + c, _, err := o.client(env) + if err != nil { + return err + } + inst, created, err := c.CreatePrivateServer(cmdContext(cmd), args[0], owner) + if err != nil { + return err + } + if o.output != formatTable { + return printObject(cmd, o.output, inst) + } + verb := "already running" + if created { + verb = "started" + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "instance/%s %s (%s)\n", text(inst["id"]), verb, text(inst["state"])) + return err + }, + ValidArgsFunction: completeFirstArg(completeResource(env, o, "pools")), + } + cmd.Flags().StringVar(&owner, "owner", "", "owner of the server, e.g. a player uuid") + return cmd +} + +func newPrivateListCmd(env *Env, o *opts) *cobra.Command { + var owner string + cmd := &cobra.Command{ + Use: "list [--owner ]", + Short: "List private servers", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + c, _, err := o.client(env) + if err != nil { + return err + } + list, err := c.PrivateServers(cmdContext(cmd), owner) + if err != nil { + return err + } + return printList(cmd, o.output, list, privateColumns) + }, + } + cmd.Flags().StringVar(&owner, "owner", "", "only the servers of this owner") + return cmd +} diff --git a/internal/cli/private_test.go b/internal/cli/private_test.go new file mode 100644 index 0000000..6c3b4d9 --- /dev/null +++ b/internal/cli/private_test.go @@ -0,0 +1,69 @@ +package cli + +import ( + "encoding/json" + "io" + "net/http" + "strings" + "testing" +) + +const privateInstanceJSON = `{"id":"home-abc12","pool":"home","state":"Starting","players":0,"labels":{"grus.olf/owner":"alex"}}` + +func TestPrivateCreateStartsAServerForTheOwner(t *testing.T) { + var got map[string]string + mux := http.NewServeMux() + mux.HandleFunc("POST /v1/private-servers", func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &got) + w.WriteHeader(http.StatusCreated) + io.WriteString(w, privateInstanceJSON) + }) + h := newHarness(t, mux) + + out := h.ok("", "private", "create", "home", "--owner", "alex") + + if got["pool"] != "home" || got["owner"] != "alex" { + t.Errorf("request body = %v", got) + } + if !strings.Contains(out, "home-abc12 started") { + t.Errorf("output = %q, want the instance reported as started", out) + } +} + +func TestPrivateCreateReportsAnExistingServer(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("POST /v1/private-servers", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, privateInstanceJSON) }) + h := newHarness(t, mux) + + if out := h.ok("", "private", "create", "home", "--owner", "alex"); !strings.Contains(out, "already running") { + t.Errorf("output = %q, want already running", out) + } +} + +func TestPrivateCreateNeedsAnOwner(t *testing.T) { + h := newHarness(t, http.NewServeMux()) + + if _, _, err := h.run("", "private", "create", "home"); err == nil { + t.Fatal("create without --owner succeeded") + } +} + +func TestPrivateListPassesTheOwnerFilter(t *testing.T) { + var q string + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/private-servers", func(w http.ResponseWriter, r *http.Request) { + q = r.URL.RawQuery + io.WriteString(w, "["+privateInstanceJSON+"]") + }) + h := newHarness(t, mux) + + out := h.ok("", "private", "list", "--owner", "alex") + + if q != "owner=alex" { + t.Errorf("query = %q", q) + } + if !strings.Contains(out, "home-abc12") || !strings.Contains(out, "alex") { + t.Errorf("table lacks the server and its owner:\n%s", out) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 8895c28..70cc95d 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), newLoginCmd(env), newConfigCmd(env), + newNetworkCmd(env, &o), newPrivateCmd(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 33d753c..24406fa 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -298,3 +298,37 @@ func (c *Client) stream(ctx context.Context, path, lastID string, fn func(Event) } return err } + +// CreatePrivateServer starts the private server of owner in pool or returns the one the owner already has. +// created tells which of the two happened. +func (c *Client) CreatePrivateServer(ctx context.Context, pool, owner string) (inst Object, created bool, err error) { + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + req, err := c.newRequest(ctx, http.MethodPost, "/v1/private-servers", nil, map[string]string{"pool": pool, "owner": owner}) + if err != nil { + return nil, false, err + } + resp, err := c.send(req) + if err != nil { + return nil, false, err + } + defer resp.Body.Close() + if err := json.NewDecoder(resp.Body).Decode(&inst); err != nil { + return nil, false, err + } + return inst, resp.StatusCode == http.StatusCreated, nil +} + +// PrivateServers lists the private servers, of one owner when owner is not empty. +func (c *Client) PrivateServers(ctx context.Context, owner string) ([]Object, error) { + q := url.Values{} + if owner != "" { + q.Set("owner", owner) + } + var out []Object + err := c.call(ctx, http.MethodGet, "/v1/private-servers", q, nil, &out) + if err != nil && isStatus(err, http.StatusNotFound) { + return nil, &NotSupportedError{What: "private servers"} + } + return out, err +} diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 0c974c9..5e92a35 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -192,3 +192,23 @@ func TestTemplates(t *testing.T) { t.Errorf("got %v err %v", got, err) } } + +func TestCreatePrivateServerTellsCreatedFromExisting(t *testing.T) { + for _, tc := range []struct { + status int + created bool + }{{http.StatusCreated, true}, {http.StatusOK, false}} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(`{"id":"home-1"}`)) + })) + c := New(srv.URL, "t", srv.Client()) + + inst, created, err := c.CreatePrivateServer(context.Background(), "home", "alex") + srv.Close() + + if err != nil || created != tc.created || inst["id"] != "home-1" { + t.Errorf("status %d: got (%v, %v, %v), want created=%v", tc.status, inst, created, err, tc.created) + } + } +} diff --git a/internal/controller/controller.go b/internal/controller/controller.go index bc9de98..fa55c93 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log/slog" + "maps" "math/big" "strings" "sync" @@ -61,6 +62,7 @@ type Controller struct { resolveWarned map[string]string // per pool: last unresolvable reason already reported lastNetwork model.NetworkStatus // last network.players payload adoptHosts map[string]bool // hosts whose unknown instances are adopted once they can be listed + idleSince map[string]time.Time // per private instance: since when it has had no players } // New builds a controller. Call Adopt (or Run, which adopts first) before reconciling. @@ -93,6 +95,7 @@ func New(cfg Config, st store.Store, drv driver.Driver, tpl templates.Store, pub lastPublished: make(map[string]time.Time), resolveWarned: make(map[string]string), adoptHosts: make(map[string]bool), + idleSince: make(map[string]time.Time), } } @@ -342,6 +345,11 @@ func (c *Controller) lifecycleOf(ctx context.Context, pool string) model.Lifecyc // createInstance records a new Requested instance, resolves templates, schedules it and starts it through // the driver. Template and start failures end in Failed, not in an error; only storage errors are returned. func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model.Instance, error) { + return c.createInstanceWithLabels(ctx, pool, nil) +} + +// createInstanceWithLabels is createInstance for an instance that starts with labels (e.g. its owner). +func (c *Controller) createInstanceWithLabels(ctx context.Context, pool model.Pool, labels map[string]string) (model.Instance, error) { spec := pool.Spec.WithDefaults() now := c.clock.Now() @@ -358,7 +366,7 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model sum := sha256.Sum256([]byte(token)) tokenHash := hex.EncodeToString(sum[:]) - inst, err := c.insertRequested(ctx, pool, spec, now, tokenHash) + inst, err := c.insertRequested(ctx, pool, spec, now, tokenHash, labels) if err != nil { return model.Instance{}, err } @@ -390,7 +398,7 @@ func (c *Controller) createInstance(ctx context.Context, pool model.Pool) (model } // insertRequested stores a new Requested instance with a fresh id and publishes instance.created. -func (c *Controller) insertRequested(ctx context.Context, pool model.Pool, spec model.PoolSpec, now time.Time, tokenHash string) (model.Instance, error) { +func (c *Controller) insertRequested(ctx context.Context, pool model.Pool, spec model.PoolSpec, now time.Time, tokenHash string, labels map[string]string) (model.Instance, error) { for attempt := 0; attempt < maxIDAttempts; attempt++ { id, err := c.newID(ctx, pool.Name, spec.Mode) if err != nil { @@ -406,6 +414,7 @@ func (c *Controller) insertRequested(ctx context.Context, pool model.Pool, spec StateSince: now, CreatedAt: now, MaxPlayers: spec.Scaling.Capacity, + Labels: maps.Clone(labels), TokenHash: tokenHash, } err = c.st.CreateInstance(ctx, inst) diff --git a/internal/controller/private.go b/internal/controller/private.go new file mode 100644 index 0000000..eeafed2 --- /dev/null +++ b/internal/controller/private.go @@ -0,0 +1,168 @@ +package controller + +import ( + "context" + "fmt" + "regexp" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/model" + "github.com/OneLiteFeatherNET/grus/internal/state" + "github.com/OneLiteFeatherNET/grus/internal/store" +) + +// ownerRE limits owners to what fits a label value (player uuids and names). +var ownerRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`) + +// ownerOf returns the owner label of an instance. +func ownerOf(inst model.Instance) string { return inst.Labels[model.LabelOwner] } + +// usable reports whether a private instance can still take its owner: it is on its way up or running. +func usable(inst model.Instance) bool { + switch inst.State { + case model.StateRequested, model.StateScheduled, model.StatePreparing, model.StateStarting, + model.StateReady, model.StateAllocated: + return true + } + return false +} + +// CreatePrivateServer returns the live instance of owner in pool, or starts one. An owner with an instance +// that is draining or stopping has to wait until it is gone once the quota is used up. +func (c *Controller) CreatePrivateServer(ctx context.Context, pool, owner string) (model.Instance, bool, error) { + if !ownerRE.MatchString(owner) { + return model.Instance{}, false, &ValidationError{Kind: "private server", Fields: []model.FieldError{ + {Field: "owner", Message: "must match " + ownerRE.String()}}} + } + c.mu.Lock() + defer c.mu.Unlock() + p, err := c.st.GetPool(ctx, pool) + if err != nil { + return model.Instance{}, false, mapErr(err) + } + spec := p.Spec.WithDefaults() + if spec.Private == nil { + return model.Instance{}, false, &ValidationError{Kind: "private server", Fields: []model.FieldError{ + {Field: "pool", Message: "pool " + pool + " has no private section"}}} + } + insts, err := c.listAll(ctx) + if err != nil { + return model.Instance{}, false, err + } + owned, live := 0, 0 + for _, inst := range insts { + if inst.State.Terminal() || inst.Pool != pool { + continue + } + live++ + if ownerOf(inst) != owner { + continue + } + if usable(inst) { + return inst, false, nil + } + owned++ + } + if owned >= spec.Private.QuotaPerOwner { + return model.Instance{}, false, fmt.Errorf("%w: %s still has %d instance(s) in %s that are stopping", ErrQuota, owner, owned, pool) + } + if p.Maintenance { + return model.Instance{}, false, fmt.Errorf("%w: pool %s is in maintenance", ErrInvalidState, pool) + } + if live >= spec.Scaling.Max || countLive(insts) >= c.cfg.MaxInstances { + return model.Instance{}, false, ErrLimit + } + inst, err := c.createInstanceWithLabels(ctx, p, map[string]string{model.LabelOwner: owner}) + if err != nil { + return model.Instance{}, false, mapErr(err) + } + c.Trigger() + return inst, true, nil +} + +// ListPrivateServers lists the non-terminal instances that have an owner, optionally of one owner. +func (c *Controller) ListPrivateServers(ctx context.Context, owner string) ([]model.Instance, error) { + insts, err := c.st.ListInstances(ctx, store.InstanceFilter{}) + if err != nil { + return nil, mapErr(err) + } + var out []model.Instance + for _, inst := range insts { + if inst.State.Terminal() || ownerOf(inst) == "" || (owner != "" && ownerOf(inst) != owner) { + continue + } + out = append(out, inst) + } + return out, nil +} + +// StopPrivateServer drains the private instance id. An instance that is not private is reported as unknown. +func (c *Controller) StopPrivateServer(ctx context.Context, id string) (model.Instance, error) { + c.mu.Lock() + defer c.mu.Unlock() + inst, err := c.st.GetInstance(ctx, id) + if err != nil { + return model.Instance{}, mapErr(err) + } + if ownerOf(inst) == "" { + return model.Instance{}, fmt.Errorf("%w: %s is not a private server", ErrNotFound, id) + } + if inst.State.Terminal() { + return model.Instance{}, fmt.Errorf("%w: instance is %s", ErrInvalidState, inst.State) + } + switch { + case inst.State == model.StateReady: + inst, err = c.apply(ctx, inst, state.InDrain, "private server stop requested") + case inst.State == model.StateDraining || inst.State == model.StateStopping: + // already on its way out + default: + inst, err = c.stop(ctx, inst, state.InStop, "private server stop requested", c.lifecycleOf(ctx, inst.Pool)) + } + if err != nil { + return model.Instance{}, mapErr(err) + } + c.Trigger() + return inst, nil +} + +// stopIdlePrivate stops the Ready and Allocated instances of private pools that have had no players for the +// pool's idle timeout. The time an instance became empty is tracked in memory; after a controller restart the +// idle period starts over, which only delays a stop. Callers hold c.mu. +func (c *Controller) stopIdlePrivate(ctx context.Context, insts []model.Instance, specs map[string]model.PoolSpec, unlisted map[string]bool, now time.Time) []error { + var errs []error + seen := make(map[string]bool) + for _, inst := range insts { + spec, ok := specs[inst.Pool] + if !ok || spec.Private == nil || ownerOf(inst) == "" || unlisted[hostOf(inst)] { + continue + } + if inst.State != model.StateReady && inst.State != model.StateAllocated { + continue + } + seen[inst.ID] = true + if inst.Players > 0 { + delete(c.idleSince, inst.ID) + continue + } + since, ok := c.idleSince[inst.ID] + if !ok { + c.idleSince[inst.ID] = now + continue + } + if now.Sub(since) < spec.Private.IdleTimeout.D() { + continue + } + if _, err := c.stop(ctx, inst, state.InStop, "idle", c.lifecycleOf(ctx, inst.Pool)); err != nil { + errs = append(errs, fmt.Errorf("stop idle private instance %s: %w", inst.ID, err)) + continue + } + delete(c.idleSince, inst.ID) + c.pub.Publish(model.EventPrivateIdleStop, model.PrivateIdleStopData{Pool: inst.Pool, Instance: inst.ID, Owner: ownerOf(inst)}) + } + for id := range c.idleSince { + if !seen[id] { + delete(c.idleSince, id) + } + } + return errs +} diff --git a/internal/controller/private_test.go b/internal/controller/private_test.go new file mode 100644 index 0000000..5e6ee20 --- /dev/null +++ b/internal/controller/private_test.go @@ -0,0 +1,222 @@ +package controller + +import ( + "errors" + "testing" + "time" + + "github.com/OneLiteFeatherNET/grus/internal/driver" + "github.com/OneLiteFeatherNET/grus/internal/model" +) + +func privateSpec(quota int, idle time.Duration) model.PoolSpec { + s := dynamicSpec(0, 0) + s.Scaling.Capacity = 0 + s.Private = &model.Private{QuotaPerOwner: quota, IdleTimeout: model.Duration(idle)} + return s +} + +func TestPrivatePoolIsNotAutoscaled(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + + f.reconcile() + + if n := len(f.drv.Started()); n != 0 { + t.Fatalf("started instances = %d, want 0 for a private pool without requests", n) + } +} + +func TestCreatePrivateServerStartsOwnedInstance(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + + inst, created, err := f.c.CreatePrivateServer(f.ctx, "home", "alex") + if err != nil || !created { + t.Fatalf("create = (%v, created %v), want a new instance", err, created) + } + if got := inst.Labels[model.LabelOwner]; got != "alex" { + t.Errorf("owner label = %q, want alex", got) + } + if n := len(f.drv.Started()); n != 1 { + t.Errorf("started instances = %d, want 1", n) + } +} + +func TestCreatePrivateServerReturnsTheExistingInstance(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + first, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + + again, created, err := f.c.CreatePrivateServer(f.ctx, "home", "alex") + + if err != nil || created || again.ID != first.ID { + t.Fatalf("second create = (%s, created %v, %v), want the first instance %s", again.ID, created, err, first.ID) + } + if n := len(f.drv.Started()); n != 1 { + t.Errorf("started instances = %d, want 1", n) + } +} + +func TestCreatePrivateServerRejectsOwnerAtQuotaWhileStopping(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + first, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + f.bringUp(first.ID, "10.0.0.1:25565") + if _, err := f.c.StopPrivateServer(f.ctx, first.ID); err != nil { + t.Fatalf("stop: %v", err) + } + + _, _, err := f.c.CreatePrivateServer(f.ctx, "home", "alex") + + if !errors.Is(err, ErrQuota) { + t.Fatalf("create while the old instance drains = %v, want ErrQuota", err) + } +} + +func TestCreatePrivateServerQuotasAreOwnerSpecific(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + _, _, _ = f.c.CreatePrivateServer(f.ctx, "home", "alex") + + if _, created, err := f.c.CreatePrivateServer(f.ctx, "home", "sam"); err != nil || !created { + t.Fatalf("other owner = (created %v, %v), want a new instance", created, err) + } +} + +func TestCreatePrivateServerNeedsAPrivatePool(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("lobby", dynamicSpec(0, 0)) + + _, _, err := f.c.CreatePrivateServer(f.ctx, "lobby", "alex") + + var ve *ValidationError + if !errors.As(err, &ve) { + t.Fatalf("create in a normal pool = %v, want a validation error", err) + } +} + +func TestCreatePrivateServerUnknownPoolAndBadOwner(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + + if _, _, err := f.c.CreatePrivateServer(f.ctx, "nope", "alex"); !errors.Is(err, ErrNotFound) { + t.Errorf("unknown pool = %v, want ErrNotFound", err) + } + var ve *ValidationError + if _, _, err := f.c.CreatePrivateServer(f.ctx, "home", "a b/c"); !errors.As(err, &ve) { + t.Errorf("bad owner = %v, want a validation error", err) + } +} + +func TestCreatePrivateServerRespectsPoolMax(t *testing.T) { + f := newFixture(t, Config{}) + spec := privateSpec(1, time.Minute) + spec.Scaling.Max = 1 + f.putPool("home", spec) + _, _, _ = f.c.CreatePrivateServer(f.ctx, "home", "alex") + + if _, _, err := f.c.CreatePrivateServer(f.ctx, "home", "sam"); !errors.Is(err, ErrLimit) { + t.Fatalf("create above scaling.max = %v, want ErrLimit", err) + } +} + +func TestListPrivateServersFiltersByOwner(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + f.putPool("lobby", dynamicSpec(1, 0)) + f.reconcile() + _, _, _ = f.c.CreatePrivateServer(f.ctx, "home", "alex") + _, _, _ = f.c.CreatePrivateServer(f.ctx, "home", "sam") + + all, _ := f.c.ListPrivateServers(f.ctx, "") + mine, _ := f.c.ListPrivateServers(f.ctx, "alex") + + if len(all) != 2 || len(mine) != 1 || mine[0].Labels[model.LabelOwner] != "alex" { + t.Fatalf("list = %d all, %d of alex; want 2 and 1 (lobby instances are not private)", len(all), len(mine)) + } +} + +func TestStopPrivateServerDrainsAndRejectsNormalInstances(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + f.putPool("lobby", dynamicSpec(1, 0)) + f.reconcile() + lobbyID := f.instancesOf("lobby")[0].ID + priv, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + f.bringUp(priv.ID, "10.0.0.1:25565") + + got, err := f.c.StopPrivateServer(f.ctx, priv.ID) + if err != nil || got.State != model.StateDraining { + t.Fatalf("stop = (%s, %v), want Draining", got.State, err) + } + if _, err := f.c.StopPrivateServer(f.ctx, lobbyID); !errors.Is(err, ErrNotFound) { + t.Fatalf("stop of a non-private instance = %v, want ErrNotFound", err) + } +} + +func TestIdlePrivateInstanceStopsAfterTimeout(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, 5*time.Minute)) + inst, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + f.bringUp(inst.ID, "10.0.0.1:25565") + + f.advance(4 * time.Minute) + if got := f.get(inst.ID).State; got != model.StateReady { + t.Fatalf("state before the timeout = %s, want Ready", got) + } + f.advance(2 * time.Minute) + + if got := f.get(inst.ID).State; got != model.StateStopping { + t.Fatalf("state after the timeout = %s, want Stopping", got) + } + if n := f.pub.count(model.EventPrivateIdleStop); n != 1 { + t.Errorf("private.idle-stop events = %d, want 1", n) + } + var found bool + for i, typ := range f.pub.types { + if typ == model.EventPrivateIdleStop { + d := f.pub.data[i].(model.PrivateIdleStopData) + found = d.Owner == "alex" && d.Instance == inst.ID && d.Pool == "home" + } + } + if !found { + t.Errorf("private.idle-stop payload does not name pool, instance and owner") + } +} + +func TestPlayersResetTheIdleTimer(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, 5*time.Minute)) + inst, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + f.bringUp(inst.ID, "10.0.0.1:25565") + + f.advance(4 * time.Minute) + _, _ = f.c.SelfStatus(f.ctx, inst.ID, StatusUpdate{Players: 1}) + f.advance(10 * time.Second) + _, _ = f.c.SelfStatus(f.ctx, inst.ID, StatusUpdate{Players: 0}) + f.advance(4 * time.Minute) + + if got := f.get(inst.ID).State; got != model.StateReady { + t.Fatalf("state = %s, want Ready: the idle period restarted when the player left", got) + } + f.advance(2 * time.Minute) + if got := f.get(inst.ID).State; got != model.StateStopping { + t.Fatalf("state = %s, want Stopping after a full idle period", got) + } +} + +func TestInstanceLabelsFromStatusKeepTheOwner(t *testing.T) { + f := newFixture(t, Config{}) + f.putPool("home", privateSpec(1, time.Minute)) + inst, _, _ := f.c.CreatePrivateServer(f.ctx, "home", "alex") + f.drv.SetPhase(inst.ID, driver.PhaseRunning, "10.0.0.1:25565") + f.reconcile() + _, _ = f.c.SelfReady(f.ctx, inst.ID) + + got, err := f.c.SelfStatus(f.ctx, inst.ID, StatusUpdate{Labels: map[string]string{"map": "x", model.LabelOwner: "mallory"}}) + + if err != nil || got.Labels[model.LabelOwner] != "alex" || got.Labels["map"] != "x" { + t.Fatalf("labels = %v (%v), want owner alex kept and map added", got.Labels, err) + } +} diff --git a/internal/controller/reconcile.go b/internal/controller/reconcile.go index 7132bc5..81f2c8f 100644 --- a/internal/controller/reconcile.go +++ b/internal/controller/reconcile.go @@ -120,6 +120,12 @@ func (c *Controller) ReconcileOnce(ctx context.Context) error { } } + // 3b. Private instances that stayed empty for the idle timeout. + if insts, err = c.listAll(ctx); err != nil { + return err + } + errs = append(errs, c.stopIdlePrivate(ctx, insts, specs, unlisted, now)...) + // 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 aa527a2..249f7d5 100644 --- a/internal/controller/service.go +++ b/internal/controller/service.go @@ -22,6 +22,8 @@ var ( ErrLimit = errors.New("instance limit reached") // ErrManagedElsewhere: the object is owned by Kubernetes and cannot be changed through the API (HTTP 409). ErrManagedElsewhere = errors.New("managed by kubernetes") + // ErrQuota: the owner already has as many private instances in the pool as the quota allows (HTTP 409). + ErrQuota = errors.New("private server quota reached") ) // ValidationError carries field errors of a pool, environment or group spec (HTTP 422). @@ -80,6 +82,14 @@ type Service interface { Logs(ctx context.Context, id string, tail int, follow bool) (io.ReadCloser, error) Command(ctx context.Context, id string, line string) error + // CreatePrivateServer returns the live private instance of owner in pool or starts one; created tells which. + // ErrQuota when the owner has no usable instance but is at the quota of the pool. + CreatePrivateServer(ctx context.Context, pool, owner string) (inst model.Instance, created bool, err error) + // ListPrivateServers lists the live private instances; owner filters when not empty. + ListPrivateServers(ctx context.Context, owner string) ([]model.Instance, error) + // StopPrivateServer drains a private instance: it stops as soon as its players left. + StopPrivateServer(ctx context.Context, id string) (model.Instance, 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/controller/service_impl.go b/internal/controller/service_impl.go index 43408a8..b9de497 100644 --- a/internal/controller/service_impl.go +++ b/internal/controller/service_impl.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "regexp" + "strings" "github.com/OneLiteFeatherNET/grus/internal/driver" "github.com/OneLiteFeatherNET/grus/internal/model" @@ -262,7 +263,7 @@ func (c *Controller) SelfStatus(ctx context.Context, id string, u StatusUpdate) inst.MaxPlayers = u.MaxPlayers } if u.Labels != nil { - inst.Labels = u.Labels + inst.Labels = withGrusLabels(u.Labels, inst.Labels) } inst.LastHeartbeat = &now @@ -320,3 +321,20 @@ func (c *Controller) SelfShutdown(ctx context.Context, id string) (model.Instanc c.Trigger() return inst, nil } + +// withGrusLabels returns reported plus the grus.olf/ labels of current: an instance cannot drop or forge the +// labels the controller sets (owner, cells). +func withGrusLabels(reported, current map[string]string) map[string]string { + out := make(map[string]string, len(reported)+len(current)) + for k, v := range reported { + if !strings.HasPrefix(k, model.LabelPrefix) { + out[k] = v + } + } + for k, v := range current { + if strings.HasPrefix(k, model.LabelPrefix) { + out[k] = v + } + } + return out +} diff --git a/internal/model/model.go b/internal/model/model.go index 049f61c..c384ca5 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -142,10 +142,14 @@ type Sharding struct { Cells []string `json:"cells,omitempty" doc:"Explicit cell names"` } -// Private lets owners run their own instance of a pool (spec only; behaviour follows later). +// Private lets owners run their own instance of a pool. A pool with Private set is never autoscaled: its +// instances are created on demand (POST /v1/private-servers) and stopped after IdleTimeout without players. +// +// World persistence is spec only: a later version snapshots the instance directory to a template when the +// instance is stopped and restores it on the next start, so the owner's world survives the idle stop. type Private struct { - QuotaPerOwner int `json:"quotaPerOwner,omitempty"` - IdleTimeout Duration `json:"idleTimeout,omitempty"` + QuotaPerOwner int `json:"quotaPerOwner,omitempty" doc:"Instances one owner may have at once (default 1)"` + IdleTimeout Duration `json:"idleTimeout,omitempty" doc:"Stop an instance after this long without players (default 10m)"` } // PoolSpec is the declarative template for the instances of a pool. Without Environment the inline @@ -183,6 +187,14 @@ const ( DefaultGracePeriod = 30 * time.Second DefaultHeartbeatTimeout = 15 * time.Second DefaultStartTimeout = 5 * time.Minute + DefaultQuotaPerOwner = 1 + DefaultPrivateIdle = 10 * time.Minute +) + +// Instance label keys set by Grus. SelfStatus keeps labels with this prefix when an instance replaces its labels. +const ( + LabelPrefix = "grus.olf/" + LabelOwner = LabelPrefix + "owner" ) // WithDefaults returns a copy with every empty optional field set to its default. @@ -211,6 +223,16 @@ func (s PoolSpec) WithDefaults() PoolSpec { if s.Lifecycle.StartTimeout == 0 { s.Lifecycle.StartTimeout = Duration(DefaultStartTimeout) } + if s.Private != nil { + p := *s.Private + if p.QuotaPerOwner == 0 { + p.QuotaPerOwner = DefaultQuotaPerOwner + } + if p.IdleTimeout == 0 { + p.IdleTimeout = Duration(DefaultPrivateIdle) + } + s.Private = &p + } return s } @@ -270,6 +292,26 @@ func (s PoolSpec) Validate() []FieldError { if s.Scaling.TargetUtilization <= 0 || s.Scaling.TargetUtilization > 1 { add("scaling.targetUtilization", "must be in (0, 1]") } + if p := s.Private; p != nil { + if p.QuotaPerOwner < 0 { + add("private.quotaPerOwner", "must not be negative") + } + if p.IdleTimeout < 0 { + add("private.idleTimeout", "must not be negative") + } + if s.Scaling.Min != 0 { + add("scaling.min", "must be 0 for a private pool; instances are created on demand") + } + if s.Scaling.Max < 1 { + add("scaling.max", "must be at least 1 for a private pool") + } + if s.Scaling.Buffer != 0 { + add("scaling.buffer", "must be 0 for a private pool") + } + if s.Mode != ModeDynamic { + add("mode", "must be dynamic for a private pool") + } + } for i, t := range s.Templates { if t.Name == "" { add(fmt.Sprintf("templates[%d].name", i), "is required") @@ -336,6 +378,7 @@ const ( EventTemplateTagged = "template.tagged" EventNetworkPlayers = "network.players" EventPoolCondition = "pool.condition" + EventPrivateIdleStop = "private.idle-stop" EventResync = "resync" ) @@ -382,6 +425,13 @@ type PoolConditionData struct { Message string `json:"message"` } +// PrivateIdleStopData is the payload of private.idle-stop: a private instance was stopped after it stayed empty. +type PrivateIdleStopData struct { + Pool string `json:"pool"` + Instance string `json:"instance"` + Owner string `json:"owner"` +} + // Publisher sends events to stream subscribers. Implemented by events.Hub. type Publisher interface { Publish(eventType string, data any) diff --git a/internal/model/private_test.go b/internal/model/private_test.go new file mode 100644 index 0000000..a3921a9 --- /dev/null +++ b/internal/model/private_test.go @@ -0,0 +1,55 @@ +package model + +import ( + "testing" + "time" +) + +func privatePool() PoolSpec { + return PoolSpec{ + Role: RoleGame, Mode: ModeDynamic, Driver: DriverKubernetes, Image: "x:1", + Resources: Resources{MemoryMiB: 512}, + Scaling: Scaling{Max: 4}, + Private: &Private{}, + } +} + +func fieldsOf(errs []FieldError) map[string]bool { + out := map[string]bool{} + for _, e := range errs { + out[e.Field] = true + } + return out +} + +func TestPrivateDefaultsDoNotMutateTheInput(t *testing.T) { + in := privatePool() + + got := in.WithDefaults() + + if got.Private.QuotaPerOwner != 1 || got.Private.IdleTimeout.D() != 10*time.Minute { + t.Errorf("defaults = %+v, want quota 1 and idle 10m", *got.Private) + } + if in.Private.QuotaPerOwner != 0 { + t.Errorf("WithDefaults changed the caller's private block: %+v", *in.Private) + } +} + +func TestPrivatePoolValidation(t *testing.T) { + ok := privatePool() + if errs := ok.WithDefaults().Validate(); len(errs) != 0 { + t.Fatalf("valid private pool rejected: %v", errs) + } + + bad := privatePool() + bad.Scaling.Min = 1 + bad.Scaling.Buffer = 1 + bad.Mode = ModeStatic + bad.Private.QuotaPerOwner = -1 + got := fieldsOf(bad.WithDefaults().Validate()) + for _, f := range []string{"scaling.min", "scaling.buffer", "mode", "private.quotaPerOwner"} { + if !got[f] { + t.Errorf("no error for %s in %v", f, got) + } + } +} diff --git a/web/app/types/grus-api.d.ts b/web/app/types/grus-api.d.ts index 3c5e4b8..5b6abee 100644 --- a/web/app/types/grus-api.d.ts +++ b/web/app/types/grus-api.d.ts @@ -409,6 +409,44 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/private-servers": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List private servers, optionally of one owner */ + get: operations["list-private-servers"]; + put?: never; + /** + * Start a private server for an owner, or return the one the owner already has + * @description Answers 201 when an instance was started and 200 when the owner's live instance is returned. 409 when the owner is at the quota of the pool. + */ + post: operations["create-private-server"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/private-servers/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Stop a private server once its players left (drain) */ + delete: operations["stop-private-server"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/self": { parameters: { query?: never; @@ -964,10 +1002,26 @@ export interface components { templates?: components["schemas"]["TemplateRef"][] | null; }; Private: { + /** @description Stop an instance after this long without players (default 10m) */ idleTimeout?: string; - /** Format: int64 */ + /** + * Format: int64 + * @description Instances one owner may have at once (default 1) + */ quotaPerOwner?: number; }; + PrivateServerBody: { + /** + * Format: uri + * @description A URL to the JSON Schema for this object. + * @example https://example.com/schemas/PrivateServerBody.json + */ + readonly $schema?: string; + /** @description Owner of the server, e.g. a player uuid */ + owner: string; + /** @description Private pool (a pool with a private section) */ + pool: string; + }; RegisterRequest: { /** * Format: uri @@ -2040,6 +2094,130 @@ export interface operations { }; }; }; + "list-private-servers": { + parameters: { + query?: { + /** @description Only the private servers of this owner */ + owner?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Instance"][] | null; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; + "create-private-server": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PrivateServerBody"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Instance"]; + }; + }; + /** @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"]; + }; + }; + }; + }; + "stop-private-server": { + parameters: { + query?: never; + header?: never; + path: { + /** @description Instance id */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Instance"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "get-self": { parameters: { query?: never;