pitaya

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2019 License: MIT Imports: 43 Imported by: 0

README

pitaya Build Status Coverage Status GoDoc Docs Go Report Card MIT licensed

Pitaya is an simple, fast and lightweight game server framework with clustering support and client libraries for iOS, Android, Unity and others through the C SDK. It provides a basic development framework for distributed multiplayer games and server-side applications.

Getting Started

Prerequisites
  • Go >= 1.10
  • etcd (used for service discovery)
  • nats (optional, used for sending and receiving rpc, grpc implementations can be used too if prefered)
  • docker (optional: used for running etcd and nats dependencies on containers)
Installing

clone the repo

git clone https://github.com/topfreegames/pitaya.git

setup pitaya dependencies

make setup
Hacking pitaya

Here's one example of running Pitaya:

Start etcd (This command requires docker-compose and will run an etcd container locally. An etcd may be run without docker if prefered.)

cd ./examples/testing && docker-compose up -d etcd

run the connector frontend server from cluster_grpc example

make run-cluster-grpc-example-connector

run the room backend server from the cluster_grpc example

make run-cluster-grpc-example-room

Now there should be 2 pitaya servers running, a frontend connector and a backend room. To send requests, use a REPL client for pitaya pitaya-cli.

$ pitaya-cli
Pitaya REPL Client
>>> connect localhost:3250
connected!
>>> request room.room.entry
>>> sv-> {"code":0,"result":"ok"}

Running the tests

make test

This command will run both unit and e2e tests.

Contributing

#TODO

Authors

  • TFG Co - Initial work

License

MIT License

Acknowledgements

  • nano authors for building the framework pitaya is based on.
  • pomelo authors for the inspiration on the distributed design and protocol

Security

If you have found a security vulnerability, please email security@tfgco.com

Resources

Benchmarks

using grpc

===============RUNNING BENCHMARK TESTS WITH GRPC===============
--- starting testing servers
--- sleeping for 5 seconds
goos: darwin
goarch: amd64
BenchmarkCreateManyClients-30                                              	    2000	    732922 ns/op
BenchmarkFrontHandlerWithSessionAndRawReturnsRaw-30                        	    2000	    712525 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtr-30                        	    2000	    704867 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtrManyClientsParallel-30     	    2000	    647892 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtrParallel-30                	    2000	    692803 ns/op
BenchmarkFrontHandlerWithSessionOnlyReturnsPtr-30                          	    2000	    880599 ns/op
BenchmarkFrontHandlerWithSessionOnlyReturnsPtrParallel-30                  	    2000	    630234 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtr-30                           	    1000	   1123467 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtrParallel-30                   	    2000	    667119 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtrParallelMultipleClients-30    	    2000	    664865 ns/op

using nats

===============RUNNING BENCHMARK TESTS WITH NATS===============
--- starting testing servers
--- sleeping for 5 seconds
goos: darwin
goarch: amd64
BenchmarkCreateManyClients-30                                              	    2000	    873214 ns/op
BenchmarkFrontHandlerWithSessionAndRawReturnsRaw-30                        	    2000	    702125 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtr-30                        	    2000	    794028 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtrManyClientsParallel-30     	    2000	    769600 ns/op
BenchmarkFrontHandlerWithSessionAndPtrReturnsPtrParallel-30                	    2000	    702894 ns/op
BenchmarkFrontHandlerWithSessionOnlyReturnsPtr-30                          	    2000	    984978 ns/op
BenchmarkFrontHandlerWithSessionOnlyReturnsPtrParallel-30                  	    2000	    699000 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtr-30                           	    1000	   1945727 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtrParallel-30                   	    2000	    784496 ns/op
BenchmarkBackHandlerWithSessionOnlyReturnsPtrParallelMultipleClients-30    	    2000	    846923 ns/op

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAcceptor

func AddAcceptor(ac acceptor.Acceptor)

AddAcceptor adds a new acceptor to app

func AddGRPCInfoToMetadata added in v0.7.6

func AddGRPCInfoToMetadata(
	metadata map[string]string,
	region string,
	host, port string,
	externalHost, externalPort string,
) map[string]string

AddGRPCInfoToMetadata adds host, external host and port into metadata

func AddMetricTagsToPropagateCtx added in v0.7.6

func AddMetricTagsToPropagateCtx(
	ctx context.Context,
	tags map[string]string,
) context.Context

AddMetricTagsToPropagateCtx adds a key and metric tags that will be propagated through RPC calls. Use the same tags that are at 'pitaya.metrics.additionalTags' config

func AddMetricsReporter

func AddMetricsReporter(mr metrics.Reporter)

AddMetricsReporter to be used

func AddRoute

func AddRoute(
	serverType string,
	routingFunction router.RoutingFunc,
) error

AddRoute adds a routing function to a server type

func AddToPropagateCtx

func AddToPropagateCtx(ctx context.Context, key string, val interface{}) context.Context

AddToPropagateCtx adds a key and value that will be propagated through RPC calls

func AfterHandler

func AfterHandler(h pipeline.AfterHandlerTempl)

AfterHandler pushs a function to the back of the functions pipeline that will be executed after the handler method

func BeforeHandler

func BeforeHandler(h pipeline.HandlerTempl)

BeforeHandler pushs a function to the back of the functions pipeline that will be executed before the handler method

func Configure

func Configure(
	isFrontend bool,
	serverType string,
	serverMode ServerMode,
	serverMetadata map[string]string,
	cfgs ...*viper.Viper,
)

Configure configures the app

func Descriptor added in v0.7.6

func Descriptor(protoName string) ([]byte, error)

Descriptor returns the protobuf message descriptor for a given message name

func Documentation added in v0.7.6

func Documentation(getPtrNames bool) (map[string]interface{}, error)

Documentation returns handler and remotes documentacion

func Error

func Error(err error, code string, metadata ...map[string]string) *errors.Error

Error creates a new error with a code, message and metadata

func ExtractSpan

func ExtractSpan(ctx context.Context) (opentracing.SpanContext, error)

ExtractSpan retrieves an opentracing span context from the given context The span context can be received directly or via an RPC call

func GetConfig

func GetConfig() *config.Config

GetConfig gets the pitaya config instance

func GetDefaultLoggerFromCtx added in v0.7.6

func GetDefaultLoggerFromCtx(ctx context.Context) logger.Logger

GetDefaultLoggerFromCtx returns the default logger from the given context

func GetDieChan

func GetDieChan() chan bool

GetDieChan gets the channel that the app sinalizes when its going to die

func GetFromPropagateCtx

func GetFromPropagateCtx(ctx context.Context, key string) interface{}

GetFromPropagateCtx adds a key and value that came through RPC calls

func GetMetricsReporters

func GetMetricsReporters() []metrics.Reporter

GetMetricsReporters gets registered metrics reporters

func GetModule

func GetModule(name string) (interfaces.Module, error)

GetModule gets a module with a name

func GetSerializer

func GetSerializer() serialize.Serializer

GetSerializer gets the app serializer

func GetServer

func GetServer() *cluster.Server

GetServer gets the local server instance

func GetServerByID

func GetServerByID(id string) (*cluster.Server, error)

GetServerByID returns the server with the specified id

func GetServerID

func GetServerID() string

GetServerID returns the generated server id

func GetServers added in v0.7.6

func GetServers() []*cluster.Server

GetServers get all servers

func GetServersByType

func GetServersByType(t string) (map[string]*cluster.Server, error)

GetServersByType get all servers of type

func GetSessionFromCtx

func GetSessionFromCtx(ctx context.Context) *session.Session

GetSessionFromCtx retrieves a session from a given context

func GroupAddMember added in v0.7.6

func GroupAddMember(ctx context.Context, groupName, uid string) error

GroupAddMember adds UID to group

func GroupBroadcast added in v0.7.6

func GroupBroadcast(ctx context.Context, frontendType, groupName, route string, v interface{}) error

GroupBroadcast pushes the message to all members inside group

func GroupContainsMember added in v0.7.6

func GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error)

GroupContainsMember checks whether an UID is contained in group or not

func GroupCountMembers added in v0.7.6

func GroupCountMembers(ctx context.Context, groupName string) (int, error)

GroupCountMembers get current member amount in group

func GroupCreate added in v0.7.6

func GroupCreate(ctx context.Context, groupName string) error

GroupCreate creates a group

func GroupCreateWithTTL added in v0.7.6

func GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error

GroupCreateWithTTL creates a group with given TTL

func GroupDelete added in v0.7.6

func GroupDelete(ctx context.Context, groupName string) error

GroupDelete deletes whole group, including UIDs and base group

func GroupMembers added in v0.7.6

func GroupMembers(ctx context.Context, groupName string) ([]string, error)

GroupMembers returns all member's UIDs

func GroupRemoveAll added in v0.7.6

func GroupRemoveAll(ctx context.Context, groupName string) error

GroupRemoveAll clears all UIDs

func GroupRemoveMember added in v0.7.6

func GroupRemoveMember(ctx context.Context, groupName, uid string) error

GroupRemoveMember removes specified UID from group

func GroupRenewTTL added in v0.7.6

func GroupRenewTTL(ctx context.Context, groupName string) error

GroupRenewTTL renews group with the initial TTL

func InitGroups added in v0.7.6

func InitGroups(groupService groups.GroupService)

InitGroups should be called once at the beginning of the application to setup the service type that will manage the groups

func NewAfterTimer

func NewAfterTimer(duration time.Duration, fn timer.Func) *timer.Timer

NewAfterTimer returns a new Timer containing a function that will be called after duration that specified by the duration argument. The duration d must be greater than zero; if not, NewAfterTimer will panic. Stop the timer to release associated resources.

func NewCondTimer

func NewCondTimer(condition timer.Condition, fn timer.Func) (*timer.Timer, error)

NewCondTimer returns a new Timer containing a function that will be called when condition satisfied that specified by the condition argument. The duration d must be greater than zero; if not, NewCondTimer will panic. Stop the timer to release associated resources.

func NewCountTimer

func NewCountTimer(interval time.Duration, count int, fn timer.Func) *timer.Timer

NewCountTimer returns a new Timer containing a function that will be called with a period specified by the duration argument. After count times, timer will be stopped automatically, It adjusts the intervals for slow receivers. The duration d must be greater than zero; if not, NewCountTimer will panic. Stop the timer to release associated resources.

func NewTimer

func NewTimer(interval time.Duration, fn timer.Func) *timer.Timer

NewTimer returns a new Timer containing a function that will be called with a period specified by the duration argument. It adjusts the intervals for slow receivers. The duration d must be greater than zero; if not, NewTimer will panic. Stop the timer to release associated resources.

func RPC

func RPC(ctx context.Context, routeStr string, reply proto.Message, arg proto.Message) error

RPC calls a method in a different server

func RPCTo

func RPCTo(ctx context.Context, serverID, routeStr string, reply proto.Message, arg proto.Message) error

RPCTo send a rpc to a specific server

func Register

func Register(c component.Component, options ...component.Option)

Register register a component with options

func RegisterModule

func RegisterModule(module interfaces.Module, name string) error

RegisterModule registers a module, by default it register after registered modules

func RegisterModuleAfter added in v0.7.6

func RegisterModuleAfter(module interfaces.Module, name string) error

RegisterModuleAfter registers a module after all registered modules

func RegisterModuleBefore added in v0.7.6

func RegisterModuleBefore(module interfaces.Module, name string) error

RegisterModuleBefore registers a module before all registered modules

func RegisterRPCJob added in v0.7.6

func RegisterRPCJob(rpcJob worker.RPCJob) error

RegisterRPCJob registers rpc job to execute jobs with retries

func RegisterRemote

func RegisterRemote(c component.Component, options ...component.Option)

RegisterRemote register a remote component with options

func ReliableRPC added in v0.7.6

func ReliableRPC(
	routeStr string,
	metadata map[string]interface{},
	reply, arg proto.Message,
) (jid string, err error)

ReliableRPC enqueues RPC to worker so it's executed asynchronously Default enqueue options are used

func ReliableRPCWithOptions added in v0.7.6

func ReliableRPCWithOptions(
	routeStr string,
	metadata map[string]interface{},
	reply, arg proto.Message,
	opts *worker.EnqueueOpts,
) (jid string, err error)

ReliableRPCWithOptions enqueues RPC to worker Receive worker options for this specific RPC

func SendKickToUsers added in v0.7.6

func SendKickToUsers(uids []string, frontendType string) ([]string, error)

SendKickToUsers sends kick to an user array

func SendPushToUsers

func SendPushToUsers(route string, v interface{}, uids []string, frontendType string) ([]string, error)

SendPushToUsers sends a message to the given list of users

func SetDebug

func SetDebug(debug bool)

SetDebug toggles debug on/off

func SetDictionary

func SetDictionary(dict map[string]uint16) error

SetDictionary sets routes map

func SetHeartbeatTime

func SetHeartbeatTime(interval time.Duration)

SetHeartbeatTime sets the heartbeat time

func SetLogger

func SetLogger(l logger.Logger)

SetLogger logger setter

func SetPacketDecoder

func SetPacketDecoder(d codec.PacketDecoder)

SetPacketDecoder changes the decoder used to parse messages received

func SetPacketEncoder

func SetPacketEncoder(e codec.PacketEncoder)

SetPacketEncoder changes the encoder used to package outgoing messages

func SetRPCClient

func SetRPCClient(s cluster.RPCClient)

SetRPCClient to be used

func SetRPCServer

func SetRPCServer(s cluster.RPCServer)

SetRPCServer to be used

func SetSerializer

func SetSerializer(seri serialize.Serializer)

SetSerializer customize application serializer, which automatically Marshal and UnMarshal handler payload

func SetServiceDiscoveryClient

func SetServiceDiscoveryClient(s cluster.ServiceDiscovery)

SetServiceDiscoveryClient to be used

func SetTimerBacklog

func SetTimerBacklog(c int)

SetTimerBacklog set the timer created/closing channel backlog, A small backlog may cause the logic to be blocked when call NewTimer/NewCountTimer/timer.Stop in main logic gorontine.

func SetTimerPrecision

func SetTimerPrecision(precision time.Duration)

SetTimerPrecision set the ticker precision, and time precision can not less than a Millisecond, and can not change after application running. The default precision is time.Second

func Shutdown

func Shutdown()

Shutdown send a signal to let 'pitaya' shutdown itself.

func Start

func Start()

Start starts the app

func StartWorker added in v0.7.6

func StartWorker(config *config.Config) error

StartWorker configures, starts and returns pitaya worker

Types

type App

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

App is the base app struct

type ServerMode

type ServerMode byte

ServerMode represents a server mode

const (

	// Cluster represents a server running with connection to other servers
	Cluster ServerMode
	// Standalone represents a server running without connection to other servers
	Standalone
)

Directories

Path Synopsis
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
conn
codec/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
message/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
examples
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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