pitaya

package module
v0.0.0-...-4e7898a Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2021 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

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

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

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

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

Descriptor returns the protobuf message descriptor for a given message name

func Documentation

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

Documentation returns handler and remotes documentacion

func Error

func Error(err error, code uint32, 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

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

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

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

GroupAddMember adds UID to group

func GroupBroadcast

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

GroupBroadcast pushes the message to all members inside group

func GroupContainsMember

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

GroupContainsMember checks whether an UID is contained in group or not

func GroupCountMembers

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

GroupCountMembers get current member amount in group

func GroupCreate

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

GroupCreate creates a group

func GroupCreateWithTTL

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

GroupCreateWithTTL creates a group with given TTL

func GroupDelete

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

GroupDelete deletes whole group, including UIDs and base group

func GroupMembers

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

GroupMembers returns all member's UIDs

func GroupRemoveAll

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

GroupRemoveAll clears all UIDs

func GroupRemoveMember

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

GroupRemoveMember removes specified UID from group

func GroupRenewTTL

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

GroupRenewTTL renews group with the initial TTL

func InitGroups

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 NewSessionTimer

func NewSessionTimer(session *session.Session, interval time.Duration, fn timer.Func) *timer.Timer

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

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

RegisterModuleAfter registers a module after all registered modules

func RegisterModuleBefore

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

RegisterModuleBefore registers a module before all registered modules

func RegisterRPCJob

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

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

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

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

SendKickToUsers sends kick to an user array

func SendPushToUsers

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

func SetRateLimiter(wrapper *acceptor.RateLimiter)

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

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 mock_acceptor is a generated GoMock package.
Package mock_acceptor is a generated GoMock package.
pkg
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