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
454 changes: 453 additions & 1 deletion api/openapi.yaml

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ func build(mux *http.ServeMux, s *server, version string) huma.API {
api := humago.New(mux, config)
api.UseMiddleware(s.auth.middleware(api))
s.registerPools(api)
s.registerDeclarations(api)
s.registerInstances(api)
s.registerSelf(api)
s.registerTemplates(api)
Expand Down
132 changes: 132 additions & 0 deletions internal/api/declarations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package api

import (
"context"
"net/http"

"github.com/danielgtaylor/huma/v2"

"github.com/OneLiteFeatherNET/grus/internal/model"
)

type nameInput struct {
Name string `path:"name" doc:"Object name"`
}

type environmentOutput struct{ Body model.Environment }
type environmentsOutput struct{ Body []model.Environment }
type putEnvironmentInput struct {
Name string `path:"name" doc:"Environment name"`
Body model.EnvironmentSpec
}

type groupOutput struct{ Body model.Group }
type groupsOutput struct{ Body []model.Group }
type putGroupInput struct {
Name string `path:"name" doc:"Group name"`
Body model.GroupSpec
}

type networkOutput struct{ Body model.NetworkStatus }

const managedNote = " Objects owned by Kubernetes answer 409."

func (s *server) registerDeclarations(api huma.API) {
huma.Register(api, operation(scopePoolsRead, huma.Operation{
OperationID: "list-environments", Method: http.MethodGet, Path: "/v1/environments", Summary: "List environments",
}), func(ctx context.Context, _ *struct{}) (*environmentsOutput, error) {
list, err := s.svc.ListEnvironments(ctx)
if err != nil {
return nil, mapError(s.log, err)
}
if list == nil {
list = []model.Environment{}
}
return &environmentsOutput{Body: list}, nil
})
huma.Register(api, operation(scopePoolsRead, huma.Operation{
OperationID: "get-environment", Method: http.MethodGet, Path: "/v1/environments/{name}", Summary: "Get an environment",
}), func(ctx context.Context, in *nameInput) (*environmentOutput, error) {
e, err := s.svc.GetEnvironment(ctx, in.Name)
if err != nil {
return nil, mapError(s.log, err)
}
return &environmentOutput{Body: e}, nil
})
huma.Register(api, operation(scopePoolsWrite, huma.Operation{
OperationID: "put-environment", Method: http.MethodPut, Path: "/v1/environments/{name}",
Summary: "Create or replace an environment",
Description: "Idempotent. Generation increases when the spec changes." + managedNote,
}), func(ctx context.Context, in *putEnvironmentInput) (*environmentOutput, error) {
e, err := s.svc.PutEnvironment(ctx, in.Name, in.Body)
if err != nil {
return nil, mapError(s.log, err)
}
return &environmentOutput{Body: e}, nil
})
huma.Register(api, operation(scopePoolsWrite, huma.Operation{
OperationID: "delete-environment", Method: http.MethodDelete, Path: "/v1/environments/{name}",
Summary: "Delete an environment", Description: "Pools that still name it stop starting instances." + managedNote,
DefaultStatus: http.StatusNoContent,
}), func(ctx context.Context, in *nameInput) (*struct{}, error) {
if err := s.svc.DeleteEnvironment(ctx, in.Name); err != nil {
return nil, mapError(s.log, err)
}
return nil, nil
})

huma.Register(api, operation(scopePoolsRead, huma.Operation{
OperationID: "list-groups", Method: http.MethodGet, Path: "/v1/groups", Summary: "List groups",
}), func(ctx context.Context, _ *struct{}) (*groupsOutput, error) {
list, err := s.svc.ListGroups(ctx)
if err != nil {
return nil, mapError(s.log, err)
}
if list == nil {
list = []model.Group{}
}
return &groupsOutput{Body: list}, nil
})
huma.Register(api, operation(scopePoolsRead, huma.Operation{
OperationID: "get-group", Method: http.MethodGet, Path: "/v1/groups/{name}", Summary: "Get a group",
}), func(ctx context.Context, in *nameInput) (*groupOutput, error) {
g, err := s.svc.GetGroup(ctx, in.Name)
if err != nil {
return nil, mapError(s.log, err)
}
return &groupOutput{Body: g}, nil
})
huma.Register(api, operation(scopePoolsWrite, huma.Operation{
OperationID: "put-group", Method: http.MethodPut, Path: "/v1/groups/{name}",
Summary: "Create or replace a group",
Description: "Idempotent. Generation increases when the spec changes." + managedNote,
}), func(ctx context.Context, in *putGroupInput) (*groupOutput, error) {
g, err := s.svc.PutGroup(ctx, in.Name, in.Body)
if err != nil {
return nil, mapError(s.log, err)
}
return &groupOutput{Body: g}, nil
})
huma.Register(api, operation(scopePoolsWrite, huma.Operation{
OperationID: "delete-group", Method: http.MethodDelete, Path: "/v1/groups/{name}",
Summary: "Delete a group", Description: "Pools that still name it stop starting instances." + managedNote,
DefaultStatus: http.StatusNoContent,
}), func(ctx context.Context, in *nameInput) (*struct{}, error) {
if err := s.svc.DeleteGroup(ctx, in.Name); err != nil {
return nil, mapError(s.log, err)
}
return nil, nil
})

huma.Register(api, operation(scopePlayersRead, huma.Operation{
OperationID: "get-network", Method: http.MethodGet, Path: "/v1/network", Summary: "Get the network player count",
Description: "Players and capacity summed over all Ready and Allocated proxy instances. " +
"The SSE event network.players is published whenever the sum changes.",
}), func(ctx context.Context, _ *struct{}) (*networkOutput, error) {
n, err := s.svc.Network(ctx)
if err != nil {
return nil, mapError(s.log, err)
}
return &networkOutput{Body: n}, nil
})
}
103 changes: 103 additions & 0 deletions internal/api/declarations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package api

import (
"encoding/json"
"net/http"
"testing"

"github.com/OneLiteFeatherNET/grus/internal/controller"
"github.com/OneLiteFeatherNET/grus/internal/model"
)

const validEnvironmentBody = `{"kind":"jvm","jvm":{"jar":"paper.jar","flags":["-XX:+UseG1GC"]},"readiness":"tcp","gracePeriod":"45s"}`

func TestAdminPutsEnvironmentAndGetsItBack(t *testing.T) {
fx := newFixture(t, Config{}, nil)
rec := fx.call(t, http.MethodPut, "/v1/environments/paper", adminToken, "application/json", validEnvironmentBody)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body)
}
var env model.Environment
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatalf("decode environment: %v", err)
}
if env.Name != "paper" || env.Source != model.SourceAPI || fx.svc.envSpec.JVM == nil || fx.svc.envSpec.JVM.Jar != "paper.jar" {
t.Errorf("environment = %+v, spec passed to service = %+v", env, fx.svc.envSpec)
}
if got := fx.call(t, http.MethodGet, "/v1/environments/paper", adminToken, "", ""); got.Code != http.StatusOK {
t.Errorf("get status = %d, want 200", got.Code)
}
if got := fx.call(t, http.MethodGet, "/v1/environments", adminToken, "", ""); got.Body.String() != "[]\n" {
t.Errorf("empty list body = %q, want a top-level empty array", got.Body.String())
}
}

func TestPutGroupAndDeleteRoutes(t *testing.T) {
fx := newFixture(t, Config{}, nil)
rec := fx.call(t, http.MethodPut, "/v1/groups/base", adminToken, "application/json", `{"env":{"A":"1"}}`)
if rec.Code != http.StatusOK || fx.svc.groupName != "base" {
t.Fatalf("put group status = %d name = %q; body %s", rec.Code, fx.svc.groupName, rec.Body)
}
if got := fx.call(t, http.MethodDelete, "/v1/groups/base", adminToken, "", ""); got.Code != http.StatusNoContent {
t.Errorf("delete group status = %d, want 204", got.Code)
}
if got := fx.call(t, http.MethodDelete, "/v1/environments/paper", adminToken, "", ""); got.Code != http.StatusNoContent || fx.svc.deletedEnv != "paper" {
t.Errorf("delete environment status = %d deleted = %q", got.Code, fx.svc.deletedEnv)
}
}

func TestKubernetesManagedObjectReturns409(t *testing.T) {
fx := newFixture(t, Config{}, nil)
fx.svc.putErr = controller.ErrManagedElsewhere
for _, tc := range []struct{ method, path, body string }{
{http.MethodPut, "/v1/environments/paper", validEnvironmentBody},
{http.MethodPut, "/v1/groups/base", `{}`},
{http.MethodPut, "/v1/pools/lobby", validPoolBody},
{http.MethodDelete, "/v1/groups/base", ""},
} {
ct := ""
if tc.body != "" {
ct = "application/json"
}
if rec := fx.call(t, tc.method, tc.path, adminToken, ct, tc.body); rec.Code != http.StatusConflict {
t.Errorf("%s %s status = %d, want 409; body %s", tc.method, tc.path, rec.Code, rec.Body)
}
}
}

func TestInvalidEnvironmentReturns422(t *testing.T) {
fx := newFixture(t, Config{}, nil)
fx.svc.putErr = &controller.ValidationError{Kind: "environment", Fields: []model.FieldError{{Field: "kind", Message: "must be jvm, native or container"}}}
rec := fx.call(t, http.MethodPut, "/v1/environments/paper", adminToken, "application/json", `{"kind":"wasm"}`)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status = %d, want 422; body %s", rec.Code, rec.Body)
}
}

func TestInstanceTokenCannotWriteEnvironments(t *testing.T) {
fx := newFixture(t, Config{}, nil)
rec := fx.call(t, http.MethodPut, "/v1/environments/paper", gameToken, "application/json", validEnvironmentBody)
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403", rec.Code)
}
}

func TestNetworkIsReadableByProxyButNotByGameInstances(t *testing.T) {
fx := newFixture(t, Config{}, nil)
fx.svc.network = model.NetworkStatus{Players: 12, MaxPlayers: 200, Proxies: 2}

rec := fx.call(t, http.MethodGet, "/v1/network", proxyToken, "", "")
if rec.Code != http.StatusOK {
t.Fatalf("proxy status = %d, want 200; body %s", rec.Code, rec.Body)
}
var got model.NetworkStatus
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || got != fx.svc.network {
t.Errorf("network = %+v err=%v, want %+v", got, err, fx.svc.network)
}
if rec := fx.call(t, http.MethodGet, "/v1/network", gameToken, "", ""); rec.Code != http.StatusForbidden {
t.Errorf("game instance status = %d, want 403", rec.Code)
}
if rec := fx.call(t, http.MethodGet, "/v1/network", adminToken, "", ""); rec.Code != http.StatusOK {
t.Errorf("admin status = %d, want 200", rec.Code)
}
}
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):
case errors.Is(err, controller.ErrHasPlayers), errors.Is(err, controller.ErrInvalidState), errors.Is(err, controller.ErrLimit), errors.Is(err, controller.ErrManagedElsewhere):
return huma.Error409Conflict(err.Error())
default:
log.Error("api: request failed", "err", err)
Expand Down
44 changes: 44 additions & 0 deletions internal/api/fakes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ type fakeService struct {
putName string
putSpec model.PoolSpec

env model.Environment
envName string
envSpec model.EnvironmentSpec
deletedEnv string
groupName string
network model.NetworkStatus

listFilter store.InstanceFilter
listed []model.Instance

Expand Down Expand Up @@ -78,6 +85,43 @@ func (f *fakeService) SetMaintenance(_ context.Context, name string, enabled boo
return model.Pool{Name: name, Maintenance: enabled}, nil
}

func (f *fakeService) PutEnvironment(_ context.Context, name string, spec model.EnvironmentSpec) (model.Environment, error) {
f.envName, f.envSpec = name, spec
if f.putErr != nil {
return model.Environment{}, f.putErr
}
return model.Environment{Name: name, Spec: spec, Source: model.SourceAPI, Generation: 1}, nil
}

func (f *fakeService) GetEnvironment(context.Context, string) (model.Environment, error) {
return f.env, nil
}

func (f *fakeService) ListEnvironments(context.Context) ([]model.Environment, error) { return nil, nil }

func (f *fakeService) DeleteEnvironment(_ context.Context, name string) error {
f.deletedEnv = name
return f.putErr
}

func (f *fakeService) PutGroup(_ context.Context, name string, spec model.GroupSpec) (model.Group, error) {
f.groupName = name
if f.putErr != nil {
return model.Group{}, f.putErr
}
return model.Group{Name: name, Spec: spec, Source: model.SourceAPI, Generation: 1}, nil
}

func (f *fakeService) GetGroup(context.Context, string) (model.Group, error) {
return model.Group{}, nil
}

func (f *fakeService) ListGroups(context.Context) ([]model.Group, error) { return nil, nil }

func (f *fakeService) DeleteGroup(context.Context, string) error { return f.putErr }

func (f *fakeService) Network(context.Context) (model.NetworkStatus, error) { return f.network, nil }

func (f *fakeService) ListInstances(_ context.Context, filter store.InstanceFilter) ([]model.Instance, error) {
f.listFilter = filter
return f.listed, nil
Expand Down
Loading