server

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

README

Unity Game Server Hosting Server Library

A Golang game server can be integrated with the platform quickly by using this library. A fully-formed usage example can be found here.

Short Demonstration

A basic server can be set up by using the server.New() function with the Start(), Stop() and message channels:

package main

import "github.com/Unity-Technologies/unity-gaming-services-go-sdk/game-server-hosting/server"

func main() {
	s, err := server.New(server.TypeAllocation)
	if err != nil {
		// ...
	}
	
	// Handle server events (i.e. allocation, deallocation, errors)
	done := make(chan struct{})
	go handleEvents(s, done)
	
	if err = s.Start(); err != nil {
		// ...
	}

	if err = s.WaitUntilTerminated(); err != nil {
		close(done)
		// ...
	}
}

func handleEvents(s *server.Server, done chan struct{}) {
	for {
		select {
		case <-s.OnAllocate():
			// handle allocation

		case <-s.OnDeallocate():
			// handle deallocation

		case <-s.OnError():
			// handle error

		case <-s.OnConfigurationChanged():
			// handle configuration change

		case <-done:
			return
		}
	}
}

Documentation

Index

Constants

View Source
const (
	// QueryProtocolA2S represents the 'a2s' query protocol.
	// Although A2S is supported, SQP is the recommended query implementation.
	// Documentation: https://docs.unity.com/game-server-hosting/en/manual/concepts/a2s
	QueryProtocolA2S = QueryProtocol("a2s")

	// QueryProtocolSQP represents the 'sqp' query protocol.
	// SQP is the recommended query protocol.
	// Documentation: https://docs.unity.com/game-server-hosting/en/manual/concepts/sqp
	QueryProtocolSQP = QueryProtocol("sqp")

	// QueryProtocolRecommended represents the recommended query protocol.
	QueryProtocolRecommended
)
View Source
const (
	// TypeAllocation represents a server which is using the 'allocations' model of server usage.
	TypeAllocation = Type(iota)

	// TypeReservation represents a server which is using the 'reservations' model of server usage.
	TypeReservation
)
View Source
const (
	// DefaultWriteBufferSizeBytes represents the default size of the write buffer for the query handler.
	DefaultWriteBufferSizeBytes = 1024

	// DefaultWriteDeadlineDuration represents the default write deadline duration for responding in the query handler.
	DefaultWriteDeadlineDuration = 1 * time.Second

	// DefaultReadDeadlineDuration represents the default read deadline duration for consuming a query request.
	DefaultReadDeadlineDuration = 3 * time.Second

	// DefaultReadBufferSizeBytes represents the default size of the read buffer for the query handler.
	DefaultReadBufferSizeBytes = 1024
)

Variables

View Source
var (
	// ErrOperationNotApplicable represents that the operation being performed is not applicable to the server type.
	ErrOperationNotApplicable = errors.New("the operation requested is not applicable to the server type")

	// ErrNilContext represents that the context supplied is nil.
	ErrNilContext = errors.New("context is nil")

	// ErrNilArgs represents that the arguments supplied are nil.
	ErrNilArgs = errors.New("arguments supplied are nil")

	// ErrMetricsUnsupported represents that the query type this server is using does not support additional metrics.
	ErrMetricsUnsupported = errors.New("metrics are not supported for this query type")

	// ErrMetricOutOfBounds represents that the metric index provided will overflow the metrics buffer.
	ErrMetricOutOfBounds = errors.New("metrics index provided will overflow the metrics buffer")

	/// ErrNotAllocated represents that the server is not allocated.
	ErrNotAllocated = errors.New("server is not allocated")
)
View Source
var ErrUnsupportedQueryType = errors.New("supplied query type is not supported")

ErrUnsupportedQueryType is an error that specifies the provided query type is not supported by this library.

Functions

This section is empty.

Types

type Config

type Config struct {
	// AllocatedUUID is the allocation ID provided to an event.
	AllocatedUUID string `json:"allocatedUUID"`

	// FleetID is the ID of the fleet of which the server is a member.
	FleetID string `json:"fleetID"`

	// IP is the IPv4 address of this server.
	IP string `json:"ip"`

	// IPV6 is the IPv6 address of this server. This can be empty.
	IPv6 string `json:"ipv6"`

	// LocalProxyURL is the URL to the local proxy service, which can handle interactions with the allocations payload store.
	LocalProxyURL string `json:"localProxyUrl"`

	// MachineID is the ID of the machine on which the server is running.
	MachineID json.Number `json:"machineID"`

	// Port is the port number this server uses for game interactions. It is up to the implemented to bind their game
	// server to this port.
	Port json.Number `json:"port"`

	// QueryPort is the port number this server uses for query interactions. These interactions are handled over UDP.
	QueryPort json.Number `json:"queryPort"`

	// QueryType represents the query protocol used by this server.
	QueryType QueryProtocol `json:"queryType"`

	// RegionID is the ID of the region of which the server is a member.
	RegionID string `json:"regionID"`

	// RegionName is the name of the region of which the server is a member.
	RegionName string `json:"regionName"`

	// ServerID is the ID of the running server in the Unity Game Server Hosting platform.
	ServerID json.Number `json:"serverID"`

	// ServerLogDir is the directory where the server should place its log files. These will be detected by Unity Game Server
	// Hosting and made available in the dashboard.
	ServerLogDir string `json:"serverLogDir"`

	// Extra represents any other arguments passed to this server, for example, those specified in a build configuration.
	Extra map[string]string `json:"-"`
}

Config represents the game server configuration variables provided from the Unity Game Server Hosting platform.

type Option

type Option func(s *Server)

Option represents a function that modifies a property of the game server.

func WithConfigPath

func WithConfigPath(path string) Option

WithConfigPath sets the configuration file to use when starting the server. In most circumstances, the default value is reasonable to use.

func WithQueryReadBuffer

func WithQueryReadBuffer(sizeBytes int) Option

WithQueryReadBuffer sets the read buffer size for the query handler.

func WithQueryReadDeadlineDuration added in v0.2.0

func WithQueryReadDeadlineDuration(duration time.Duration) Option

WithQueryReadDeadlineDuration sets the read deadline duration for consuming query requests in the query handler.

func WithQueryWriteBuffer

func WithQueryWriteBuffer(sizeBytes int) Option

WithQueryWriteBuffer sets the write buffer size for the query handler.

func WithQueryWriteDeadlineDuration

func WithQueryWriteDeadlineDuration(duration time.Duration) Option

WithQueryWriteDeadlineDuration sets the write deadline duration for responding to query requests in the query handler.

type QueryProtocol

type QueryProtocol string

QueryProtocol represents the query type the server uses. Documentation: https://docs.unity.com/game-server-hosting/en/manual/concepts/query-protocols

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents an instance of a game server, handling changes to configuration and responding to query requests.

func New

func New(serverType Type, opts ...Option) (*Server, error)

New creates a new instance of Server, denoting which type of server to use.

func (*Server) Config

func (s *Server) Config() Config

Config returns a copy of the configuration the server is currently using.

func (*Server) Hold added in v0.4.0

func (s *Server) Hold(ctx context.Context, args *model.HoldRequest) (*model.HoldStatus, error)

Hold holds this server, preventing descaling until after a reservation completes, the expiry time elapses, or the hold is manually released with the Release() method.

func (*Server) HoldStatus added in v0.4.0

func (s *Server) HoldStatus(ctx context.Context) (*model.HoldStatus, error)

HoldStatus gets the status of the hold for the server, including the time at which the hold expires.

func (*Server) OnAllocate

func (s *Server) OnAllocate() <-chan string

OnAllocate returns a read-only channel that receives messages when the server is allocated.

func (*Server) OnConfigurationChanged

func (s *Server) OnConfigurationChanged() <-chan Config

OnConfigurationChanged returns a read-only channel that receives messages when the server detects a change in the configuration file.

func (*Server) OnDeallocate

func (s *Server) OnDeallocate() <-chan string

OnDeallocate returns a read-only channel that receives messages when the server is de-allocated.

func (*Server) OnError

func (s *Server) OnError() <-chan error

OnError returns a read-only channel that receives messages when the server encounters an error.

func (*Server) PlayerJoined

func (s *Server) PlayerJoined() int32

PlayerJoined indicates a new player has joined the server.

func (*Server) PlayerLeft

func (s *Server) PlayerLeft() int32

PlayerLeft indicates a player has left the server.

func (*Server) PushError

func (s *Server) PushError(err error)

PushError pushes an error to a channel consumer. Listening for errors is optional, so this makes sure we don't deadlock if nobody is listening.

func (*Server) ReadyForPlayers added in v0.5.0

func (s *Server) ReadyForPlayers(ctx context.Context) error

ReadyForPlayers indicates the server is ready for players to join.

func (*Server) Release added in v0.4.0

func (s *Server) Release(ctx context.Context) error

Release manually releases any existing holds for this server.

func (*Server) Reserve added in v0.3.0

func (s *Server) Reserve(ctx context.Context, args *model.ReserveRequest) (*model.ReserveResponse, error)

Reserve reserves this server for use. Only applicable to reservation-based fleets.

func (*Server) SetCurrentPlayers added in v0.4.3

func (s *Server) SetCurrentPlayers(players int32)

SetCurrentPlayers sets the number of players currently in the game. Can be used as an alternative to PlayerJoined and PlayerLeft.

func (*Server) SetGameMap

func (s *Server) SetGameMap(gameMap string)

SetGameMap sets the server game map for query / metrics purposes.

func (*Server) SetGameType

func (s *Server) SetGameType(gameType string)

SetGameType sets the server game type for query / metrics purposes.

func (*Server) SetMaxPlayers

func (s *Server) SetMaxPlayers(max int32)

SetMaxPlayers sets the maximum players this server will host. It does not enforce this number, it only serves for query / metrics.

func (*Server) SetMetric added in v0.3.0

func (s *Server) SetMetric(index byte, value float32) error

SetMetric sets the metric at index to provided value. Only supported if the query type is QueryProtocolSQP, otherwise, ErrMetricsUnsupported is returned. The maximum index is specified by sqp.MaxMetrics, any index supplied above this will return ErrMetricOutOfBounds.

func (*Server) SetServerName

func (s *Server) SetServerName(name string)

SetServerName sets the server name for query / metrics purposes.

func (*Server) Start

func (s *Server) Start() error

Start starts the server, opening the configured query port which responds with the configured protocol. The event loop will also listen for changes to the `server.json` configuration file, publishing any changes in the form of allocation or de-allocation messages. As the server can start in an allocated state, make sure that another goroutine is consuming messages from at least the `OnAllocated()` and `OnDeallocated()` channels before calling this method.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the game, pushing a de-allocation message and closing the query port.

func (*Server) Unreserve added in v0.3.0

func (s *Server) Unreserve(ctx context.Context) error

Unreserve unreserves this server, making it available for use. Only applicable to reservation-based fleets.

func (*Server) WaitUntilTerminated

func (s *Server) WaitUntilTerminated() error

WaitUntilTerminated waits until the server receives a termination signal from the platform. The Unity Gaming Services process management daemon will signal the game server to stop. A graceful stop signal (SIGTERM) will be sent if the game server fleet has been configured to support it.

type Type

type Type int8

Type represents the type of server, that being 'allocations' or 'reservations'.

Directories

Path Synopsis
internal
a2s
sqp

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL