Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <player-uuid> # starts the server, or shows the one that already runs
grus private list --owner <player-uuid>
```

`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).
127 changes: 127 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 23 additions & 0 deletions internal/api/fakes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
73 changes: 73 additions & 0 deletions internal/api/private.go
Original file line number Diff line number Diff line change
@@ -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
})
}
88 changes: 88 additions & 0 deletions internal/api/private_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading