pitaya

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2018 License: MIT Imports: 40 Imported by: 0

README

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

Pitaya is an easy to use, fast and lightweight game server framework with clustering support and client libraries for iOS, Android, Unity and others through the C SDK. The goal of pitaya is to provide 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, it's used for sending and receiving rpc, you can use grpc implementations too if you prefer)
  • docker (optional: 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 how to run one of the examples:

start etcd (this command requires docker-compose and will run an etcd container locally, you may run an etcd without docker if you prefer)

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

run the connector frontend server from cluster_grpc example

run-cluster-grpc-example-connector

run the room backend server from the cluster_grpc example

run-cluster-grpc-example-room

You should now have 2 pitaya servers running, a frontend connector and a backend room. You can then use pitaya-cli a REPL client for pitaya for sending some requests:

$ 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.

Deployment

#TODO

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

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 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.Handler)

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.Handler)

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 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 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 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 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

func RegisterRemote

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

RegisterRemote register a remote component with options

func SendPushToUsers

func SendPushToUsers(route string, v interface{}, uids []string, frontendType 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

Types

type App

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

App is the base app struct

type Group

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

Group represents a session group which is used to manage a number of sessions, data sent to the group will be sent to all sessions in it.

func NewGroup

func NewGroup(n string) *Group

NewGroup returns a new group instance

func (*Group) Add

func (c *Group) Add(session *session.Session) error

Add adds session to group

func (*Group) Broadcast

func (c *Group) Broadcast(route string, v interface{}) error

Broadcast pushes the message to all members

func (*Group) Close

func (c *Group) Close() error

Close destroy group, which will release all resource in the group

func (*Group) Contains

func (c *Group) Contains(uid string) bool

Contains check whether a UID is contained in current group or not

func (*Group) Count

func (c *Group) Count() int

Count get current member amount in the group

func (*Group) Leave

func (c *Group) Leave(s *session.Session) error

Leave removes specified UID related session from group

func (*Group) LeaveAll

func (c *Group) LeaveAll() error

LeaveAll clears all sessions in the group

func (*Group) Member

func (c *Group) Member(uid string) (*session.Session, error)

Member returns specified UID's session

func (*Group) Members

func (c *Group) Members() []string

Members returns all member's UID in current group

func (*Group) Multicast

func (c *Group) Multicast(route string, v interface{}, filter SessionFilter) error

Multicast push the message to the filtered clients

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
)

type SessionFilter

type SessionFilter func(*session.Session) bool

SessionFilter represents a filter which is used to filter sessions when Multicast, the session will receive the message when the filter returns true.

Directories

Path Synopsis
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
examples
demo/cluster_protobuf/protos
Package protos is a generated protocol buffer package.
Package protos is a generated protocol buffer package.
demo/protos
Package protos is a generated protocol buffer package.
Package protos is a generated protocol buffer package.
testing/protos
Package protos is a generated protocol buffer package.
Package protos is a generated protocol buffer package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
internal
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.
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.

Jump to

Keyboard shortcuts

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