Files
CosmicClash/server/agones/allocation.go
T
2026-09-01 09:49:09 +01:00

148 lines
4.8 KiB
Go

// Package agones contains the narrow provider adapter used by the allocator.
// Domain policy and durable allocation records remain outside this package.
package agones
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cosmic-clash/cosmic-clash/server/domain"
)
type Client struct {
BaseURL string
Namespace string
HTTP *http.Client
}
type AllocatedServer struct {
Allocation domain.Allocation
Endpoint string
GameServer string
}
type allocationRequest struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Spec struct {
Selectors []struct {
MatchLabels map[string]string `json:"matchLabels"`
} `json:"selectors"`
} `json:"spec"`
}
type allocationResponse struct {
Status struct {
State string `json:"state"`
GameServerName string `json:"gameServerName"`
Address string `json:"address"`
Ports []struct {
Name string `json:"name"`
Port int `json:"port"`
} `json:"ports"`
} `json:"status"`
}
func (c Client) Allocate(ctx context.Context, request domain.AllocationRequest, labels map[string]string, now time.Time) (AllocatedServer, error) {
if c.HTTP == nil {
c.HTTP = http.DefaultClient
}
base, err := c.endpoint()
if err != nil {
return AllocatedServer{}, err
}
if request.AllocationID == "" || request.MatchID == "" || (request.Region != "EU" && request.Region != "NA") || request.Build == "" || request.Protocol <= 0 || (request.Transport != "enet" && request.Transport != "steam_sdr") || now.IsZero() {
return AllocatedServer{}, domain.ErrAllocationInput
}
if len(labels) == 0 {
return AllocatedServer{}, fmt.Errorf("allocation labels are required")
}
for key, value := range labels {
if key == "" || value == "" || strings.ContainsAny(key+value, "\r\n") {
return AllocatedServer{}, fmt.Errorf("invalid allocation label")
}
}
var body allocationRequest
body.APIVersion = "allocation.agones.dev/v1"
body.Kind = "GameServerAllocation"
body.Spec.Selectors = []struct {
MatchLabels map[string]string `json:"matchLabels"`
}{{MatchLabels: cloneLabels(labels)}}
encoded, err := json.Marshal(body)
if err != nil {
return AllocatedServer{}, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/apis/allocation.agones.dev/v1/namespaces/"+url.PathEscape(c.Namespace)+"/gameserverallocations", bytes.NewReader(encoded))
if err != nil {
return AllocatedServer{}, err
}
req.Header.Set("Content-Type", "application/json")
response, err := c.HTTP.Do(req)
if err != nil {
return AllocatedServer{}, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return AllocatedServer{}, fmt.Errorf("Agones allocation returned %s", response.Status)
}
var decoded allocationResponse
decoder := json.NewDecoder(io.LimitReader(response.Body, 64<<10))
if err := decoder.Decode(&decoded); err != nil {
return AllocatedServer{}, fmt.Errorf("decode Agones allocation: %w", err)
}
if decoded.Status.State != "Allocated" || decoded.Status.GameServerName == "" || decoded.Status.Address == "" {
return AllocatedServer{}, fmt.Errorf("Agones allocation is incomplete")
}
port, err := selectPort(decoded.Status.Ports)
if err != nil {
return AllocatedServer{}, err
}
return AllocatedServer{Allocation: domain.Allocation{AllocationID: request.AllocationID, MatchID: request.MatchID, ServerID: decoded.Status.GameServerName, Region: request.Region, Build: request.Build, Protocol: request.Protocol, Transport: request.Transport, State: domain.ServerAllocated, AllocatedAt: now}, Endpoint: net.JoinHostPort(decoded.Status.Address, strconv.Itoa(port)), GameServer: decoded.Status.GameServerName}, nil
}
func (c Client) endpoint() (string, error) {
if c.Namespace == "" || strings.ContainsAny(c.Namespace, "/\r\n") {
return "", fmt.Errorf("invalid Agones namespace")
}
u, err := url.Parse(c.BaseURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.Path != "" {
return "", fmt.Errorf("invalid Agones base URL")
}
return strings.TrimRight(c.BaseURL, "/"), nil
}
func selectPort(ports []struct {
Name string `json:"name"`
Port int `json:"port"`
}) (int, error) {
for _, port := range ports {
if port.Name == "default" {
if port.Port < 1 || port.Port > 65535 {
return 0, fmt.Errorf("Agones returned invalid default port")
}
return port.Port, nil
}
}
if len(ports) != 1 || ports[0].Port < 1 || ports[0].Port > 65535 {
return 0, fmt.Errorf("Agones returned no usable game port")
}
return ports[0].Port, nil
}
func cloneLabels(labels map[string]string) map[string]string {
copy := make(map[string]string, len(labels))
for key, value := range labels {
copy[key] = value
}
return copy
}