repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
topfreegames/pitaya
worker/mocks/rpc_job.go
NewMockRPCJob
func NewMockRPCJob(ctrl *gomock.Controller) *MockRPCJob { mock := &MockRPCJob{ctrl: ctrl} mock.recorder = &MockRPCJobMockRecorder{mock} return mock }
go
func NewMockRPCJob(ctrl *gomock.Controller) *MockRPCJob { mock := &MockRPCJob{ctrl: ctrl} mock.recorder = &MockRPCJobMockRecorder{mock} return mock }
[ "func", "NewMockRPCJob", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockRPCJob", "{", "mock", ":=", "&", "MockRPCJob", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockRPCJobMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockRPCJob creates a new mock instance
[ "NewMockRPCJob", "creates", "a", "new", "mock", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L26-L30
train
topfreegames/pitaya
worker/mocks/rpc_job.go
GetArgReply
func (m *MockRPCJob) GetArgReply(arg0 string) (proto.Message, proto.Message, error) { ret := m.ctrl.Call(m, "GetArgReply", arg0) ret0, _ := ret[0].(proto.Message) ret1, _ := ret[1].(proto.Message) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
go
func (m *MockRPCJob) GetArgReply(arg0 string) (proto.Message, proto.Message, error) { ret := m.ctrl.Call(m, "GetArgReply", arg0) ret0, _ := ret[0].(proto.Message) ret1, _ := ret[1].(proto.Message) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
[ "func", "(", "m", "*", "MockRPCJob", ")", "GetArgReply", "(", "arg0", "string", ")", "(", "proto", ".", "Message", ",", "proto", ".", "Message", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "proto", ".", "Message", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "proto", ".", "Message", ")", "\n", "ret2", ",", "_", ":=", "ret", "[", "2", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", ",", "ret2", "\n", "}" ]
// GetArgReply mocks base method
[ "GetArgReply", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L38-L44
train
topfreegames/pitaya
worker/mocks/rpc_job.go
GetArgReply
func (mr *MockRPCJobMockRecorder) GetArgReply(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetArgReply", reflect.TypeOf((*MockRPCJob)(nil).GetArgReply), arg0) }
go
func (mr *MockRPCJobMockRecorder) GetArgReply(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetArgReply", reflect.TypeOf((*MockRPCJob)(nil).GetArgReply), arg0) }
[ "func", "(", "mr", "*", "MockRPCJobMockRecorder", ")", "GetArgReply", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockRPCJob", ")", "(", "nil", ")", ".", "GetArgReply", ")", ",", "arg0", ")", "\n", "}" ]
// GetArgReply indicates an expected call of GetArgReply
[ "GetArgReply", "indicates", "an", "expected", "call", "of", "GetArgReply" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L47-L49
train
topfreegames/pitaya
worker/mocks/rpc_job.go
RPC
func (m *MockRPCJob) RPC(arg0 context.Context, arg1, arg2 string, arg3, arg4 proto.Message) error { ret := m.ctrl.Call(m, "RPC", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockRPCJob) RPC(arg0 context.Context, arg1, arg2 string, arg3, arg4 proto.Message) error { ret := m.ctrl.Call(m, "RPC", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockRPCJob", ")", "RPC", "(", "arg0", "context", ".", "Context", ",", "arg1", ",", "arg2", "string", ",", "arg3", ",", "arg4", "proto", ".", "Message", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// RPC mocks base method
[ "RPC", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L52-L56
train
topfreegames/pitaya
worker/mocks/rpc_job.go
RPC
func (mr *MockRPCJobMockRecorder) RPC(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPC", reflect.TypeOf((*MockRPCJob)(nil).RPC), arg0, arg1, arg2, arg3, arg4) }
go
func (mr *MockRPCJobMockRecorder) RPC(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPC", reflect.TypeOf((*MockRPCJob)(nil).RPC), arg0, arg1, arg2, arg3, arg4) }
[ "func", "(", "mr", "*", "MockRPCJobMockRecorder", ")", "RPC", "(", "arg0", ",", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockRPCJob", ")", "(", "nil", ")", ".", "RPC", ")", ",", "arg0", ",", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ")", "\n", "}" ]
// RPC indicates an expected call of RPC
[ "RPC", "indicates", "an", "expected", "call", "of", "RPC" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L59-L61
train
topfreegames/pitaya
worker/mocks/rpc_job.go
ServerDiscovery
func (m *MockRPCJob) ServerDiscovery(arg0 string, arg1 map[string]interface{}) (string, error) { ret := m.ctrl.Call(m, "ServerDiscovery", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockRPCJob) ServerDiscovery(arg0 string, arg1 map[string]interface{}) (string, error) { ret := m.ctrl.Call(m, "ServerDiscovery", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockRPCJob", ")", "ServerDiscovery", "(", "arg0", "string", ",", "arg1", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "string", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// ServerDiscovery mocks base method
[ "ServerDiscovery", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/mocks/rpc_job.go#L64-L69
train
topfreegames/pitaya
defaultpipelines/default_struct_validator.go
Validate
func (v *DefaultValidator) Validate(ctx context.Context, in interface{}) (interface{}, error) { if in == nil { return in, nil } v.lazyinit() if err := v.validate.Struct(in); err != nil { return nil, err } return in, nil }
go
func (v *DefaultValidator) Validate(ctx context.Context, in interface{}) (interface{}, error) { if in == nil { return in, nil } v.lazyinit() if err := v.validate.Struct(in); err != nil { return nil, err } return in, nil }
[ "func", "(", "v", "*", "DefaultValidator", ")", "Validate", "(", "ctx", "context", ".", "Context", ",", "in", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "in", "==", "nil", "{", "return", "in", ",", "nil", "\n", "}", "\n\n", "v", ".", "lazyinit", "(", ")", "\n", "if", "err", ":=", "v", ".", "validate", ".", "Struct", "(", "in", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "in", ",", "nil", "\n", "}" ]
// Validate is the the function responsible for validating the 'in' parameter // based on the struct tags the parameter has. // This function has the pipeline.Handler signature so // it is possible to use it as a pipeline function
[ "Validate", "is", "the", "the", "function", "responsible", "for", "validating", "the", "in", "parameter", "based", "on", "the", "struct", "tags", "the", "parameter", "has", ".", "This", "function", "has", "the", "pipeline", ".", "Handler", "signature", "so", "it", "is", "possible", "to", "use", "it", "as", "a", "pipeline", "function" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/defaultpipelines/default_struct_validator.go#L21-L32
train
topfreegames/pitaya
app.go
Configure
func Configure( isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, cfgs ...*viper.Viper, ) { if app.configured { logger.Log.Warn("pitaya configured twice!") } app.config = config.NewConfig(cfgs...) if app.heartbeat == time.Duration(0) { app.heartbeat = app.config.GetDuration("pitaya.heartbeat.interval") } app.server.Frontend = isFrontend app.server.Type = serverType app.serverMode = serverMode app.server.Metadata = serverMetadata app.messageEncoder = message.NewMessagesEncoder(app.config.GetBool("pitaya.handler.messages.compression")) configureMetrics(serverType) configureDefaultPipelines(app.config) app.configured = true }
go
func Configure( isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, cfgs ...*viper.Viper, ) { if app.configured { logger.Log.Warn("pitaya configured twice!") } app.config = config.NewConfig(cfgs...) if app.heartbeat == time.Duration(0) { app.heartbeat = app.config.GetDuration("pitaya.heartbeat.interval") } app.server.Frontend = isFrontend app.server.Type = serverType app.serverMode = serverMode app.server.Metadata = serverMetadata app.messageEncoder = message.NewMessagesEncoder(app.config.GetBool("pitaya.handler.messages.compression")) configureMetrics(serverType) configureDefaultPipelines(app.config) app.configured = true }
[ "func", "Configure", "(", "isFrontend", "bool", ",", "serverType", "string", ",", "serverMode", "ServerMode", ",", "serverMetadata", "map", "[", "string", "]", "string", ",", "cfgs", "...", "*", "viper", ".", "Viper", ",", ")", "{", "if", "app", ".", "configured", "{", "logger", ".", "Log", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "app", ".", "config", "=", "config", ".", "NewConfig", "(", "cfgs", "...", ")", "\n", "if", "app", ".", "heartbeat", "==", "time", ".", "Duration", "(", "0", ")", "{", "app", ".", "heartbeat", "=", "app", ".", "config", ".", "GetDuration", "(", "\"", "\"", ")", "\n", "}", "\n", "app", ".", "server", ".", "Frontend", "=", "isFrontend", "\n", "app", ".", "server", ".", "Type", "=", "serverType", "\n", "app", ".", "serverMode", "=", "serverMode", "\n", "app", ".", "server", ".", "Metadata", "=", "serverMetadata", "\n", "app", ".", "messageEncoder", "=", "message", ".", "NewMessagesEncoder", "(", "app", ".", "config", ".", "GetBool", "(", "\"", "\"", ")", ")", "\n", "configureMetrics", "(", "serverType", ")", "\n", "configureDefaultPipelines", "(", "app", ".", "config", ")", "\n", "app", ".", "configured", "=", "true", "\n", "}" ]
// Configure configures the app
[ "Configure", "configures", "the", "app" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L119-L141
train
topfreegames/pitaya
app.go
AddAcceptor
func AddAcceptor(ac acceptor.Acceptor) { if !app.server.Frontend { logger.Log.Error("tried to add an acceptor to a backend server, skipping") return } app.acceptors = append(app.acceptors, ac) }
go
func AddAcceptor(ac acceptor.Acceptor) { if !app.server.Frontend { logger.Log.Error("tried to add an acceptor to a backend server, skipping") return } app.acceptors = append(app.acceptors, ac) }
[ "func", "AddAcceptor", "(", "ac", "acceptor", ".", "Acceptor", ")", "{", "if", "!", "app", ".", "server", ".", "Frontend", "{", "logger", ".", "Log", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "app", ".", "acceptors", "=", "append", "(", "app", ".", "acceptors", ",", "ac", ")", "\n", "}" ]
// AddAcceptor adds a new acceptor to app
[ "AddAcceptor", "adds", "a", "new", "acceptor", "to", "app" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L186-L192
train
topfreegames/pitaya
app.go
GetServerByID
func GetServerByID(id string) (*cluster.Server, error) { return app.serviceDiscovery.GetServer(id) }
go
func GetServerByID(id string) (*cluster.Server, error) { return app.serviceDiscovery.GetServer(id) }
[ "func", "GetServerByID", "(", "id", "string", ")", "(", "*", "cluster", ".", "Server", ",", "error", ")", "{", "return", "app", ".", "serviceDiscovery", ".", "GetServer", "(", "id", ")", "\n", "}" ]
// GetServerByID returns the server with the specified id
[ "GetServerByID", "returns", "the", "server", "with", "the", "specified", "id" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L271-L273
train
topfreegames/pitaya
app.go
GetServersByType
func GetServersByType(t string) (map[string]*cluster.Server, error) { return app.serviceDiscovery.GetServersByType(t) }
go
func GetServersByType(t string) (map[string]*cluster.Server, error) { return app.serviceDiscovery.GetServersByType(t) }
[ "func", "GetServersByType", "(", "t", "string", ")", "(", "map", "[", "string", "]", "*", "cluster", ".", "Server", ",", "error", ")", "{", "return", "app", ".", "serviceDiscovery", ".", "GetServersByType", "(", "t", ")", "\n", "}" ]
// GetServersByType get all servers of type
[ "GetServersByType", "get", "all", "servers", "of", "type" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L276-L278
train
topfreegames/pitaya
app.go
AddMetricsReporter
func AddMetricsReporter(mr metrics.Reporter) { app.metricsReporters = append(app.metricsReporters, mr) }
go
func AddMetricsReporter(mr metrics.Reporter) { app.metricsReporters = append(app.metricsReporters, mr) }
[ "func", "AddMetricsReporter", "(", "mr", "metrics", ".", "Reporter", ")", "{", "app", ".", "metricsReporters", "=", "append", "(", "app", ".", "metricsReporters", ",", "mr", ")", "\n", "}" ]
// AddMetricsReporter to be used
[ "AddMetricsReporter", "to", "be", "used" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L286-L288
train
topfreegames/pitaya
app.go
SetDictionary
func SetDictionary(dict map[string]uint16) error { if app.running { return constants.ErrChangeDictionaryWhileRunning } return message.SetDictionary(dict) }
go
func SetDictionary(dict map[string]uint16) error { if app.running { return constants.ErrChangeDictionaryWhileRunning } return message.SetDictionary(dict) }
[ "func", "SetDictionary", "(", "dict", "map", "[", "string", "]", "uint16", ")", "error", "{", "if", "app", ".", "running", "{", "return", "constants", ".", "ErrChangeDictionaryWhileRunning", "\n", "}", "\n", "return", "message", ".", "SetDictionary", "(", "dict", ")", "\n", "}" ]
// SetDictionary sets routes map
[ "SetDictionary", "sets", "routes", "map" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L485-L490
train
topfreegames/pitaya
app.go
Error
func Error(err error, code string, metadata ...map[string]string) *errors.Error { return errors.NewError(err, code, metadata...) }
go
func Error(err error, code string, metadata ...map[string]string) *errors.Error { return errors.NewError(err, code, metadata...) }
[ "func", "Error", "(", "err", "error", ",", "code", "string", ",", "metadata", "...", "map", "[", "string", "]", "string", ")", "*", "errors", ".", "Error", "{", "return", "errors", ".", "NewError", "(", "err", ",", "code", ",", "metadata", "...", ")", "\n", "}" ]
// Error creates a new error with a code, message and metadata
[ "Error", "creates", "a", "new", "error", "with", "a", "code", "message", "and", "metadata" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L518-L520
train
topfreegames/pitaya
app.go
GetSessionFromCtx
func GetSessionFromCtx(ctx context.Context) *session.Session { sessionVal := ctx.Value(constants.SessionCtxKey) if sessionVal == nil { logger.Log.Warn("ctx doesn't contain a session, are you calling GetSessionFromCtx from inside a remote?") return nil } return sessionVal.(*session.Session) }
go
func GetSessionFromCtx(ctx context.Context) *session.Session { sessionVal := ctx.Value(constants.SessionCtxKey) if sessionVal == nil { logger.Log.Warn("ctx doesn't contain a session, are you calling GetSessionFromCtx from inside a remote?") return nil } return sessionVal.(*session.Session) }
[ "func", "GetSessionFromCtx", "(", "ctx", "context", ".", "Context", ")", "*", "session", ".", "Session", "{", "sessionVal", ":=", "ctx", ".", "Value", "(", "constants", ".", "SessionCtxKey", ")", "\n", "if", "sessionVal", "==", "nil", "{", "logger", ".", "Log", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "sessionVal", ".", "(", "*", "session", ".", "Session", ")", "\n", "}" ]
// GetSessionFromCtx retrieves a session from a given context
[ "GetSessionFromCtx", "retrieves", "a", "session", "from", "a", "given", "context" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L523-L530
train
topfreegames/pitaya
app.go
GetDefaultLoggerFromCtx
func GetDefaultLoggerFromCtx(ctx context.Context) logger.Logger { return ctx.Value(constants.LoggerCtxKey).(logger.Logger) }
go
func GetDefaultLoggerFromCtx(ctx context.Context) logger.Logger { return ctx.Value(constants.LoggerCtxKey).(logger.Logger) }
[ "func", "GetDefaultLoggerFromCtx", "(", "ctx", "context", ".", "Context", ")", "logger", ".", "Logger", "{", "return", "ctx", ".", "Value", "(", "constants", ".", "LoggerCtxKey", ")", ".", "(", "logger", ".", "Logger", ")", "\n", "}" ]
// GetDefaultLoggerFromCtx returns the default logger from the given context
[ "GetDefaultLoggerFromCtx", "returns", "the", "default", "logger", "from", "the", "given", "context" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L533-L535
train
topfreegames/pitaya
app.go
AddMetricTagsToPropagateCtx
func AddMetricTagsToPropagateCtx( ctx context.Context, tags map[string]string, ) context.Context { return pcontext.AddToPropagateCtx(ctx, constants.MetricTagsKey, tags) }
go
func AddMetricTagsToPropagateCtx( ctx context.Context, tags map[string]string, ) context.Context { return pcontext.AddToPropagateCtx(ctx, constants.MetricTagsKey, tags) }
[ "func", "AddMetricTagsToPropagateCtx", "(", "ctx", "context", ".", "Context", ",", "tags", "map", "[", "string", "]", "string", ",", ")", "context", ".", "Context", "{", "return", "pcontext", ".", "AddToPropagateCtx", "(", "ctx", ",", "constants", ".", "MetricTagsKey", ",", "tags", ")", "\n", "}" ]
// 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
[ "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" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L540-L545
train
topfreegames/pitaya
app.go
GetFromPropagateCtx
func GetFromPropagateCtx(ctx context.Context, key string) interface{} { return pcontext.GetFromPropagateCtx(ctx, key) }
go
func GetFromPropagateCtx(ctx context.Context, key string) interface{} { return pcontext.GetFromPropagateCtx(ctx, key) }
[ "func", "GetFromPropagateCtx", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "interface", "{", "}", "{", "return", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "key", ")", "\n", "}" ]
// GetFromPropagateCtx adds a key and value that came through RPC calls
[ "GetFromPropagateCtx", "adds", "a", "key", "and", "value", "that", "came", "through", "RPC", "calls" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L553-L555
train
topfreegames/pitaya
app.go
ExtractSpan
func ExtractSpan(ctx context.Context) (opentracing.SpanContext, error) { return tracing.ExtractSpan(ctx) }
go
func ExtractSpan(ctx context.Context) (opentracing.SpanContext, error) { return tracing.ExtractSpan(ctx) }
[ "func", "ExtractSpan", "(", "ctx", "context", ".", "Context", ")", "(", "opentracing", ".", "SpanContext", ",", "error", ")", "{", "return", "tracing", ".", "ExtractSpan", "(", "ctx", ")", "\n", "}" ]
// ExtractSpan retrieves an opentracing span context from the given context // The span context can be received directly or via an RPC call
[ "ExtractSpan", "retrieves", "an", "opentracing", "span", "context", "from", "the", "given", "context", "The", "span", "context", "can", "be", "received", "directly", "or", "via", "an", "RPC", "call" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L559-L561
train
topfreegames/pitaya
app.go
Documentation
func Documentation(getPtrNames bool) (map[string]interface{}, error) { handlerDocs, err := handlerService.Docs(getPtrNames) if err != nil { return nil, err } remoteDocs, err := remoteService.Docs(getPtrNames) if err != nil { return nil, err } return map[string]interface{}{ "handlers": handlerDocs, "remotes": remoteDocs, }, nil }
go
func Documentation(getPtrNames bool) (map[string]interface{}, error) { handlerDocs, err := handlerService.Docs(getPtrNames) if err != nil { return nil, err } remoteDocs, err := remoteService.Docs(getPtrNames) if err != nil { return nil, err } return map[string]interface{}{ "handlers": handlerDocs, "remotes": remoteDocs, }, nil }
[ "func", "Documentation", "(", "getPtrNames", "bool", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "handlerDocs", ",", "err", ":=", "handlerService", ".", "Docs", "(", "getPtrNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "remoteDocs", ",", "err", ":=", "remoteService", ".", "Docs", "(", "getPtrNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "handlerDocs", ",", "\"", "\"", ":", "remoteDocs", ",", "}", ",", "nil", "\n", "}" ]
// Documentation returns handler and remotes documentacion
[ "Documentation", "returns", "handler", "and", "remotes", "documentacion" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L564-L577
train
topfreegames/pitaya
app.go
AddGRPCInfoToMetadata
func AddGRPCInfoToMetadata( metadata map[string]string, region string, host, port string, externalHost, externalPort string, ) map[string]string { metadata[constants.GRPCHostKey] = host metadata[constants.GRPCPortKey] = port metadata[constants.GRPCExternalHostKey] = externalHost metadata[constants.GRPCExternalPortKey] = externalPort metadata[constants.RegionKey] = region return metadata }
go
func AddGRPCInfoToMetadata( metadata map[string]string, region string, host, port string, externalHost, externalPort string, ) map[string]string { metadata[constants.GRPCHostKey] = host metadata[constants.GRPCPortKey] = port metadata[constants.GRPCExternalHostKey] = externalHost metadata[constants.GRPCExternalPortKey] = externalPort metadata[constants.RegionKey] = region return metadata }
[ "func", "AddGRPCInfoToMetadata", "(", "metadata", "map", "[", "string", "]", "string", ",", "region", "string", ",", "host", ",", "port", "string", ",", "externalHost", ",", "externalPort", "string", ",", ")", "map", "[", "string", "]", "string", "{", "metadata", "[", "constants", ".", "GRPCHostKey", "]", "=", "host", "\n", "metadata", "[", "constants", ".", "GRPCPortKey", "]", "=", "port", "\n", "metadata", "[", "constants", ".", "GRPCExternalHostKey", "]", "=", "externalHost", "\n", "metadata", "[", "constants", ".", "GRPCExternalPortKey", "]", "=", "externalPort", "\n", "metadata", "[", "constants", ".", "RegionKey", "]", "=", "region", "\n", "return", "metadata", "\n", "}" ]
// AddGRPCInfoToMetadata adds host, external host and // port into metadata
[ "AddGRPCInfoToMetadata", "adds", "host", "external", "host", "and", "port", "into", "metadata" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L581-L593
train
topfreegames/pitaya
app.go
StartWorker
func StartWorker(config *config.Config) error { var err error app.worker, err = worker.NewWorker(config) if err != nil { return err } app.worker.Start() return nil }
go
func StartWorker(config *config.Config) error { var err error app.worker, err = worker.NewWorker(config) if err != nil { return err } app.worker.Start() return nil }
[ "func", "StartWorker", "(", "config", "*", "config", ".", "Config", ")", "error", "{", "var", "err", "error", "\n", "app", ".", "worker", ",", "err", "=", "worker", ".", "NewWorker", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "app", ".", "worker", ".", "Start", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// StartWorker configures, starts and returns pitaya worker
[ "StartWorker", "configures", "starts", "and", "returns", "pitaya", "worker" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L601-L611
train
topfreegames/pitaya
app.go
RegisterRPCJob
func RegisterRPCJob(rpcJob worker.RPCJob) error { err := app.worker.RegisterRPCJob(rpcJob) return err }
go
func RegisterRPCJob(rpcJob worker.RPCJob) error { err := app.worker.RegisterRPCJob(rpcJob) return err }
[ "func", "RegisterRPCJob", "(", "rpcJob", "worker", ".", "RPCJob", ")", "error", "{", "err", ":=", "app", ".", "worker", ".", "RegisterRPCJob", "(", "rpcJob", ")", "\n", "return", "err", "\n", "}" ]
// RegisterRPCJob registers rpc job to execute jobs with retries
[ "RegisterRPCJob", "registers", "rpc", "job", "to", "execute", "jobs", "with", "retries" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/app.go#L614-L617
train
topfreegames/pitaya
component/service.go
NewService
func NewService(comp Component, opts []Option) *Service { s := &Service{ Type: reflect.TypeOf(comp), Receiver: reflect.ValueOf(comp), } // apply options for i := range opts { opt := opts[i] opt(&s.Options) } if name := s.Options.name; name != "" { s.Name = name } else { s.Name = reflect.Indirect(s.Receiver).Type().Name() } return s }
go
func NewService(comp Component, opts []Option) *Service { s := &Service{ Type: reflect.TypeOf(comp), Receiver: reflect.ValueOf(comp), } // apply options for i := range opts { opt := opts[i] opt(&s.Options) } if name := s.Options.name; name != "" { s.Name = name } else { s.Name = reflect.Indirect(s.Receiver).Type().Name() } return s }
[ "func", "NewService", "(", "comp", "Component", ",", "opts", "[", "]", "Option", ")", "*", "Service", "{", "s", ":=", "&", "Service", "{", "Type", ":", "reflect", ".", "TypeOf", "(", "comp", ")", ",", "Receiver", ":", "reflect", ".", "ValueOf", "(", "comp", ")", ",", "}", "\n\n", "// apply options", "for", "i", ":=", "range", "opts", "{", "opt", ":=", "opts", "[", "i", "]", "\n", "opt", "(", "&", "s", ".", "Options", ")", "\n", "}", "\n", "if", "name", ":=", "s", ".", "Options", ".", "name", ";", "name", "!=", "\"", "\"", "{", "s", ".", "Name", "=", "name", "\n", "}", "else", "{", "s", ".", "Name", "=", "reflect", ".", "Indirect", "(", "s", ".", "Receiver", ")", ".", "Type", "(", ")", ".", "Name", "(", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// NewService creates a new service
[ "NewService", "creates", "a", "new", "service" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/component/service.go#L62-L80
train
topfreegames/pitaya
component/service.go
ValidateMessageType
func (h *Handler) ValidateMessageType(msgType message.Type) (exitOnError bool, err error) { if h.MessageType != msgType { switch msgType { case message.Request: err = constants.ErrRequestOnNotify exitOnError = true case message.Notify: err = constants.ErrNotifyOnRequest } } return }
go
func (h *Handler) ValidateMessageType(msgType message.Type) (exitOnError bool, err error) { if h.MessageType != msgType { switch msgType { case message.Request: err = constants.ErrRequestOnNotify exitOnError = true case message.Notify: err = constants.ErrNotifyOnRequest } } return }
[ "func", "(", "h", "*", "Handler", ")", "ValidateMessageType", "(", "msgType", "message", ".", "Type", ")", "(", "exitOnError", "bool", ",", "err", "error", ")", "{", "if", "h", ".", "MessageType", "!=", "msgType", "{", "switch", "msgType", "{", "case", "message", ".", "Request", ":", "err", "=", "constants", ".", "ErrRequestOnNotify", "\n", "exitOnError", "=", "true", "\n\n", "case", "message", ".", "Notify", ":", "err", "=", "constants", ".", "ErrNotifyOnRequest", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ValidateMessageType validates a given message type against the handler's one // and returns an error if it is a mismatch and a boolean indicating if the caller should // exit in the presence of this error or not.
[ "ValidateMessageType", "validates", "a", "given", "message", "type", "against", "the", "handler", "s", "one", "and", "returns", "an", "error", "if", "it", "is", "a", "mismatch", "and", "a", "boolean", "indicating", "if", "the", "caller", "should", "exit", "in", "the", "presence", "of", "this", "error", "or", "not", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/component/service.go#L161-L173
train
topfreegames/pitaya
examples/demo/cluster_protobuf/services/room.go
Init
func (r *Room) Init() { gsi := groups.NewMemoryGroupService(config.NewConfig()) pitaya.InitGroups(gsi) pitaya.GroupCreate(context.Background(), "room") }
go
func (r *Room) Init() { gsi := groups.NewMemoryGroupService(config.NewConfig()) pitaya.InitGroups(gsi) pitaya.GroupCreate(context.Background(), "room") }
[ "func", "(", "r", "*", "Room", ")", "Init", "(", ")", "{", "gsi", ":=", "groups", ".", "NewMemoryGroupService", "(", "config", ".", "NewConfig", "(", ")", ")", "\n", "pitaya", ".", "InitGroups", "(", "gsi", ")", "\n", "pitaya", ".", "GroupCreate", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// Init runs on service initialization
[ "Init", "runs", "on", "service", "initialization" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster_protobuf/services/room.go#L53-L57
train
topfreegames/pitaya
tracing/log.go
LogError
func LogError(span opentracing.Span, message string) { span.SetTag("error", true) span.LogFields( log.String("event", "error"), log.String("message", message), ) }
go
func LogError(span opentracing.Span, message string) { span.SetTag("error", true) span.LogFields( log.String("event", "error"), log.String("message", message), ) }
[ "func", "LogError", "(", "span", "opentracing", ".", "Span", ",", "message", "string", ")", "{", "span", ".", "SetTag", "(", "\"", "\"", ",", "true", ")", "\n", "span", ".", "LogFields", "(", "log", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "log", ".", "String", "(", "\"", "\"", ",", "message", ")", ",", ")", "\n", "}" ]
// LogError logs an error to an opentracing span
[ "LogError", "logs", "an", "error", "to", "an", "opentracing", "span" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/log.go#L31-L37
train
topfreegames/pitaya
cluster/nats_rpc_client.go
BroadcastSessionBind
func (ns *NatsRPCClient) BroadcastSessionBind(uid string) error { msg := &protos.BindMsg{ Uid: uid, Fid: ns.server.ID, } msgData, err := proto.Marshal(msg) if err != nil { return err } return ns.Send(GetBindBroadcastTopic(ns.server.Type), msgData) }
go
func (ns *NatsRPCClient) BroadcastSessionBind(uid string) error { msg := &protos.BindMsg{ Uid: uid, Fid: ns.server.ID, } msgData, err := proto.Marshal(msg) if err != nil { return err } return ns.Send(GetBindBroadcastTopic(ns.server.Type), msgData) }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "BroadcastSessionBind", "(", "uid", "string", ")", "error", "{", "msg", ":=", "&", "protos", ".", "BindMsg", "{", "Uid", ":", "uid", ",", "Fid", ":", "ns", ".", "server", ".", "ID", ",", "}", "\n", "msgData", ",", "err", ":=", "proto", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ns", ".", "Send", "(", "GetBindBroadcastTopic", "(", "ns", ".", "server", ".", "Type", ")", ",", "msgData", ")", "\n", "}" ]
// BroadcastSessionBind sends the binding information to other servers that may br interested in this info
[ "BroadcastSessionBind", "sends", "the", "binding", "information", "to", "other", "servers", "that", "may", "br", "interested", "in", "this", "info" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L91-L101
train
topfreegames/pitaya
cluster/nats_rpc_client.go
Send
func (ns *NatsRPCClient) Send(topic string, data []byte) error { if !ns.running { return constants.ErrRPCClientNotInitialized } return ns.conn.Publish(topic, data) }
go
func (ns *NatsRPCClient) Send(topic string, data []byte) error { if !ns.running { return constants.ErrRPCClientNotInitialized } return ns.conn.Publish(topic, data) }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "Send", "(", "topic", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "if", "!", "ns", ".", "running", "{", "return", "constants", ".", "ErrRPCClientNotInitialized", "\n", "}", "\n", "return", "ns", ".", "conn", ".", "Publish", "(", "topic", ",", "data", ")", "\n", "}" ]
// Send publishes a message in a given topic
[ "Send", "publishes", "a", "message", "in", "a", "given", "topic" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L104-L109
train
topfreegames/pitaya
cluster/nats_rpc_client.go
SendPush
func (ns *NatsRPCClient) SendPush(userID string, frontendSv *Server, push *protos.Push) error { topic := GetUserMessagesTopic(userID, frontendSv.Type) msg, err := proto.Marshal(push) if err != nil { return err } return ns.Send(topic, msg) }
go
func (ns *NatsRPCClient) SendPush(userID string, frontendSv *Server, push *protos.Push) error { topic := GetUserMessagesTopic(userID, frontendSv.Type) msg, err := proto.Marshal(push) if err != nil { return err } return ns.Send(topic, msg) }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "SendPush", "(", "userID", "string", ",", "frontendSv", "*", "Server", ",", "push", "*", "protos", ".", "Push", ")", "error", "{", "topic", ":=", "GetUserMessagesTopic", "(", "userID", ",", "frontendSv", ".", "Type", ")", "\n", "msg", ",", "err", ":=", "proto", ".", "Marshal", "(", "push", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ns", ".", "Send", "(", "topic", ",", "msg", ")", "\n", "}" ]
// SendPush sends a message to a user
[ "SendPush", "sends", "a", "message", "to", "a", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L112-L119
train
topfreegames/pitaya
cluster/nats_rpc_client.go
SendKick
func (ns *NatsRPCClient) SendKick(userID string, serverType string, kick *protos.KickMsg) error { topic := GetUserKickTopic(userID, serverType) msg, err := proto.Marshal(kick) if err != nil { return err } return ns.Send(topic, msg) }
go
func (ns *NatsRPCClient) SendKick(userID string, serverType string, kick *protos.KickMsg) error { topic := GetUserKickTopic(userID, serverType) msg, err := proto.Marshal(kick) if err != nil { return err } return ns.Send(topic, msg) }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "SendKick", "(", "userID", "string", ",", "serverType", "string", ",", "kick", "*", "protos", ".", "KickMsg", ")", "error", "{", "topic", ":=", "GetUserKickTopic", "(", "userID", ",", "serverType", ")", "\n", "msg", ",", "err", ":=", "proto", ".", "Marshal", "(", "kick", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ns", ".", "Send", "(", "topic", ",", "msg", ")", "\n", "}" ]
// SendKick kicks an user
[ "SendKick", "kicks", "an", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L122-L129
train
topfreegames/pitaya
cluster/nats_rpc_client.go
Call
func (ns *NatsRPCClient) Call( ctx context.Context, rpcType protos.RPCType, route *route.Route, session *session.Session, msg *message.Message, server *Server, ) (*protos.Response, error) { parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } tags := opentracing.Tags{ "span.kind": "client", "local.id": ns.server.ID, "peer.serverType": server.Type, "peer.id": server.ID, } ctx = tracing.StartSpan(ctx, "RPC Call", tags, parent) defer tracing.FinishSpan(ctx, err) if !ns.running { err = constants.ErrRPCClientNotInitialized return nil, err } req, err := buildRequest(ctx, rpcType, route, session, msg, ns.server) if err != nil { return nil, err } marshalledData, err := proto.Marshal(&req) if err != nil { return nil, err } var m *nats.Msg if ns.metricsReporters != nil { startTime := time.Now() ctx = pcontext.AddToPropagateCtx(ctx, constants.StartTimeKey, startTime.UnixNano()) ctx = pcontext.AddToPropagateCtx(ctx, constants.RouteKey, route.String()) defer func() { typ := "rpc" metrics.ReportTimingFromCtx(ctx, ns.metricsReporters, typ, err) }() } m, err = ns.conn.Request(getChannel(server.Type, server.ID), marshalledData, ns.reqTimeout) if err != nil { return nil, err } res := &protos.Response{} err = proto.Unmarshal(m.Data, res) if err != nil { return nil, err } if res.Error != nil { if res.Error.Code == "" { res.Error.Code = errors.ErrUnknownCode } err = &errors.Error{ Code: res.Error.Code, Message: res.Error.Msg, Metadata: res.Error.Metadata, } return nil, err } return res, nil }
go
func (ns *NatsRPCClient) Call( ctx context.Context, rpcType protos.RPCType, route *route.Route, session *session.Session, msg *message.Message, server *Server, ) (*protos.Response, error) { parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } tags := opentracing.Tags{ "span.kind": "client", "local.id": ns.server.ID, "peer.serverType": server.Type, "peer.id": server.ID, } ctx = tracing.StartSpan(ctx, "RPC Call", tags, parent) defer tracing.FinishSpan(ctx, err) if !ns.running { err = constants.ErrRPCClientNotInitialized return nil, err } req, err := buildRequest(ctx, rpcType, route, session, msg, ns.server) if err != nil { return nil, err } marshalledData, err := proto.Marshal(&req) if err != nil { return nil, err } var m *nats.Msg if ns.metricsReporters != nil { startTime := time.Now() ctx = pcontext.AddToPropagateCtx(ctx, constants.StartTimeKey, startTime.UnixNano()) ctx = pcontext.AddToPropagateCtx(ctx, constants.RouteKey, route.String()) defer func() { typ := "rpc" metrics.ReportTimingFromCtx(ctx, ns.metricsReporters, typ, err) }() } m, err = ns.conn.Request(getChannel(server.Type, server.ID), marshalledData, ns.reqTimeout) if err != nil { return nil, err } res := &protos.Response{} err = proto.Unmarshal(m.Data, res) if err != nil { return nil, err } if res.Error != nil { if res.Error.Code == "" { res.Error.Code = errors.ErrUnknownCode } err = &errors.Error{ Code: res.Error.Code, Message: res.Error.Msg, Metadata: res.Error.Metadata, } return nil, err } return res, nil }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "Call", "(", "ctx", "context", ".", "Context", ",", "rpcType", "protos", ".", "RPCType", ",", "route", "*", "route", ".", "Route", ",", "session", "*", "session", ".", "Session", ",", "msg", "*", "message", ".", "Message", ",", "server", "*", "Server", ",", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "parent", ",", "err", ":=", "tracing", ".", "ExtractSpan", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Warnf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "tags", ":=", "opentracing", ".", "Tags", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "ns", ".", "server", ".", "ID", ",", "\"", "\"", ":", "server", ".", "Type", ",", "\"", "\"", ":", "server", ".", "ID", ",", "}", "\n", "ctx", "=", "tracing", ".", "StartSpan", "(", "ctx", ",", "\"", "\"", ",", "tags", ",", "parent", ")", "\n", "defer", "tracing", ".", "FinishSpan", "(", "ctx", ",", "err", ")", "\n\n", "if", "!", "ns", ".", "running", "{", "err", "=", "constants", ".", "ErrRPCClientNotInitialized", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "req", ",", "err", ":=", "buildRequest", "(", "ctx", ",", "rpcType", ",", "route", ",", "session", ",", "msg", ",", "ns", ".", "server", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "marshalledData", ",", "err", ":=", "proto", ".", "Marshal", "(", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "m", "*", "nats", ".", "Msg", "\n\n", "if", "ns", ".", "metricsReporters", "!=", "nil", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ctx", "=", "pcontext", ".", "AddToPropagateCtx", "(", "ctx", ",", "constants", ".", "StartTimeKey", ",", "startTime", ".", "UnixNano", "(", ")", ")", "\n", "ctx", "=", "pcontext", ".", "AddToPropagateCtx", "(", "ctx", ",", "constants", ".", "RouteKey", ",", "route", ".", "String", "(", ")", ")", "\n", "defer", "func", "(", ")", "{", "typ", ":=", "\"", "\"", "\n", "metrics", ".", "ReportTimingFromCtx", "(", "ctx", ",", "ns", ".", "metricsReporters", ",", "typ", ",", "err", ")", "\n", "}", "(", ")", "\n", "}", "\n", "m", ",", "err", "=", "ns", ".", "conn", ".", "Request", "(", "getChannel", "(", "server", ".", "Type", ",", "server", ".", "ID", ")", ",", "marshalledData", ",", "ns", ".", "reqTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ":=", "&", "protos", ".", "Response", "{", "}", "\n", "err", "=", "proto", ".", "Unmarshal", "(", "m", ".", "Data", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "Error", "!=", "nil", "{", "if", "res", ".", "Error", ".", "Code", "==", "\"", "\"", "{", "res", ".", "Error", ".", "Code", "=", "errors", ".", "ErrUnknownCode", "\n", "}", "\n", "err", "=", "&", "errors", ".", "Error", "{", "Code", ":", "res", ".", "Error", ".", "Code", ",", "Message", ":", "res", ".", "Error", ".", "Msg", ",", "Metadata", ":", "res", ".", "Error", ".", "Metadata", ",", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Call calls a method remotelly
[ "Call", "calls", "a", "method", "remotelly" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L132-L200
train
topfreegames/pitaya
cluster/nats_rpc_client.go
Init
func (ns *NatsRPCClient) Init() error { ns.running = true conn, err := setupNatsConn(ns.connString, ns.appDieChan, nats.MaxReconnects(ns.maxReconnectionRetries)) if err != nil { return err } ns.conn = conn return nil }
go
func (ns *NatsRPCClient) Init() error { ns.running = true conn, err := setupNatsConn(ns.connString, ns.appDieChan, nats.MaxReconnects(ns.maxReconnectionRetries)) if err != nil { return err } ns.conn = conn return nil }
[ "func", "(", "ns", "*", "NatsRPCClient", ")", "Init", "(", ")", "error", "{", "ns", ".", "running", "=", "true", "\n", "conn", ",", "err", ":=", "setupNatsConn", "(", "ns", ".", "connString", ",", "ns", ".", "appDieChan", ",", "nats", ".", "MaxReconnects", "(", "ns", ".", "maxReconnectionRetries", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ns", ".", "conn", "=", "conn", "\n", "return", "nil", "\n", "}" ]
// Init inits nats rpc client
[ "Init", "inits", "nats", "rpc", "client" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/nats_rpc_client.go#L203-L211
train
topfreegames/pitaya
agent/agent_remote.go
NewRemote
func NewRemote( sess *protos.Session, reply string, rpcClient cluster.RPCClient, encoder codec.PacketEncoder, serializer serialize.Serializer, serviceDiscovery cluster.ServiceDiscovery, frontendID string, messageEncoder message.Encoder, ) (*Remote, error) { a := &Remote{ chDie: make(chan struct{}), reply: reply, // TODO this is totally coupled with NATS serializer: serializer, encoder: encoder, rpcClient: rpcClient, serviceDiscovery: serviceDiscovery, frontendID: frontendID, messageEncoder: messageEncoder, } // binding session s := session.New(a, false, sess.GetUid()) s.SetFrontendData(frontendID, sess.GetId()) err := s.SetDataEncoded(sess.GetData()) if err != nil { return nil, err } a.Session = s return a, nil }
go
func NewRemote( sess *protos.Session, reply string, rpcClient cluster.RPCClient, encoder codec.PacketEncoder, serializer serialize.Serializer, serviceDiscovery cluster.ServiceDiscovery, frontendID string, messageEncoder message.Encoder, ) (*Remote, error) { a := &Remote{ chDie: make(chan struct{}), reply: reply, // TODO this is totally coupled with NATS serializer: serializer, encoder: encoder, rpcClient: rpcClient, serviceDiscovery: serviceDiscovery, frontendID: frontendID, messageEncoder: messageEncoder, } // binding session s := session.New(a, false, sess.GetUid()) s.SetFrontendData(frontendID, sess.GetId()) err := s.SetDataEncoded(sess.GetData()) if err != nil { return nil, err } a.Session = s return a, nil }
[ "func", "NewRemote", "(", "sess", "*", "protos", ".", "Session", ",", "reply", "string", ",", "rpcClient", "cluster", ".", "RPCClient", ",", "encoder", "codec", ".", "PacketEncoder", ",", "serializer", "serialize", ".", "Serializer", ",", "serviceDiscovery", "cluster", ".", "ServiceDiscovery", ",", "frontendID", "string", ",", "messageEncoder", "message", ".", "Encoder", ",", ")", "(", "*", "Remote", ",", "error", ")", "{", "a", ":=", "&", "Remote", "{", "chDie", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "reply", ":", "reply", ",", "// TODO this is totally coupled with NATS", "serializer", ":", "serializer", ",", "encoder", ":", "encoder", ",", "rpcClient", ":", "rpcClient", ",", "serviceDiscovery", ":", "serviceDiscovery", ",", "frontendID", ":", "frontendID", ",", "messageEncoder", ":", "messageEncoder", ",", "}", "\n\n", "// binding session", "s", ":=", "session", ".", "New", "(", "a", ",", "false", ",", "sess", ".", "GetUid", "(", ")", ")", "\n", "s", ".", "SetFrontendData", "(", "frontendID", ",", "sess", ".", "GetId", "(", ")", ")", "\n", "err", ":=", "s", ".", "SetDataEncoded", "(", "sess", ".", "GetData", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "a", ".", "Session", "=", "s", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// NewRemote create new Remote instance
[ "NewRemote", "create", "new", "Remote", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent_remote.go#L56-L87
train
topfreegames/pitaya
agent/agent_remote.go
Push
func (a *Remote) Push(route string, v interface{}) error { if (reflect.TypeOf(a.rpcClient) == reflect.TypeOf(&cluster.NatsRPCClient{}) && a.Session.UID() == "") { return constants.ErrNoUIDBind } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%dbytes", a.Session.ID(), a.Session.UID(), route, len(d)) default: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%+v", a.Session.ID(), a.Session.UID(), route, v) } sv, err := a.serviceDiscovery.GetServer(a.frontendID) if err != nil { return err } return a.sendPush( pendingMessage{typ: message.Push, route: route, payload: v}, a.Session.UID(), sv, ) }
go
func (a *Remote) Push(route string, v interface{}) error { if (reflect.TypeOf(a.rpcClient) == reflect.TypeOf(&cluster.NatsRPCClient{}) && a.Session.UID() == "") { return constants.ErrNoUIDBind } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%dbytes", a.Session.ID(), a.Session.UID(), route, len(d)) default: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%+v", a.Session.ID(), a.Session.UID(), route, v) } sv, err := a.serviceDiscovery.GetServer(a.frontendID) if err != nil { return err } return a.sendPush( pendingMessage{typ: message.Push, route: route, payload: v}, a.Session.UID(), sv, ) }
[ "func", "(", "a", "*", "Remote", ")", "Push", "(", "route", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "(", "reflect", ".", "TypeOf", "(", "a", ".", "rpcClient", ")", "==", "reflect", ".", "TypeOf", "(", "&", "cluster", ".", "NatsRPCClient", "{", "}", ")", "&&", "a", ".", "Session", ".", "UID", "(", ")", "==", "\"", "\"", ")", "{", "return", "constants", ".", "ErrNoUIDBind", "\n", "}", "\n", "switch", "d", ":=", "v", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "route", ",", "len", "(", "d", ")", ")", "\n", "default", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "route", ",", "v", ")", "\n", "}", "\n\n", "sv", ",", "err", ":=", "a", ".", "serviceDiscovery", ".", "GetServer", "(", "a", ".", "frontendID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "a", ".", "sendPush", "(", "pendingMessage", "{", "typ", ":", "message", ".", "Push", ",", "route", ":", "route", ",", "payload", ":", "v", "}", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "sv", ",", ")", "\n", "}" ]
// Push pushes the message to the user
[ "Push", "pushes", "the", "message", "to", "the", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent_remote.go#L105-L127
train
topfreegames/pitaya
agent/agent_remote.go
ResponseMID
func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error { err := false if len(isError) > 0 { err = isError[0] } if mid <= 0 { return constants.ErrSessionOnNotify } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Response, ID=%d, MID=%d, Data=%dbytes", a.Session.ID(), mid, len(d)) default: logger.Log.Infof("Type=Response, ID=%d, MID=%d, Data=%+v", a.Session.ID(), mid, v) } return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}, a.reply) }
go
func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error { err := false if len(isError) > 0 { err = isError[0] } if mid <= 0 { return constants.ErrSessionOnNotify } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Response, ID=%d, MID=%d, Data=%dbytes", a.Session.ID(), mid, len(d)) default: logger.Log.Infof("Type=Response, ID=%d, MID=%d, Data=%+v", a.Session.ID(), mid, v) } return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}, a.reply) }
[ "func", "(", "a", "*", "Remote", ")", "ResponseMID", "(", "ctx", "context", ".", "Context", ",", "mid", "uint", ",", "v", "interface", "{", "}", ",", "isError", "...", "bool", ")", "error", "{", "err", ":=", "false", "\n", "if", "len", "(", "isError", ")", ">", "0", "{", "err", "=", "isError", "[", "0", "]", "\n", "}", "\n\n", "if", "mid", "<=", "0", "{", "return", "constants", ".", "ErrSessionOnNotify", "\n", "}", "\n\n", "switch", "d", ":=", "v", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "mid", ",", "len", "(", "d", ")", ")", "\n", "default", ":", "logger", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "mid", ",", "v", ")", "\n", "}", "\n\n", "return", "a", ".", "send", "(", "pendingMessage", "{", "ctx", ":", "ctx", ",", "typ", ":", "message", ".", "Response", ",", "mid", ":", "mid", ",", "payload", ":", "v", ",", "err", ":", "err", "}", ",", "a", ".", "reply", ")", "\n", "}" ]
// ResponseMID reponds the message with mid to the user
[ "ResponseMID", "reponds", "the", "message", "with", "mid", "to", "the", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent_remote.go#L130-L150
train
topfreegames/pitaya
errors/errors.go
CodeFromError
func CodeFromError(err error) string { if err == nil { return "" } pitayaErr, ok := err.(*Error) if !ok { return ErrUnknownCode } if pitayaErr == nil { return "" } return pitayaErr.Code }
go
func CodeFromError(err error) string { if err == nil { return "" } pitayaErr, ok := err.(*Error) if !ok { return ErrUnknownCode } if pitayaErr == nil { return "" } return pitayaErr.Code }
[ "func", "CodeFromError", "(", "err", "error", ")", "string", "{", "if", "err", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "pitayaErr", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", "\n", "if", "!", "ok", "{", "return", "ErrUnknownCode", "\n", "}", "\n\n", "if", "pitayaErr", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "pitayaErr", ".", "Code", "\n", "}" ]
// CodeFromError returns the code of error. // If error is nil, return empty string. // If error is not a pitaya error, returns unkown code
[ "CodeFromError", "returns", "the", "code", "of", "error", ".", "If", "error", "is", "nil", "return", "empty", "string", ".", "If", "error", "is", "not", "a", "pitaya", "error", "returns", "unkown", "code" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/errors/errors.go#L81-L96
train
topfreegames/pitaya
timer.go
NewTimer
func NewTimer(interval time.Duration, fn timer.Func) *timer.Timer { return NewCountTimer(interval, timer.LoopForever, fn) }
go
func NewTimer(interval time.Duration, fn timer.Func) *timer.Timer { return NewCountTimer(interval, timer.LoopForever, fn) }
[ "func", "NewTimer", "(", "interval", "time", ".", "Duration", ",", "fn", "timer", ".", "Func", ")", "*", "timer", ".", "Timer", "{", "return", "NewCountTimer", "(", "interval", ",", "timer", ".", "LoopForever", ",", "fn", ")", "\n", "}" ]
// 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.
[ "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", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/timer.go#L36-L38
train
topfreegames/pitaya
timer.go
NewCountTimer
func NewCountTimer(interval time.Duration, count int, fn timer.Func) *timer.Timer { if fn == nil { panic("pitaya/timer: nil timer function") } if interval <= 0 { panic("non-positive interval for NewTimer") } t := timer.NewTimer(fn, interval, count) // add to manager timer.Manager.ChCreatedTimer <- t return t }
go
func NewCountTimer(interval time.Duration, count int, fn timer.Func) *timer.Timer { if fn == nil { panic("pitaya/timer: nil timer function") } if interval <= 0 { panic("non-positive interval for NewTimer") } t := timer.NewTimer(fn, interval, count) // add to manager timer.Manager.ChCreatedTimer <- t return t }
[ "func", "NewCountTimer", "(", "interval", "time", ".", "Duration", ",", "count", "int", ",", "fn", "timer", ".", "Func", ")", "*", "timer", ".", "Timer", "{", "if", "fn", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "interval", "<=", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "t", ":=", "timer", ".", "NewTimer", "(", "fn", ",", "interval", ",", "count", ")", "\n", "// add to manager", "timer", ".", "Manager", ".", "ChCreatedTimer", "<-", "t", "\n", "return", "t", "\n", "}" ]
// 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.
[ "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", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/timer.go#L45-L57
train
topfreegames/pitaya
timer.go
NewAfterTimer
func NewAfterTimer(duration time.Duration, fn timer.Func) *timer.Timer { return NewCountTimer(duration, 1, fn) }
go
func NewAfterTimer(duration time.Duration, fn timer.Func) *timer.Timer { return NewCountTimer(duration, 1, fn) }
[ "func", "NewAfterTimer", "(", "duration", "time", ".", "Duration", ",", "fn", "timer", ".", "Func", ")", "*", "timer", ".", "Timer", "{", "return", "NewCountTimer", "(", "duration", ",", "1", ",", "fn", ")", "\n", "}" ]
// 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.
[ "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", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/timer.go#L63-L65
train
topfreegames/pitaya
timer.go
NewCondTimer
func NewCondTimer(condition timer.Condition, fn timer.Func) (*timer.Timer, error) { if condition == nil { return nil, constants.ErrNilCondition } t := NewCountTimer(time.Duration(math.MaxInt64), timer.LoopForever, fn) t.SetCondition(condition) return t, nil }
go
func NewCondTimer(condition timer.Condition, fn timer.Func) (*timer.Timer, error) { if condition == nil { return nil, constants.ErrNilCondition } t := NewCountTimer(time.Duration(math.MaxInt64), timer.LoopForever, fn) t.SetCondition(condition) return t, nil }
[ "func", "NewCondTimer", "(", "condition", "timer", ".", "Condition", ",", "fn", "timer", ".", "Func", ")", "(", "*", "timer", ".", "Timer", ",", "error", ")", "{", "if", "condition", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrNilCondition", "\n", "}", "\n\n", "t", ":=", "NewCountTimer", "(", "time", ".", "Duration", "(", "math", ".", "MaxInt64", ")", ",", "timer", ".", "LoopForever", ",", "fn", ")", "\n", "t", ".", "SetCondition", "(", "condition", ")", "\n", "return", "t", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/timer.go#L71-L79
train
topfreegames/pitaya
timer.go
SetTimerPrecision
func SetTimerPrecision(precision time.Duration) { if precision < time.Millisecond { panic("time precision can not less than a Millisecond") } timer.Precision = precision }
go
func SetTimerPrecision(precision time.Duration) { if precision < time.Millisecond { panic("time precision can not less than a Millisecond") } timer.Precision = precision }
[ "func", "SetTimerPrecision", "(", "precision", "time", ".", "Duration", ")", "{", "if", "precision", "<", "time", ".", "Millisecond", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "timer", ".", "Precision", "=", "precision", "\n", "}" ]
// 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
[ "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" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/timer.go#L84-L89
train
topfreegames/pitaya
examples/demo/cluster/services/connector.go
NotifySessionData
func (c *Connector) NotifySessionData(ctx context.Context, data *SessionData) { s := pitaya.GetSessionFromCtx(ctx) err := s.SetData(data.Data) if err != nil { fmt.Println("got error on notify", err) } }
go
func (c *Connector) NotifySessionData(ctx context.Context, data *SessionData) { s := pitaya.GetSessionFromCtx(ctx) err := s.SetData(data.Data) if err != nil { fmt.Println("got error on notify", err) } }
[ "func", "(", "c", "*", "Connector", ")", "NotifySessionData", "(", "ctx", "context", ".", "Context", ",", "data", "*", "SessionData", ")", "{", "s", ":=", "pitaya", ".", "GetSessionFromCtx", "(", "ctx", ")", "\n", "err", ":=", "s", ".", "SetData", "(", "data", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// NotifySessionData sets the session data
[ "NotifySessionData", "sets", "the", "session", "data" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster/services/connector.go#L62-L68
train
topfreegames/pitaya
examples/demo/cluster/services/connector.go
Docs
func (c *ConnectorRemote) Docs(ctx context.Context, ddd *protos.Doc) (*protos.Doc, error) { d, err := pitaya.Documentation(true) if err != nil { return nil, err } doc, err := json.Marshal(d) if err != nil { return nil, err } return &protos.Doc{Doc: string(doc)}, nil }
go
func (c *ConnectorRemote) Docs(ctx context.Context, ddd *protos.Doc) (*protos.Doc, error) { d, err := pitaya.Documentation(true) if err != nil { return nil, err } doc, err := json.Marshal(d) if err != nil { return nil, err } return &protos.Doc{Doc: string(doc)}, nil }
[ "func", "(", "c", "*", "ConnectorRemote", ")", "Docs", "(", "ctx", "context", ".", "Context", ",", "ddd", "*", "protos", ".", "Doc", ")", "(", "*", "protos", ".", "Doc", ",", "error", ")", "{", "d", ",", "err", ":=", "pitaya", ".", "Documentation", "(", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "doc", ",", "err", ":=", "json", ".", "Marshal", "(", "d", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "protos", ".", "Doc", "{", "Doc", ":", "string", "(", "doc", ")", "}", ",", "nil", "\n", "}" ]
// Docs returns documentation
[ "Docs", "returns", "documentation" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster/services/connector.go#L79-L91
train
topfreegames/pitaya
acceptor/tcp_acceptor.go
NewTCPAcceptor
func NewTCPAcceptor(addr string, certs ...string) *TCPAcceptor { keyFile := "" certFile := "" if len(certs) != 2 && len(certs) != 0 { panic(constants.ErrInvalidCertificates) } else if len(certs) == 2 { certFile = certs[0] keyFile = certs[1] } return &TCPAcceptor{ addr: addr, connChan: make(chan net.Conn), running: false, certFile: certFile, keyFile: keyFile, } }
go
func NewTCPAcceptor(addr string, certs ...string) *TCPAcceptor { keyFile := "" certFile := "" if len(certs) != 2 && len(certs) != 0 { panic(constants.ErrInvalidCertificates) } else if len(certs) == 2 { certFile = certs[0] keyFile = certs[1] } return &TCPAcceptor{ addr: addr, connChan: make(chan net.Conn), running: false, certFile: certFile, keyFile: keyFile, } }
[ "func", "NewTCPAcceptor", "(", "addr", "string", ",", "certs", "...", "string", ")", "*", "TCPAcceptor", "{", "keyFile", ":=", "\"", "\"", "\n", "certFile", ":=", "\"", "\"", "\n", "if", "len", "(", "certs", ")", "!=", "2", "&&", "len", "(", "certs", ")", "!=", "0", "{", "panic", "(", "constants", ".", "ErrInvalidCertificates", ")", "\n", "}", "else", "if", "len", "(", "certs", ")", "==", "2", "{", "certFile", "=", "certs", "[", "0", "]", "\n", "keyFile", "=", "certs", "[", "1", "]", "\n", "}", "\n\n", "return", "&", "TCPAcceptor", "{", "addr", ":", "addr", ",", "connChan", ":", "make", "(", "chan", "net", ".", "Conn", ")", ",", "running", ":", "false", ",", "certFile", ":", "certFile", ",", "keyFile", ":", "keyFile", ",", "}", "\n", "}" ]
// NewTCPAcceptor creates a new instance of tcp acceptor
[ "NewTCPAcceptor", "creates", "a", "new", "instance", "of", "tcp", "acceptor" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/tcp_acceptor.go#L42-L59
train
topfreegames/pitaya
acceptor/tcp_acceptor.go
ListenAndServe
func (a *TCPAcceptor) ListenAndServe() { if a.hasTLSCertificates() { a.ListenAndServeTLS(a.certFile, a.keyFile) return } listener, err := net.Listen("tcp", a.addr) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } a.listener = listener a.running = true a.serve() }
go
func (a *TCPAcceptor) ListenAndServe() { if a.hasTLSCertificates() { a.ListenAndServeTLS(a.certFile, a.keyFile) return } listener, err := net.Listen("tcp", a.addr) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } a.listener = listener a.running = true a.serve() }
[ "func", "(", "a", "*", "TCPAcceptor", ")", "ListenAndServe", "(", ")", "{", "if", "a", ".", "hasTLSCertificates", "(", ")", "{", "a", ".", "ListenAndServeTLS", "(", "a", ".", "certFile", ",", "a", ".", "keyFile", ")", "\n", "return", "\n", "}", "\n\n", "listener", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "a", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "a", ".", "listener", "=", "listener", "\n", "a", ".", "running", "=", "true", "\n", "a", ".", "serve", "(", ")", "\n", "}" ]
// ListenAndServe using tcp acceptor
[ "ListenAndServe", "using", "tcp", "acceptor" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/tcp_acceptor.go#L85-L98
train
topfreegames/pitaya
acceptor/tcp_acceptor.go
ListenAndServeTLS
func (a *TCPAcceptor) ListenAndServeTLS(cert, key string) { crt, err := tls.LoadX509KeyPair(cert, key) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } tlsCfg := &tls.Config{Certificates: []tls.Certificate{crt}} listener, err := tls.Listen("tcp", a.addr, tlsCfg) a.listener = listener a.running = true a.serve() }
go
func (a *TCPAcceptor) ListenAndServeTLS(cert, key string) { crt, err := tls.LoadX509KeyPair(cert, key) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } tlsCfg := &tls.Config{Certificates: []tls.Certificate{crt}} listener, err := tls.Listen("tcp", a.addr, tlsCfg) a.listener = listener a.running = true a.serve() }
[ "func", "(", "a", "*", "TCPAcceptor", ")", "ListenAndServeTLS", "(", "cert", ",", "key", "string", ")", "{", "crt", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "cert", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "tlsCfg", ":=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "crt", "}", "}", "\n\n", "listener", ",", "err", ":=", "tls", ".", "Listen", "(", "\"", "\"", ",", "a", ".", "addr", ",", "tlsCfg", ")", "\n", "a", ".", "listener", "=", "listener", "\n", "a", ".", "running", "=", "true", "\n", "a", ".", "serve", "(", ")", "\n", "}" ]
// ListenAndServeTLS listens using tls
[ "ListenAndServeTLS", "listens", "using", "tls" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/tcp_acceptor.go#L101-L113
train
topfreegames/pitaya
acceptor/ws_acceptor.go
NewWSAcceptor
func NewWSAcceptor(addr string, certs ...string) *WSAcceptor { keyFile := "" certFile := "" if len(certs) != 2 && len(certs) != 0 { panic(constants.ErrInvalidCertificates) } else if len(certs) == 2 { certFile = certs[0] keyFile = certs[1] } w := &WSAcceptor{ addr: addr, connChan: make(chan net.Conn), certFile: certFile, keyFile: keyFile, } return w }
go
func NewWSAcceptor(addr string, certs ...string) *WSAcceptor { keyFile := "" certFile := "" if len(certs) != 2 && len(certs) != 0 { panic(constants.ErrInvalidCertificates) } else if len(certs) == 2 { certFile = certs[0] keyFile = certs[1] } w := &WSAcceptor{ addr: addr, connChan: make(chan net.Conn), certFile: certFile, keyFile: keyFile, } return w }
[ "func", "NewWSAcceptor", "(", "addr", "string", ",", "certs", "...", "string", ")", "*", "WSAcceptor", "{", "keyFile", ":=", "\"", "\"", "\n", "certFile", ":=", "\"", "\"", "\n", "if", "len", "(", "certs", ")", "!=", "2", "&&", "len", "(", "certs", ")", "!=", "0", "{", "panic", "(", "constants", ".", "ErrInvalidCertificates", ")", "\n", "}", "else", "if", "len", "(", "certs", ")", "==", "2", "{", "certFile", "=", "certs", "[", "0", "]", "\n", "keyFile", "=", "certs", "[", "1", "]", "\n", "}", "\n\n", "w", ":=", "&", "WSAcceptor", "{", "addr", ":", "addr", ",", "connChan", ":", "make", "(", "chan", "net", ".", "Conn", ")", ",", "certFile", ":", "certFile", ",", "keyFile", ":", "keyFile", ",", "}", "\n", "return", "w", "\n", "}" ]
// NewWSAcceptor returns a new instance of WSAcceptor
[ "NewWSAcceptor", "returns", "a", "new", "instance", "of", "WSAcceptor" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/ws_acceptor.go#L45-L62
train
topfreegames/pitaya
acceptor/ws_acceptor.go
ListenAndServe
func (w *WSAcceptor) ListenAndServe() { if w.hasTLSCertificates() { w.ListenAndServeTLS(w.certFile, w.keyFile) return } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } listener, err := net.Listen("tcp", w.addr) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } w.listener = listener w.serve(&upgrader) }
go
func (w *WSAcceptor) ListenAndServe() { if w.hasTLSCertificates() { w.ListenAndServeTLS(w.certFile, w.keyFile) return } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } listener, err := net.Listen("tcp", w.addr) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } w.listener = listener w.serve(&upgrader) }
[ "func", "(", "w", "*", "WSAcceptor", ")", "ListenAndServe", "(", ")", "{", "if", "w", ".", "hasTLSCertificates", "(", ")", "{", "w", ".", "ListenAndServeTLS", "(", "w", ".", "certFile", ",", "w", ".", "keyFile", ")", "\n", "return", "\n", "}", "\n\n", "var", "upgrader", "=", "websocket", ".", "Upgrader", "{", "ReadBufferSize", ":", "1024", ",", "WriteBufferSize", ":", "1024", ",", "CheckOrigin", ":", "func", "(", "r", "*", "http", ".", "Request", ")", "bool", "{", "return", "true", "\n", "}", ",", "}", "\n\n", "listener", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "w", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "w", ".", "listener", "=", "listener", "\n\n", "w", ".", "serve", "(", "&", "upgrader", ")", "\n", "}" ]
// ListenAndServe listens and serve in the specified addr
[ "ListenAndServe", "listens", "and", "serve", "in", "the", "specified", "addr" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/ws_acceptor.go#L102-L123
train
topfreegames/pitaya
acceptor/ws_acceptor.go
ListenAndServeTLS
func (w *WSAcceptor) ListenAndServeTLS(cert, key string) { var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } crt, err := tls.LoadX509KeyPair(cert, key) if err != nil { logger.Log.Fatalf("Failed to load x509: %s", err.Error()) } tlsCfg := &tls.Config{Certificates: []tls.Certificate{crt}} listener, err := tls.Listen("tcp", w.addr, tlsCfg) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } w.listener = listener w.serve(&upgrader) }
go
func (w *WSAcceptor) ListenAndServeTLS(cert, key string) { var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } crt, err := tls.LoadX509KeyPair(cert, key) if err != nil { logger.Log.Fatalf("Failed to load x509: %s", err.Error()) } tlsCfg := &tls.Config{Certificates: []tls.Certificate{crt}} listener, err := tls.Listen("tcp", w.addr, tlsCfg) if err != nil { logger.Log.Fatalf("Failed to listen: %s", err.Error()) } w.listener = listener w.serve(&upgrader) }
[ "func", "(", "w", "*", "WSAcceptor", ")", "ListenAndServeTLS", "(", "cert", ",", "key", "string", ")", "{", "var", "upgrader", "=", "websocket", ".", "Upgrader", "{", "ReadBufferSize", ":", "1024", ",", "WriteBufferSize", ":", "1024", ",", "}", "\n\n", "crt", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "cert", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "tlsCfg", ":=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "crt", "}", "}", "\n", "listener", ",", "err", ":=", "tls", ".", "Listen", "(", "\"", "\"", ",", "w", ".", "addr", ",", "tlsCfg", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "w", ".", "listener", "=", "listener", "\n", "w", ".", "serve", "(", "&", "upgrader", ")", "\n", "}" ]
// ListenAndServeTLS listens and serve in the specified addr using tls
[ "ListenAndServeTLS", "listens", "and", "serve", "in", "the", "specified", "addr", "using", "tls" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/ws_acceptor.go#L126-L144
train
topfreegames/pitaya
acceptor/ws_acceptor.go
Stop
func (w *WSAcceptor) Stop() { err := w.listener.Close() if err != nil { logger.Log.Errorf("Failed to stop: %s", err.Error()) } }
go
func (w *WSAcceptor) Stop() { err := w.listener.Close() if err != nil { logger.Log.Errorf("Failed to stop: %s", err.Error()) } }
[ "func", "(", "w", "*", "WSAcceptor", ")", "Stop", "(", ")", "{", "err", ":=", "w", ".", "listener", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// Stop stops the acceptor
[ "Stop", "stops", "the", "acceptor" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/acceptor/ws_acceptor.go#L156-L161
train
topfreegames/pitaya
client/client.go
New
func New(logLevel logrus.Level, requestTimeout ...time.Duration) *Client { l := logrus.New() l.Formatter = &logrus.TextFormatter{} l.SetLevel(logLevel) logger.Log = l reqTimeout := 5 * time.Second if len(requestTimeout) > 0 { reqTimeout = requestTimeout[0] } return &Client{ Connected: false, packetEncoder: codec.NewPomeloPacketEncoder(), packetDecoder: codec.NewPomeloPacketDecoder(), packetChan: make(chan *packet.Packet, 10), pendingRequests: make(map[uint]*pendingRequest), requestTimeout: reqTimeout, // 30 here is the limit of inflight messages // TODO this should probably be configurable pendingChan: make(chan bool, 30), messageEncoder: message.NewMessagesEncoder(true), } }
go
func New(logLevel logrus.Level, requestTimeout ...time.Duration) *Client { l := logrus.New() l.Formatter = &logrus.TextFormatter{} l.SetLevel(logLevel) logger.Log = l reqTimeout := 5 * time.Second if len(requestTimeout) > 0 { reqTimeout = requestTimeout[0] } return &Client{ Connected: false, packetEncoder: codec.NewPomeloPacketEncoder(), packetDecoder: codec.NewPomeloPacketDecoder(), packetChan: make(chan *packet.Packet, 10), pendingRequests: make(map[uint]*pendingRequest), requestTimeout: reqTimeout, // 30 here is the limit of inflight messages // TODO this should probably be configurable pendingChan: make(chan bool, 30), messageEncoder: message.NewMessagesEncoder(true), } }
[ "func", "New", "(", "logLevel", "logrus", ".", "Level", ",", "requestTimeout", "...", "time", ".", "Duration", ")", "*", "Client", "{", "l", ":=", "logrus", ".", "New", "(", ")", "\n", "l", ".", "Formatter", "=", "&", "logrus", ".", "TextFormatter", "{", "}", "\n", "l", ".", "SetLevel", "(", "logLevel", ")", "\n\n", "logger", ".", "Log", "=", "l", "\n\n", "reqTimeout", ":=", "5", "*", "time", ".", "Second", "\n", "if", "len", "(", "requestTimeout", ")", ">", "0", "{", "reqTimeout", "=", "requestTimeout", "[", "0", "]", "\n", "}", "\n\n", "return", "&", "Client", "{", "Connected", ":", "false", ",", "packetEncoder", ":", "codec", ".", "NewPomeloPacketEncoder", "(", ")", ",", "packetDecoder", ":", "codec", ".", "NewPomeloPacketDecoder", "(", ")", ",", "packetChan", ":", "make", "(", "chan", "*", "packet", ".", "Packet", ",", "10", ")", ",", "pendingRequests", ":", "make", "(", "map", "[", "uint", "]", "*", "pendingRequest", ")", ",", "requestTimeout", ":", "reqTimeout", ",", "// 30 here is the limit of inflight messages", "// TODO this should probably be configurable", "pendingChan", ":", "make", "(", "chan", "bool", ",", "30", ")", ",", "messageEncoder", ":", "message", ".", "NewMessagesEncoder", "(", "true", ")", ",", "}", "\n", "}" ]
// New returns a new client
[ "New", "returns", "a", "new", "client" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/client/client.go#L104-L128
train
topfreegames/pitaya
client/client.go
pendingRequestsReaper
func (c *Client) pendingRequestsReaper() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: toDelete := make([]*pendingRequest, 0) c.pendingReqMutex.Lock() for _, v := range c.pendingRequests { if time.Now().Sub(v.sentAt) > c.requestTimeout { toDelete = append(toDelete, v) } } for _, pendingReq := range toDelete { err := pitaya.Error(errors.New("request timeout"), "PIT-504") errMarshalled, _ := json.Marshal(err) // send a timeout to incoming msg chan m := &message.Message{ Type: message.Response, ID: pendingReq.msg.ID, Route: pendingReq.msg.Route, Data: errMarshalled, Err: true, } delete(c.pendingRequests, pendingReq.msg.ID) <-c.pendingChan c.IncomingMsgChan <- m } c.pendingReqMutex.Unlock() case <-c.closeChan: return } } }
go
func (c *Client) pendingRequestsReaper() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: toDelete := make([]*pendingRequest, 0) c.pendingReqMutex.Lock() for _, v := range c.pendingRequests { if time.Now().Sub(v.sentAt) > c.requestTimeout { toDelete = append(toDelete, v) } } for _, pendingReq := range toDelete { err := pitaya.Error(errors.New("request timeout"), "PIT-504") errMarshalled, _ := json.Marshal(err) // send a timeout to incoming msg chan m := &message.Message{ Type: message.Response, ID: pendingReq.msg.ID, Route: pendingReq.msg.Route, Data: errMarshalled, Err: true, } delete(c.pendingRequests, pendingReq.msg.ID) <-c.pendingChan c.IncomingMsgChan <- m } c.pendingReqMutex.Unlock() case <-c.closeChan: return } } }
[ "func", "(", "c", "*", "Client", ")", "pendingRequestsReaper", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "1", "*", "time", ".", "Second", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "toDelete", ":=", "make", "(", "[", "]", "*", "pendingRequest", ",", "0", ")", "\n", "c", ".", "pendingReqMutex", ".", "Lock", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "c", ".", "pendingRequests", "{", "if", "time", ".", "Now", "(", ")", ".", "Sub", "(", "v", ".", "sentAt", ")", ">", "c", ".", "requestTimeout", "{", "toDelete", "=", "append", "(", "toDelete", ",", "v", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "pendingReq", ":=", "range", "toDelete", "{", "err", ":=", "pitaya", ".", "Error", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "errMarshalled", ",", "_", ":=", "json", ".", "Marshal", "(", "err", ")", "\n", "// send a timeout to incoming msg chan", "m", ":=", "&", "message", ".", "Message", "{", "Type", ":", "message", ".", "Response", ",", "ID", ":", "pendingReq", ".", "msg", ".", "ID", ",", "Route", ":", "pendingReq", ".", "msg", ".", "Route", ",", "Data", ":", "errMarshalled", ",", "Err", ":", "true", ",", "}", "\n", "delete", "(", "c", ".", "pendingRequests", ",", "pendingReq", ".", "msg", ".", "ID", ")", "\n", "<-", "c", ".", "pendingChan", "\n", "c", ".", "IncomingMsgChan", "<-", "m", "\n", "}", "\n", "c", ".", "pendingReqMutex", ".", "Unlock", "(", ")", "\n", "case", "<-", "c", ".", "closeChan", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// pendingRequestsReaper delete timedout requests
[ "pendingRequestsReaper", "delete", "timedout", "requests" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/client/client.go#L189-L222
train
topfreegames/pitaya
client/client.go
Disconnect
func (c *Client) Disconnect() { if c.Connected { c.Connected = false close(c.closeChan) c.conn.Close() } }
go
func (c *Client) Disconnect() { if c.Connected { c.Connected = false close(c.closeChan) c.conn.Close() } }
[ "func", "(", "c", "*", "Client", ")", "Disconnect", "(", ")", "{", "if", "c", ".", "Connected", "{", "c", ".", "Connected", "=", "false", "\n", "close", "(", "c", ".", "closeChan", ")", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Disconnect disconnects the client
[ "Disconnect", "disconnects", "the", "client" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/client/client.go#L317-L323
train
topfreegames/pitaya
client/client.go
sendMsg
func (c *Client) sendMsg(msgType message.Type, route string, data []byte) (uint, error) { // TODO mount msg and encode m := message.Message{ Type: msgType, ID: uint(atomic.AddUint32(&c.nextID, 1)), Route: route, Data: data, Err: false, } p, err := c.buildPacket(m) if msgType == message.Request { c.pendingChan <- true c.pendingReqMutex.Lock() if _, ok := c.pendingRequests[m.ID]; !ok { c.pendingRequests[m.ID] = &pendingRequest{ msg: &m, sentAt: time.Now(), } } c.pendingReqMutex.Unlock() } if err != nil { return m.ID, err } _, err = c.conn.Write(p) return m.ID, err }
go
func (c *Client) sendMsg(msgType message.Type, route string, data []byte) (uint, error) { // TODO mount msg and encode m := message.Message{ Type: msgType, ID: uint(atomic.AddUint32(&c.nextID, 1)), Route: route, Data: data, Err: false, } p, err := c.buildPacket(m) if msgType == message.Request { c.pendingChan <- true c.pendingReqMutex.Lock() if _, ok := c.pendingRequests[m.ID]; !ok { c.pendingRequests[m.ID] = &pendingRequest{ msg: &m, sentAt: time.Now(), } } c.pendingReqMutex.Unlock() } if err != nil { return m.ID, err } _, err = c.conn.Write(p) return m.ID, err }
[ "func", "(", "c", "*", "Client", ")", "sendMsg", "(", "msgType", "message", ".", "Type", ",", "route", "string", ",", "data", "[", "]", "byte", ")", "(", "uint", ",", "error", ")", "{", "// TODO mount msg and encode", "m", ":=", "message", ".", "Message", "{", "Type", ":", "msgType", ",", "ID", ":", "uint", "(", "atomic", ".", "AddUint32", "(", "&", "c", ".", "nextID", ",", "1", ")", ")", ",", "Route", ":", "route", ",", "Data", ":", "data", ",", "Err", ":", "false", ",", "}", "\n", "p", ",", "err", ":=", "c", ".", "buildPacket", "(", "m", ")", "\n", "if", "msgType", "==", "message", ".", "Request", "{", "c", ".", "pendingChan", "<-", "true", "\n", "c", ".", "pendingReqMutex", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "c", ".", "pendingRequests", "[", "m", ".", "ID", "]", ";", "!", "ok", "{", "c", ".", "pendingRequests", "[", "m", ".", "ID", "]", "=", "&", "pendingRequest", "{", "msg", ":", "&", "m", ",", "sentAt", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}", "\n", "c", ".", "pendingReqMutex", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "m", ".", "ID", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "conn", ".", "Write", "(", "p", ")", "\n", "return", "m", ".", "ID", ",", "err", "\n", "}" ]
// sendMsg sends the request to the server
[ "sendMsg", "sends", "the", "request", "to", "the", "server" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/client/client.go#L400-L427
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
NewMockServiceDiscovery
func NewMockServiceDiscovery(ctrl *gomock.Controller) *MockServiceDiscovery { mock := &MockServiceDiscovery{ctrl: ctrl} mock.recorder = &MockServiceDiscoveryMockRecorder{mock} return mock }
go
func NewMockServiceDiscovery(ctrl *gomock.Controller) *MockServiceDiscovery { mock := &MockServiceDiscovery{ctrl: ctrl} mock.recorder = &MockServiceDiscoveryMockRecorder{mock} return mock }
[ "func", "NewMockServiceDiscovery", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockServiceDiscovery", "{", "mock", ":=", "&", "MockServiceDiscovery", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockServiceDiscoveryMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockServiceDiscovery creates a new mock instance
[ "NewMockServiceDiscovery", "creates", "a", "new", "mock", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L25-L29
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
GetServersByType
func (m *MockServiceDiscovery) GetServersByType(serverType string) (map[string]*cluster.Server, error) { ret := m.ctrl.Call(m, "GetServersByType", serverType) ret0, _ := ret[0].(map[string]*cluster.Server) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockServiceDiscovery) GetServersByType(serverType string) (map[string]*cluster.Server, error) { ret := m.ctrl.Call(m, "GetServersByType", serverType) ret0, _ := ret[0].(map[string]*cluster.Server) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockServiceDiscovery", ")", "GetServersByType", "(", "serverType", "string", ")", "(", "map", "[", "string", "]", "*", "cluster", ".", "Server", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "serverType", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "map", "[", "string", "]", "*", "cluster", ".", "Server", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// GetServersByType mocks base method
[ "GetServersByType", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L37-L42
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
GetServersByType
func (mr *MockServiceDiscoveryMockRecorder) GetServersByType(serverType interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServersByType", reflect.TypeOf((*MockServiceDiscovery)(nil).GetServersByType), serverType) }
go
func (mr *MockServiceDiscoveryMockRecorder) GetServersByType(serverType interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServersByType", reflect.TypeOf((*MockServiceDiscovery)(nil).GetServersByType), serverType) }
[ "func", "(", "mr", "*", "MockServiceDiscoveryMockRecorder", ")", "GetServersByType", "(", "serverType", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockServiceDiscovery", ")", "(", "nil", ")", ".", "GetServersByType", ")", ",", "serverType", ")", "\n", "}" ]
// GetServersByType indicates an expected call of GetServersByType
[ "GetServersByType", "indicates", "an", "expected", "call", "of", "GetServersByType" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L45-L47
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
GetServer
func (m *MockServiceDiscovery) GetServer(id string) (*cluster.Server, error) { ret := m.ctrl.Call(m, "GetServer", id) ret0, _ := ret[0].(*cluster.Server) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockServiceDiscovery) GetServer(id string) (*cluster.Server, error) { ret := m.ctrl.Call(m, "GetServer", id) ret0, _ := ret[0].(*cluster.Server) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockServiceDiscovery", ")", "GetServer", "(", "id", "string", ")", "(", "*", "cluster", ".", "Server", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "id", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "cluster", ".", "Server", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// GetServer mocks base method
[ "GetServer", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L50-L55
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
GetServer
func (mr *MockServiceDiscoveryMockRecorder) GetServer(id interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServer", reflect.TypeOf((*MockServiceDiscovery)(nil).GetServer), id) }
go
func (mr *MockServiceDiscoveryMockRecorder) GetServer(id interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServer", reflect.TypeOf((*MockServiceDiscovery)(nil).GetServer), id) }
[ "func", "(", "mr", "*", "MockServiceDiscoveryMockRecorder", ")", "GetServer", "(", "id", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockServiceDiscovery", ")", "(", "nil", ")", ".", "GetServer", ")", ",", "id", ")", "\n", "}" ]
// GetServer indicates an expected call of GetServer
[ "GetServer", "indicates", "an", "expected", "call", "of", "GetServer" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L58-L60
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
GetServers
func (m *MockServiceDiscovery) GetServers() []*cluster.Server { ret := m.ctrl.Call(m, "GetServers") ret0, _ := ret[0].([]*cluster.Server) return ret0 }
go
func (m *MockServiceDiscovery) GetServers() []*cluster.Server { ret := m.ctrl.Call(m, "GetServers") ret0, _ := ret[0].([]*cluster.Server) return ret0 }
[ "func", "(", "m", "*", "MockServiceDiscovery", ")", "GetServers", "(", ")", "[", "]", "*", "cluster", ".", "Server", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "[", "]", "*", "cluster", ".", "Server", ")", "\n", "return", "ret0", "\n", "}" ]
// GetServers mocks base method
[ "GetServers", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L63-L67
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
AddListener
func (m *MockServiceDiscovery) AddListener(listener cluster.SDListener) { m.ctrl.Call(m, "AddListener", listener) }
go
func (m *MockServiceDiscovery) AddListener(listener cluster.SDListener) { m.ctrl.Call(m, "AddListener", listener) }
[ "func", "(", "m", "*", "MockServiceDiscovery", ")", "AddListener", "(", "listener", "cluster", ".", "SDListener", ")", "{", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "listener", ")", "\n", "}" ]
// AddListener mocks base method
[ "AddListener", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L87-L89
train
topfreegames/pitaya
cluster/mocks/service_discovery.go
AddListener
func (mr *MockServiceDiscoveryMockRecorder) AddListener(listener interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddListener", reflect.TypeOf((*MockServiceDiscovery)(nil).AddListener), listener) }
go
func (mr *MockServiceDiscoveryMockRecorder) AddListener(listener interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddListener", reflect.TypeOf((*MockServiceDiscovery)(nil).AddListener), listener) }
[ "func", "(", "mr", "*", "MockServiceDiscoveryMockRecorder", ")", "AddListener", "(", "listener", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockServiceDiscovery", ")", "(", "nil", ")", ".", "AddListener", ")", ",", "listener", ")", "\n", "}" ]
// AddListener indicates an expected call of AddListener
[ "AddListener", "indicates", "an", "expected", "call", "of", "AddListener" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/mocks/service_discovery.go#L92-L94
train
topfreegames/pitaya
conn/message/mocks/message_encoder.go
NewMockEncoder
func NewMockEncoder(ctrl *gomock.Controller) *MockEncoder { mock := &MockEncoder{ctrl: ctrl} mock.recorder = &MockEncoderMockRecorder{mock} return mock }
go
func NewMockEncoder(ctrl *gomock.Controller) *MockEncoder { mock := &MockEncoder{ctrl: ctrl} mock.recorder = &MockEncoderMockRecorder{mock} return mock }
[ "func", "NewMockEncoder", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockEncoder", "{", "mock", ":=", "&", "MockEncoder", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockEncoderMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockEncoder creates a new mock instance
[ "NewMockEncoder", "creates", "a", "new", "mock", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/mocks/message_encoder.go#L25-L29
train
topfreegames/pitaya
conn/message/mocks/message_encoder.go
IsCompressionEnabled
func (m *MockEncoder) IsCompressionEnabled() bool { ret := m.ctrl.Call(m, "IsCompressionEnabled") ret0, _ := ret[0].(bool) return ret0 }
go
func (m *MockEncoder) IsCompressionEnabled() bool { ret := m.ctrl.Call(m, "IsCompressionEnabled") ret0, _ := ret[0].(bool) return ret0 }
[ "func", "(", "m", "*", "MockEncoder", ")", "IsCompressionEnabled", "(", ")", "bool", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "bool", ")", "\n", "return", "ret0", "\n", "}" ]
// IsCompressionEnabled mocks base method
[ "IsCompressionEnabled", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/mocks/message_encoder.go#L37-L41
train
topfreegames/pitaya
conn/message/mocks/message_encoder.go
IsCompressionEnabled
func (mr *MockEncoderMockRecorder) IsCompressionEnabled() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsCompressionEnabled", reflect.TypeOf((*MockEncoder)(nil).IsCompressionEnabled)) }
go
func (mr *MockEncoderMockRecorder) IsCompressionEnabled() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsCompressionEnabled", reflect.TypeOf((*MockEncoder)(nil).IsCompressionEnabled)) }
[ "func", "(", "mr", "*", "MockEncoderMockRecorder", ")", "IsCompressionEnabled", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockEncoder", ")", "(", "nil", ")", ".", "IsCompressionEnabled", ")", ")", "\n", "}" ]
// IsCompressionEnabled indicates an expected call of IsCompressionEnabled
[ "IsCompressionEnabled", "indicates", "an", "expected", "call", "of", "IsCompressionEnabled" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/mocks/message_encoder.go#L44-L46
train
topfreegames/pitaya
examples/demo/cluster_grpc/services/connector.go
SendPushToUser
func (c *Connector) SendPushToUser(ctx context.Context, msg *UserMessage) (*Response, error) { _, err := pitaya.SendPushToUsers("onMessage", msg, []string{"2"}, "connector") if err != nil { return nil, err } return &Response{ Code: 200, Msg: "boa", }, nil }
go
func (c *Connector) SendPushToUser(ctx context.Context, msg *UserMessage) (*Response, error) { _, err := pitaya.SendPushToUsers("onMessage", msg, []string{"2"}, "connector") if err != nil { return nil, err } return &Response{ Code: 200, Msg: "boa", }, nil }
[ "func", "(", "c", "*", "Connector", ")", "SendPushToUser", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "UserMessage", ")", "(", "*", "Response", ",", "error", ")", "{", "_", ",", "err", ":=", "pitaya", ".", "SendPushToUsers", "(", "\"", "\"", ",", "msg", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Response", "{", "Code", ":", "200", ",", "Msg", ":", "\"", "\"", ",", "}", ",", "nil", "\n", "}" ]
// SendPushToUser sends a push to a user
[ "SendPushToUser", "sends", "a", "push", "to", "a", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster_grpc/services/connector.go#L70-L79
train
topfreegames/pitaya
examples/demo/cluster_grpc/services/connector.go
RemoteFunc
func (c *ConnectorRemote) RemoteFunc(ctx context.Context, msg *protos.RPCMsg) (*protos.RPCRes, error) { fmt.Printf("received a remote call with this message: %s\n", msg) return &protos.RPCRes{ Msg: fmt.Sprintf("received msg: %s", msg.GetMsg()), }, nil }
go
func (c *ConnectorRemote) RemoteFunc(ctx context.Context, msg *protos.RPCMsg) (*protos.RPCRes, error) { fmt.Printf("received a remote call with this message: %s\n", msg) return &protos.RPCRes{ Msg: fmt.Sprintf("received msg: %s", msg.GetMsg()), }, nil }
[ "func", "(", "c", "*", "ConnectorRemote", ")", "RemoteFunc", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "protos", ".", "RPCMsg", ")", "(", "*", "protos", ".", "RPCRes", ",", "error", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "msg", ")", "\n", "return", "&", "protos", ".", "RPCRes", "{", "Msg", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "GetMsg", "(", ")", ")", ",", "}", ",", "nil", "\n", "}" ]
// RemoteFunc is a function that will be called remotely
[ "RemoteFunc", "is", "a", "function", "that", "will", "be", "called", "remotely" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster_grpc/services/connector.go#L82-L87
train
topfreegames/pitaya
helpers/helpers.go
GetFreePort
func GetFreePort(t testing.TB) int { t.Helper() addr, err := net.ResolveTCPAddr("tcp", "localhost:0") if err != nil { t.Fatal(err) } l, err := net.ListenTCP("tcp", addr) if err != nil { t.Fatal(err) } defer l.Close() return l.Addr().(*net.TCPAddr).Port }
go
func GetFreePort(t testing.TB) int { t.Helper() addr, err := net.ResolveTCPAddr("tcp", "localhost:0") if err != nil { t.Fatal(err) } l, err := net.ListenTCP("tcp", addr) if err != nil { t.Fatal(err) } defer l.Close() return l.Addr().(*net.TCPAddr).Port }
[ "func", "GetFreePort", "(", "t", "testing", ".", "TB", ")", "int", "{", "t", ".", "Helper", "(", ")", "\n", "addr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "l", ",", "err", ":=", "net", ".", "ListenTCP", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "defer", "l", ".", "Close", "(", ")", "\n", "return", "l", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", ".", "Port", "\n", "}" ]
// GetFreePort returns a free port
[ "GetFreePort", "returns", "a", "free", "port" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L24-L37
train
topfreegames/pitaya
helpers/helpers.go
GetMapKeys
func GetMapKeys(t *testing.T, m interface{}) []string { if reflect.ValueOf(m).Kind() != reflect.Map { t.Fatal(errors.New("GetMapKeys should receive a map")) } if reflect.TypeOf(m).Key() != reflect.TypeOf("bla") { t.Fatal(errors.New("GetMapKeys should receive a map with string keys")) } t.Helper() res := make([]string, 0) for _, k := range reflect.ValueOf(m).MapKeys() { res = append(res, k.String()) } return res }
go
func GetMapKeys(t *testing.T, m interface{}) []string { if reflect.ValueOf(m).Kind() != reflect.Map { t.Fatal(errors.New("GetMapKeys should receive a map")) } if reflect.TypeOf(m).Key() != reflect.TypeOf("bla") { t.Fatal(errors.New("GetMapKeys should receive a map with string keys")) } t.Helper() res := make([]string, 0) for _, k := range reflect.ValueOf(m).MapKeys() { res = append(res, k.String()) } return res }
[ "func", "GetMapKeys", "(", "t", "*", "testing", ".", "T", ",", "m", "interface", "{", "}", ")", "[", "]", "string", "{", "if", "reflect", ".", "ValueOf", "(", "m", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Map", "{", "t", ".", "Fatal", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "reflect", ".", "TypeOf", "(", "m", ")", ".", "Key", "(", ")", "!=", "reflect", ".", "TypeOf", "(", "\"", "\"", ")", "{", "t", ".", "Fatal", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "t", ".", "Helper", "(", ")", "\n", "res", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "k", ":=", "range", "reflect", ".", "ValueOf", "(", "m", ")", ".", "MapKeys", "(", ")", "{", "res", "=", "append", "(", "res", ",", "k", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// GetMapKeys returns a string slice with the map keys
[ "GetMapKeys", "returns", "a", "string", "slice", "with", "the", "map", "keys" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L40-L53
train
topfreegames/pitaya
helpers/helpers.go
WriteFile
func WriteFile(t *testing.T, filepath string, bytes []byte) { t.Helper() if err := ioutil.WriteFile(filepath, bytes, 0644); err != nil { t.Fatalf("failed writing file: %s", err) } }
go
func WriteFile(t *testing.T, filepath string, bytes []byte) { t.Helper() if err := ioutil.WriteFile(filepath, bytes, 0644); err != nil { t.Fatalf("failed writing file: %s", err) } }
[ "func", "WriteFile", "(", "t", "*", "testing", ".", "T", ",", "filepath", "string", ",", "bytes", "[", "]", "byte", ")", "{", "t", ".", "Helper", "(", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ",", "bytes", ",", "0644", ")", ";", "err", "!=", "nil", "{", "t", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// WriteFile test helper
[ "WriteFile", "test", "helper" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L73-L78
train
topfreegames/pitaya
helpers/helpers.go
ReadFile
func ReadFile(t *testing.T, filepath string) []byte { t.Helper() b, err := ioutil.ReadFile(filepath) if err != nil { t.Fatalf("failed reading file: %s", err) } return b }
go
func ReadFile(t *testing.T, filepath string) []byte { t.Helper() b, err := ioutil.ReadFile(filepath) if err != nil { t.Fatalf("failed reading file: %s", err) } return b }
[ "func", "ReadFile", "(", "t", "*", "testing", ".", "T", ",", "filepath", "string", ")", "[", "]", "byte", "{", "t", ".", "Helper", "(", ")", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// ReadFile test helper
[ "ReadFile", "test", "helper" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L81-L88
train
topfreegames/pitaya
helpers/helpers.go
StartProcess
func StartProcess(t testing.TB, program string, args ...string) *exec.Cmd { t.Helper() return exec.Command(program, args...) }
go
func StartProcess(t testing.TB, program string, args ...string) *exec.Cmd { t.Helper() return exec.Command(program, args...) }
[ "func", "StartProcess", "(", "t", "testing", ".", "TB", ",", "program", "string", ",", "args", "...", "string", ")", "*", "exec", ".", "Cmd", "{", "t", ".", "Helper", "(", ")", "\n", "return", "exec", ".", "Command", "(", "program", ",", "args", "...", ")", "\n", "}" ]
// StartProcess starts a process
[ "StartProcess", "starts", "a", "process" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L91-L94
train
topfreegames/pitaya
helpers/helpers.go
StartServer
func StartServer(t testing.TB, frontend bool, debug bool, svType string, port int, sdPrefix string, grpc bool) func() { grpcPort := GetFreePort(t) promPort := GetFreePort(t) var useGRPC string if grpc { useGRPC = "true" } else { useGRPC = "false" } t.Helper() args := []string{ "-type", svType, "-port", strconv.Itoa(port), fmt.Sprintf("-frontend=%s", strconv.FormatBool(frontend)), "-sdprefix", sdPrefix, "-grpcport", fmt.Sprintf("%d", grpcPort), fmt.Sprintf("-grpc=%s", useGRPC), } if debug { args = append(args, "-debug") } cmd := StartProcess( t, "../examples/testing/server", args..., ) // always use a random port for prometheus, for avoiding e2e conflicts cmd.Env = []string{fmt.Sprintf("PITAYA_METRICS_PROMETHEUS_PORT=%d", promPort)} outPipe, err := cmd.StderrPipe() if err != nil { t.Fatal(err) } err = cmd.Start() if err != nil { t.Fatal(err) } waitForServerToBeReady(t, bufio.NewReader(outPipe)) return func() { err := cmd.Process.Kill() if err != nil { t.Fatal(err) } } }
go
func StartServer(t testing.TB, frontend bool, debug bool, svType string, port int, sdPrefix string, grpc bool) func() { grpcPort := GetFreePort(t) promPort := GetFreePort(t) var useGRPC string if grpc { useGRPC = "true" } else { useGRPC = "false" } t.Helper() args := []string{ "-type", svType, "-port", strconv.Itoa(port), fmt.Sprintf("-frontend=%s", strconv.FormatBool(frontend)), "-sdprefix", sdPrefix, "-grpcport", fmt.Sprintf("%d", grpcPort), fmt.Sprintf("-grpc=%s", useGRPC), } if debug { args = append(args, "-debug") } cmd := StartProcess( t, "../examples/testing/server", args..., ) // always use a random port for prometheus, for avoiding e2e conflicts cmd.Env = []string{fmt.Sprintf("PITAYA_METRICS_PROMETHEUS_PORT=%d", promPort)} outPipe, err := cmd.StderrPipe() if err != nil { t.Fatal(err) } err = cmd.Start() if err != nil { t.Fatal(err) } waitForServerToBeReady(t, bufio.NewReader(outPipe)) return func() { err := cmd.Process.Kill() if err != nil { t.Fatal(err) } } }
[ "func", "StartServer", "(", "t", "testing", ".", "TB", ",", "frontend", "bool", ",", "debug", "bool", ",", "svType", "string", ",", "port", "int", ",", "sdPrefix", "string", ",", "grpc", "bool", ")", "func", "(", ")", "{", "grpcPort", ":=", "GetFreePort", "(", "t", ")", "\n", "promPort", ":=", "GetFreePort", "(", "t", ")", "\n", "var", "useGRPC", "string", "\n", "if", "grpc", "{", "useGRPC", "=", "\"", "\"", "\n", "}", "else", "{", "useGRPC", "=", "\"", "\"", "\n", "}", "\n", "t", ".", "Helper", "(", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "svType", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "port", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "frontend", ")", ")", ",", "\"", "\"", ",", "sdPrefix", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "grpcPort", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "useGRPC", ")", ",", "}", "\n", "if", "debug", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "}", "\n", "cmd", ":=", "StartProcess", "(", "t", ",", "\"", "\"", ",", "args", "...", ",", ")", "\n", "// always use a random port for prometheus, for avoiding e2e conflicts", "cmd", ".", "Env", "=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "promPort", ")", "}", "\n\n", "outPipe", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "cmd", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "waitForServerToBeReady", "(", "t", ",", "bufio", ".", "NewReader", "(", "outPipe", ")", ")", "\n\n", "return", "func", "(", ")", "{", "err", ":=", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// StartServer starts a server
[ "StartServer", "starts", "a", "server" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L108-L157
train
topfreegames/pitaya
helpers/helpers.go
FixtureGoldenFileName
func FixtureGoldenFileName(t *testing.T, name string) string { t.Helper() return filepath.Join("fixtures", name+".golden") }
go
func FixtureGoldenFileName(t *testing.T, name string) string { t.Helper() return filepath.Join("fixtures", name+".golden") }
[ "func", "FixtureGoldenFileName", "(", "t", "*", "testing", ".", "T", ",", "name", "string", ")", "string", "{", "t", ".", "Helper", "(", ")", "\n", "return", "filepath", ".", "Join", "(", "\"", "\"", ",", "name", "+", "\"", "\"", ")", "\n", "}" ]
// FixtureGoldenFileName returns the golden file name on fixtures path
[ "FixtureGoldenFileName", "returns", "the", "golden", "file", "name", "on", "fixtures", "path" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L160-L163
train
topfreegames/pitaya
helpers/helpers.go
ShouldEventuallyReceive
func ShouldEventuallyReceive(t testing.TB, c interface{}, timeouts ...time.Duration) interface{} { t.Helper() if !isChan(c) { t.Fatal("ShouldEventuallyReceive c argument should be a channel") } v := reflect.ValueOf(c) timeout := time.After(500 * time.Millisecond) if len(timeouts) > 0 { timeout = time.After(timeouts[0]) } recvChan := make(chan reflect.Value) go func() { v, ok := v.Recv() if ok { recvChan <- v } }() select { case <-timeout: t.Fatal(errors.New("timed out waiting for channel to receive")) case a := <-recvChan: return a.Interface() } return nil }
go
func ShouldEventuallyReceive(t testing.TB, c interface{}, timeouts ...time.Duration) interface{} { t.Helper() if !isChan(c) { t.Fatal("ShouldEventuallyReceive c argument should be a channel") } v := reflect.ValueOf(c) timeout := time.After(500 * time.Millisecond) if len(timeouts) > 0 { timeout = time.After(timeouts[0]) } recvChan := make(chan reflect.Value) go func() { v, ok := v.Recv() if ok { recvChan <- v } }() select { case <-timeout: t.Fatal(errors.New("timed out waiting for channel to receive")) case a := <-recvChan: return a.Interface() } return nil }
[ "func", "ShouldEventuallyReceive", "(", "t", "testing", ".", "TB", ",", "c", "interface", "{", "}", ",", "timeouts", "...", "time", ".", "Duration", ")", "interface", "{", "}", "{", "t", ".", "Helper", "(", ")", "\n", "if", "!", "isChan", "(", "c", ")", "{", "t", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "c", ")", "\n\n", "timeout", ":=", "time", ".", "After", "(", "500", "*", "time", ".", "Millisecond", ")", "\n\n", "if", "len", "(", "timeouts", ")", ">", "0", "{", "timeout", "=", "time", ".", "After", "(", "timeouts", "[", "0", "]", ")", "\n", "}", "\n\n", "recvChan", ":=", "make", "(", "chan", "reflect", ".", "Value", ")", "\n\n", "go", "func", "(", ")", "{", "v", ",", "ok", ":=", "v", ".", "Recv", "(", ")", "\n", "if", "ok", "{", "recvChan", "<-", "v", "\n", "}", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "timeout", ":", "t", ".", "Fatal", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "case", "a", ":=", "<-", "recvChan", ":", "return", "a", ".", "Interface", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ShouldEventuallyReceive should asserts that eventually channel c receives a value
[ "ShouldEventuallyReceive", "should", "asserts", "that", "eventually", "channel", "c", "receives", "a", "value" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/helpers/helpers.go#L196-L226
train
topfreegames/pitaya
examples/demo/worker/services/room.go
CallLog
func (*Room) CallLog(ctx context.Context, arg *protos.Arg) (*protos.Response, error) { route := "metagame.metagame.logremote" reply := &protos.Response{} jid, err := pitaya.ReliableRPC(route, nil, reply, arg) if err != nil { logger.Log.Infof("failed to enqueue rpc: %q", err) return nil, err } logger.Log.Infof("enqueue rpc job: %d", jid) return &protos.Response{Code: 200, Msg: "ok"}, nil }
go
func (*Room) CallLog(ctx context.Context, arg *protos.Arg) (*protos.Response, error) { route := "metagame.metagame.logremote" reply := &protos.Response{} jid, err := pitaya.ReliableRPC(route, nil, reply, arg) if err != nil { logger.Log.Infof("failed to enqueue rpc: %q", err) return nil, err } logger.Log.Infof("enqueue rpc job: %d", jid) return &protos.Response{Code: 200, Msg: "ok"}, nil }
[ "func", "(", "*", "Room", ")", "CallLog", "(", "ctx", "context", ".", "Context", ",", "arg", "*", "protos", ".", "Arg", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "route", ":=", "\"", "\"", "\n", "reply", ":=", "&", "protos", ".", "Response", "{", "}", "\n", "jid", ",", "err", ":=", "pitaya", ".", "ReliableRPC", "(", "route", ",", "nil", ",", "reply", ",", "arg", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "logger", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "jid", ")", "\n", "return", "&", "protos", ".", "Response", "{", "Code", ":", "200", ",", "Msg", ":", "\"", "\"", "}", ",", "nil", "\n", "}" ]
// CallLog makes ReliableRPC to metagame LogRemote
[ "CallLog", "makes", "ReliableRPC", "to", "metagame", "LogRemote" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/worker/services/room.go#L18-L29
train
topfreegames/pitaya
serialize/mocks/serializer.go
NewMockSerializer
func NewMockSerializer(ctrl *gomock.Controller) *MockSerializer { mock := &MockSerializer{ctrl: ctrl} mock.recorder = &MockSerializerMockRecorder{mock} return mock }
go
func NewMockSerializer(ctrl *gomock.Controller) *MockSerializer { mock := &MockSerializer{ctrl: ctrl} mock.recorder = &MockSerializerMockRecorder{mock} return mock }
[ "func", "NewMockSerializer", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockSerializer", "{", "mock", ":=", "&", "MockSerializer", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockSerializerMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockSerializer creates a new mock instance
[ "NewMockSerializer", "creates", "a", "new", "mock", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/serialize/mocks/serializer.go#L24-L28
train
topfreegames/pitaya
serialize/mocks/serializer.go
GetName
func (mr *MockSerializerMockRecorder) GetName() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetName", reflect.TypeOf((*MockSerializer)(nil).GetName)) }
go
func (mr *MockSerializerMockRecorder) GetName() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetName", reflect.TypeOf((*MockSerializer)(nil).GetName)) }
[ "func", "(", "mr", "*", "MockSerializerMockRecorder", ")", "GetName", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockSerializer", ")", "(", "nil", ")", ".", "GetName", ")", ")", "\n", "}" ]
// GetName indicates an expected call of GetName
[ "GetName", "indicates", "an", "expected", "call", "of", "GetName" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/serialize/mocks/serializer.go#L43-L45
train
topfreegames/pitaya
serialize/mocks/serializer.go
Marshal
func (m *MockSerializer) Marshal(arg0 interface{}) ([]byte, error) { ret := m.ctrl.Call(m, "Marshal", arg0) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockSerializer) Marshal(arg0 interface{}) ([]byte, error) { ret := m.ctrl.Call(m, "Marshal", arg0) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockSerializer", ")", "Marshal", "(", "arg0", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "[", "]", "byte", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// Marshal mocks base method
[ "Marshal", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/serialize/mocks/serializer.go#L48-L53
train
topfreegames/pitaya
serialize/mocks/serializer.go
Unmarshal
func (m *MockSerializer) Unmarshal(arg0 []byte, arg1 interface{}) error { ret := m.ctrl.Call(m, "Unmarshal", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockSerializer) Unmarshal(arg0 []byte, arg1 interface{}) error { ret := m.ctrl.Call(m, "Unmarshal", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockSerializer", ")", "Unmarshal", "(", "arg0", "[", "]", "byte", ",", "arg1", "interface", "{", "}", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// Unmarshal mocks base method
[ "Unmarshal", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/serialize/mocks/serializer.go#L61-L65
train
topfreegames/pitaya
serialize/mocks/serializer.go
Unmarshal
func (mr *MockSerializerMockRecorder) Unmarshal(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unmarshal", reflect.TypeOf((*MockSerializer)(nil).Unmarshal), arg0, arg1) }
go
func (mr *MockSerializerMockRecorder) Unmarshal(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unmarshal", reflect.TypeOf((*MockSerializer)(nil).Unmarshal), arg0, arg1) }
[ "func", "(", "mr", "*", "MockSerializerMockRecorder", ")", "Unmarshal", "(", "arg0", ",", "arg1", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockSerializer", ")", "(", "nil", ")", ".", "Unmarshal", ")", ",", "arg0", ",", "arg1", ")", "\n", "}" ]
// Unmarshal indicates an expected call of Unmarshal
[ "Unmarshal", "indicates", "an", "expected", "call", "of", "Unmarshal" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/serialize/mocks/serializer.go#L68-L70
train
topfreegames/pitaya
docgenerator/generator.go
HandlersDocs
func HandlersDocs(serverType string, services map[string]*component.Service, getPtrNames bool) (map[string]interface{}, error) { docs := &docs{ Handlers: map[string]*doc{}, } for serviceName, service := range services { for name, handler := range service.Handlers { routeName := route.NewRoute(serverType, serviceName, name) docs.Handlers[routeName.String()] = docForMethod(handler.Method, getPtrNames) } } return docs.Handlers.toMap() }
go
func HandlersDocs(serverType string, services map[string]*component.Service, getPtrNames bool) (map[string]interface{}, error) { docs := &docs{ Handlers: map[string]*doc{}, } for serviceName, service := range services { for name, handler := range service.Handlers { routeName := route.NewRoute(serverType, serviceName, name) docs.Handlers[routeName.String()] = docForMethod(handler.Method, getPtrNames) } } return docs.Handlers.toMap() }
[ "func", "HandlersDocs", "(", "serverType", "string", ",", "services", "map", "[", "string", "]", "*", "component", ".", "Service", ",", "getPtrNames", "bool", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "docs", ":=", "&", "docs", "{", "Handlers", ":", "map", "[", "string", "]", "*", "doc", "{", "}", ",", "}", "\n\n", "for", "serviceName", ",", "service", ":=", "range", "services", "{", "for", "name", ",", "handler", ":=", "range", "service", ".", "Handlers", "{", "routeName", ":=", "route", ".", "NewRoute", "(", "serverType", ",", "serviceName", ",", "name", ")", "\n", "docs", ".", "Handlers", "[", "routeName", ".", "String", "(", ")", "]", "=", "docForMethod", "(", "handler", ".", "Method", ",", "getPtrNames", ")", "\n", "}", "\n", "}", "\n\n", "return", "docs", ".", "Handlers", ".", "toMap", "(", ")", "\n", "}" ]
// HandlersDocs returns a map from route to input and output
[ "HandlersDocs", "returns", "a", "map", "from", "route", "to", "input", "and", "output" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/docgenerator/generator.go#L46-L59
train
topfreegames/pitaya
docgenerator/generator.go
RemotesDocs
func RemotesDocs(serverType string, services map[string]*component.Service, getPtrNames bool) (map[string]interface{}, error) { docs := &docs{ Remotes: map[string]*doc{}, } for serviceName, service := range services { for name, remote := range service.Remotes { routeName := route.NewRoute(serverType, serviceName, name) docs.Remotes[routeName.String()] = docForMethod(remote.Method, getPtrNames) } } return docs.Remotes.toMap() }
go
func RemotesDocs(serverType string, services map[string]*component.Service, getPtrNames bool) (map[string]interface{}, error) { docs := &docs{ Remotes: map[string]*doc{}, } for serviceName, service := range services { for name, remote := range service.Remotes { routeName := route.NewRoute(serverType, serviceName, name) docs.Remotes[routeName.String()] = docForMethod(remote.Method, getPtrNames) } } return docs.Remotes.toMap() }
[ "func", "RemotesDocs", "(", "serverType", "string", ",", "services", "map", "[", "string", "]", "*", "component", ".", "Service", ",", "getPtrNames", "bool", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "docs", ":=", "&", "docs", "{", "Remotes", ":", "map", "[", "string", "]", "*", "doc", "{", "}", ",", "}", "\n\n", "for", "serviceName", ",", "service", ":=", "range", "services", "{", "for", "name", ",", "remote", ":=", "range", "service", ".", "Remotes", "{", "routeName", ":=", "route", ".", "NewRoute", "(", "serverType", ",", "serviceName", ",", "name", ")", "\n", "docs", ".", "Remotes", "[", "routeName", ".", "String", "(", ")", "]", "=", "docForMethod", "(", "remote", ".", "Method", ",", "getPtrNames", ")", "\n", "}", "\n", "}", "\n\n", "return", "docs", ".", "Remotes", ".", "toMap", "(", ")", "\n", "}" ]
// RemotesDocs returns a map from route to input and output
[ "RemotesDocs", "returns", "a", "map", "from", "route", "to", "input", "and", "output" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/docgenerator/generator.go#L62-L75
train
topfreegames/pitaya
conn/message/message.go
New
func New(err ...bool) *Message { m := &Message{} if len(err) > 0 { m.Err = err[0] } return m }
go
func New(err ...bool) *Message { m := &Message{} if len(err) > 0 { m.Err = err[0] } return m }
[ "func", "New", "(", "err", "...", "bool", ")", "*", "Message", "{", "m", ":=", "&", "Message", "{", "}", "\n", "if", "len", "(", "err", ")", ">", "0", "{", "m", ".", "Err", "=", "err", "[", "0", "]", "\n", "}", "\n", "return", "m", "\n", "}" ]
// New returns a new message instance
[ "New", "returns", "a", "new", "message", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/message.go#L79-L85
train
topfreegames/pitaya
conn/message/message.go
String
func (m *Message) String() string { return fmt.Sprintf("Type: %s, ID: %d, Route: %s, Compressed: %t, Error: %t, Data: %v, BodyLength: %d", types[m.Type], m.ID, m.Route, m.compressed, m.Err, m.Data, len(m.Data)) }
go
func (m *Message) String() string { return fmt.Sprintf("Type: %s, ID: %d, Route: %s, Compressed: %t, Error: %t, Data: %v, BodyLength: %d", types[m.Type], m.ID, m.Route, m.compressed, m.Err, m.Data, len(m.Data)) }
[ "func", "(", "m", "*", "Message", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "types", "[", "m", ".", "Type", "]", ",", "m", ".", "ID", ",", "m", ".", "Route", ",", "m", ".", "compressed", ",", "m", ".", "Err", ",", "m", ".", "Data", ",", "len", "(", "m", ".", "Data", ")", ")", "\n", "}" ]
// String, implementation of fmt.Stringer interface
[ "String", "implementation", "of", "fmt", ".", "Stringer", "interface" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/message.go#L88-L97
train
topfreegames/pitaya
conn/message/message.go
SetDictionary
func SetDictionary(dict map[string]uint16) error { if dict == nil { return nil } for route, code := range dict { r := strings.TrimSpace(route) // duplication check if _, ok := routes[r]; ok { return fmt.Errorf("duplicated route(route: %s, code: %d)", r, code) } if _, ok := codes[code]; ok { return fmt.Errorf("duplicated route(route: %s, code: %d)", r, code) } // update map, using last value when key duplicated routes[r] = code codes[code] = r } return nil }
go
func SetDictionary(dict map[string]uint16) error { if dict == nil { return nil } for route, code := range dict { r := strings.TrimSpace(route) // duplication check if _, ok := routes[r]; ok { return fmt.Errorf("duplicated route(route: %s, code: %d)", r, code) } if _, ok := codes[code]; ok { return fmt.Errorf("duplicated route(route: %s, code: %d)", r, code) } // update map, using last value when key duplicated routes[r] = code codes[code] = r } return nil }
[ "func", "SetDictionary", "(", "dict", "map", "[", "string", "]", "uint16", ")", "error", "{", "if", "dict", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "for", "route", ",", "code", ":=", "range", "dict", "{", "r", ":=", "strings", ".", "TrimSpace", "(", "route", ")", "\n\n", "// duplication check", "if", "_", ",", "ok", ":=", "routes", "[", "r", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ",", "code", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "codes", "[", "code", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ",", "code", ")", "\n", "}", "\n\n", "// update map, using last value when key duplicated", "routes", "[", "r", "]", "=", "code", "\n", "codes", "[", "code", "]", "=", "r", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetDictionary set routes map which be used to compress route.
[ "SetDictionary", "set", "routes", "map", "which", "be", "used", "to", "compress", "route", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/message/message.go#L109-L132
train
topfreegames/pitaya
conn/packet/packet.go
String
func (p *Packet) String() string { return fmt.Sprintf("Type: %d, Length: %d, Data: %s", p.Type, p.Length, string(p.Data)) }
go
func (p *Packet) String() string { return fmt.Sprintf("Type: %d, Length: %d, Data: %s", p.Type, p.Length, string(p.Data)) }
[ "func", "(", "p", "*", "Packet", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Type", ",", "p", ".", "Length", ",", "string", "(", "p", ".", "Data", ")", ")", "\n", "}" ]
//String represents the Packet's in text mode.
[ "String", "represents", "the", "Packet", "s", "in", "text", "mode", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/conn/packet/packet.go#L40-L42
train
topfreegames/pitaya
metrics/mocks/reporter.go
NewMockReporter
func NewMockReporter(ctrl *gomock.Controller) *MockReporter { mock := &MockReporter{ctrl: ctrl} mock.recorder = &MockReporterMockRecorder{mock} return mock }
go
func NewMockReporter(ctrl *gomock.Controller) *MockReporter { mock := &MockReporter{ctrl: ctrl} mock.recorder = &MockReporterMockRecorder{mock} return mock }
[ "func", "NewMockReporter", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockReporter", "{", "mock", ":=", "&", "MockReporter", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockReporterMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockReporter creates a new mock instance
[ "NewMockReporter", "creates", "a", "new", "mock", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/mocks/reporter.go#L25-L29
train
topfreegames/pitaya
metrics/mocks/reporter.go
ReportCount
func (m *MockReporter) ReportCount(metric string, tags map[string]string, count float64) error { ret := m.ctrl.Call(m, "ReportCount", metric, tags, count) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockReporter) ReportCount(metric string, tags map[string]string, count float64) error { ret := m.ctrl.Call(m, "ReportCount", metric, tags, count) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockReporter", ")", "ReportCount", "(", "metric", "string", ",", "tags", "map", "[", "string", "]", "string", ",", "count", "float64", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "metric", ",", "tags", ",", "count", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// ReportCount mocks base method
[ "ReportCount", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/mocks/reporter.go#L37-L41
train
topfreegames/pitaya
metrics/mocks/reporter.go
ReportCount
func (mr *MockReporterMockRecorder) ReportCount(metric, tags, count interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportCount", reflect.TypeOf((*MockReporter)(nil).ReportCount), metric, tags, count) }
go
func (mr *MockReporterMockRecorder) ReportCount(metric, tags, count interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportCount", reflect.TypeOf((*MockReporter)(nil).ReportCount), metric, tags, count) }
[ "func", "(", "mr", "*", "MockReporterMockRecorder", ")", "ReportCount", "(", "metric", ",", "tags", ",", "count", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockReporter", ")", "(", "nil", ")", ".", "ReportCount", ")", ",", "metric", ",", "tags", ",", "count", ")", "\n", "}" ]
// ReportCount indicates an expected call of ReportCount
[ "ReportCount", "indicates", "an", "expected", "call", "of", "ReportCount" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/mocks/reporter.go#L44-L46
train
topfreegames/pitaya
metrics/mocks/reporter.go
ReportSummary
func (m *MockReporter) ReportSummary(metric string, tags map[string]string, value float64) error { ret := m.ctrl.Call(m, "ReportSummary", metric, tags, value) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockReporter) ReportSummary(metric string, tags map[string]string, value float64) error { ret := m.ctrl.Call(m, "ReportSummary", metric, tags, value) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockReporter", ")", "ReportSummary", "(", "metric", "string", ",", "tags", "map", "[", "string", "]", "string", ",", "value", "float64", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "metric", ",", "tags", ",", "value", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// ReportSummary mocks base method
[ "ReportSummary", "mocks", "base", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/mocks/reporter.go#L49-L53
train
topfreegames/pitaya
metrics/mocks/reporter.go
ReportSummary
func (mr *MockReporterMockRecorder) ReportSummary(metric, tags, value interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportSummary", reflect.TypeOf((*MockReporter)(nil).ReportSummary), metric, tags, value) }
go
func (mr *MockReporterMockRecorder) ReportSummary(metric, tags, value interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportSummary", reflect.TypeOf((*MockReporter)(nil).ReportSummary), metric, tags, value) }
[ "func", "(", "mr", "*", "MockReporterMockRecorder", ")", "ReportSummary", "(", "metric", ",", "tags", ",", "value", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockReporter", ")", "(", "nil", ")", ".", "ReportSummary", ")", ",", "metric", ",", "tags", ",", "value", ")", "\n", "}" ]
// ReportSummary indicates an expected call of ReportSummary
[ "ReportSummary", "indicates", "an", "expected", "call", "of", "ReportSummary" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/mocks/reporter.go#L56-L58
train
topfreegames/pitaya
tracing/span.go
InjectSpan
func InjectSpan(ctx context.Context) (context.Context, error) { span := opentracing.SpanFromContext(ctx) if span == nil { return ctx, nil } spanData := opentracing.TextMapCarrier{} tracer := opentracing.GlobalTracer() err := tracer.Inject(span.Context(), opentracing.TextMap, spanData) if err != nil { return nil, err } return pcontext.AddToPropagateCtx(ctx, constants.SpanPropagateCtxKey, spanData), nil }
go
func InjectSpan(ctx context.Context) (context.Context, error) { span := opentracing.SpanFromContext(ctx) if span == nil { return ctx, nil } spanData := opentracing.TextMapCarrier{} tracer := opentracing.GlobalTracer() err := tracer.Inject(span.Context(), opentracing.TextMap, spanData) if err != nil { return nil, err } return pcontext.AddToPropagateCtx(ctx, constants.SpanPropagateCtxKey, spanData), nil }
[ "func", "InjectSpan", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "span", ":=", "opentracing", ".", "SpanFromContext", "(", "ctx", ")", "\n", "if", "span", "==", "nil", "{", "return", "ctx", ",", "nil", "\n", "}", "\n", "spanData", ":=", "opentracing", ".", "TextMapCarrier", "{", "}", "\n", "tracer", ":=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "err", ":=", "tracer", ".", "Inject", "(", "span", ".", "Context", "(", ")", ",", "opentracing", ".", "TextMap", ",", "spanData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "pcontext", ".", "AddToPropagateCtx", "(", "ctx", ",", "constants", ".", "SpanPropagateCtxKey", ",", "spanData", ")", ",", "nil", "\n", "}" ]
// InjectSpan retrieves an opentrancing span from the current context and creates a new context // with it encoded in binary format inside the propagatable context content
[ "InjectSpan", "retrieves", "an", "opentrancing", "span", "from", "the", "current", "context", "and", "creates", "a", "new", "context", "with", "it", "encoded", "in", "binary", "format", "inside", "the", "propagatable", "context", "content" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/span.go#L79-L91
train
topfreegames/pitaya
tracing/span.go
StartSpan
func StartSpan( parentCtx context.Context, opName string, tags opentracing.Tags, reference ...opentracing.SpanContext, ) context.Context { var ref opentracing.SpanContext if len(reference) > 0 { ref = reference[0] } span := opentracing.StartSpan(opName, opentracing.ChildOf(ref), tags) return opentracing.ContextWithSpan(parentCtx, span) }
go
func StartSpan( parentCtx context.Context, opName string, tags opentracing.Tags, reference ...opentracing.SpanContext, ) context.Context { var ref opentracing.SpanContext if len(reference) > 0 { ref = reference[0] } span := opentracing.StartSpan(opName, opentracing.ChildOf(ref), tags) return opentracing.ContextWithSpan(parentCtx, span) }
[ "func", "StartSpan", "(", "parentCtx", "context", ".", "Context", ",", "opName", "string", ",", "tags", "opentracing", ".", "Tags", ",", "reference", "...", "opentracing", ".", "SpanContext", ",", ")", "context", ".", "Context", "{", "var", "ref", "opentracing", ".", "SpanContext", "\n", "if", "len", "(", "reference", ")", ">", "0", "{", "ref", "=", "reference", "[", "0", "]", "\n", "}", "\n", "span", ":=", "opentracing", ".", "StartSpan", "(", "opName", ",", "opentracing", ".", "ChildOf", "(", "ref", ")", ",", "tags", ")", "\n", "return", "opentracing", ".", "ContextWithSpan", "(", "parentCtx", ",", "span", ")", "\n", "}" ]
// StartSpan starts a new span with a given parent context, operation name, tags and // optional parent span. It returns a context with the created span.
[ "StartSpan", "starts", "a", "new", "span", "with", "a", "given", "parent", "context", "operation", "name", "tags", "and", "optional", "parent", "span", ".", "It", "returns", "a", "context", "with", "the", "created", "span", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/span.go#L95-L107
train
topfreegames/pitaya
tracing/span.go
FinishSpan
func FinishSpan(ctx context.Context, err error) { if ctx == nil { return } span := opentracing.SpanFromContext(ctx) if span == nil { return } defer span.Finish() if err != nil { LogError(span, err.Error()) } }
go
func FinishSpan(ctx context.Context, err error) { if ctx == nil { return } span := opentracing.SpanFromContext(ctx) if span == nil { return } defer span.Finish() if err != nil { LogError(span, err.Error()) } }
[ "func", "FinishSpan", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "{", "if", "ctx", "==", "nil", "{", "return", "\n", "}", "\n", "span", ":=", "opentracing", ".", "SpanFromContext", "(", "ctx", ")", "\n", "if", "span", "==", "nil", "{", "return", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n", "if", "err", "!=", "nil", "{", "LogError", "(", "span", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// FinishSpan finishes a span retrieved from the given context and logs the error if it exists
[ "FinishSpan", "finishes", "a", "span", "retrieved", "from", "the", "given", "context", "and", "logs", "the", "error", "if", "it", "exists" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/span.go#L110-L122
train
topfreegames/pitaya
router/router.go
Route
func (r *Router) Route( ctx context.Context, rpcType protos.RPCType, svType string, route *route.Route, msg *message.Message, ) (*cluster.Server, error) { if r.serviceDiscovery == nil { return nil, constants.ErrServiceDiscoveryNotInitialized } serversOfType, err := r.serviceDiscovery.GetServersByType(svType) if err != nil { return nil, err } if rpcType == protos.RPCType_User { server := r.defaultRoute(serversOfType) return server, nil } routeFunc, ok := r.routesMap[svType] if !ok { logger.Log.Debugf("no specific route for svType: %s, using default route", svType) server := r.defaultRoute(serversOfType) return server, nil } return routeFunc(ctx, route, msg.Data, serversOfType) }
go
func (r *Router) Route( ctx context.Context, rpcType protos.RPCType, svType string, route *route.Route, msg *message.Message, ) (*cluster.Server, error) { if r.serviceDiscovery == nil { return nil, constants.ErrServiceDiscoveryNotInitialized } serversOfType, err := r.serviceDiscovery.GetServersByType(svType) if err != nil { return nil, err } if rpcType == protos.RPCType_User { server := r.defaultRoute(serversOfType) return server, nil } routeFunc, ok := r.routesMap[svType] if !ok { logger.Log.Debugf("no specific route for svType: %s, using default route", svType) server := r.defaultRoute(serversOfType) return server, nil } return routeFunc(ctx, route, msg.Data, serversOfType) }
[ "func", "(", "r", "*", "Router", ")", "Route", "(", "ctx", "context", ".", "Context", ",", "rpcType", "protos", ".", "RPCType", ",", "svType", "string", ",", "route", "*", "route", ".", "Route", ",", "msg", "*", "message", ".", "Message", ",", ")", "(", "*", "cluster", ".", "Server", ",", "error", ")", "{", "if", "r", ".", "serviceDiscovery", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrServiceDiscoveryNotInitialized", "\n", "}", "\n", "serversOfType", ",", "err", ":=", "r", ".", "serviceDiscovery", ".", "GetServersByType", "(", "svType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "rpcType", "==", "protos", ".", "RPCType_User", "{", "server", ":=", "r", ".", "defaultRoute", "(", "serversOfType", ")", "\n", "return", "server", ",", "nil", "\n", "}", "\n", "routeFunc", ",", "ok", ":=", "r", ".", "routesMap", "[", "svType", "]", "\n", "if", "!", "ok", "{", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "svType", ")", "\n", "server", ":=", "r", ".", "defaultRoute", "(", "serversOfType", ")", "\n", "return", "server", ",", "nil", "\n", "}", "\n", "return", "routeFunc", "(", "ctx", ",", "route", ",", "msg", ".", "Data", ",", "serversOfType", ")", "\n", "}" ]
// Route gets the right server to use in the call
[ "Route", "gets", "the", "right", "server", "to", "use", "in", "the", "call" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/router/router.go#L76-L101
train
topfreegames/pitaya
agent/agent.go
NewAgent
func NewAgent( conn net.Conn, packetDecoder codec.PacketDecoder, packetEncoder codec.PacketEncoder, serializer serialize.Serializer, heartbeatTime time.Duration, messagesBufferSize int, dieChan chan bool, messageEncoder message.Encoder, metricsReporters []metrics.Reporter, ) *Agent { // initialize heartbeat and handshake data on first user connection once.Do(func() { hbdEncode(heartbeatTime, packetEncoder, messageEncoder.IsCompressionEnabled(), serializer.GetName()) }) a := &Agent{ appDieChan: dieChan, chDie: make(chan struct{}), chSend: make(chan pendingMessage, messagesBufferSize), chStopHeartbeat: make(chan struct{}), chStopWrite: make(chan struct{}), messagesBufferSize: messagesBufferSize, conn: conn, decoder: packetDecoder, encoder: packetEncoder, heartbeatTimeout: heartbeatTime, lastAt: time.Now().Unix(), serializer: serializer, state: constants.StatusStart, messageEncoder: messageEncoder, metricsReporters: metricsReporters, } // binding session s := session.New(a, true) metrics.ReportNumberOfConnectedClients(metricsReporters, session.SessionCount) a.Session = s return a }
go
func NewAgent( conn net.Conn, packetDecoder codec.PacketDecoder, packetEncoder codec.PacketEncoder, serializer serialize.Serializer, heartbeatTime time.Duration, messagesBufferSize int, dieChan chan bool, messageEncoder message.Encoder, metricsReporters []metrics.Reporter, ) *Agent { // initialize heartbeat and handshake data on first user connection once.Do(func() { hbdEncode(heartbeatTime, packetEncoder, messageEncoder.IsCompressionEnabled(), serializer.GetName()) }) a := &Agent{ appDieChan: dieChan, chDie: make(chan struct{}), chSend: make(chan pendingMessage, messagesBufferSize), chStopHeartbeat: make(chan struct{}), chStopWrite: make(chan struct{}), messagesBufferSize: messagesBufferSize, conn: conn, decoder: packetDecoder, encoder: packetEncoder, heartbeatTimeout: heartbeatTime, lastAt: time.Now().Unix(), serializer: serializer, state: constants.StatusStart, messageEncoder: messageEncoder, metricsReporters: metricsReporters, } // binding session s := session.New(a, true) metrics.ReportNumberOfConnectedClients(metricsReporters, session.SessionCount) a.Session = s return a }
[ "func", "NewAgent", "(", "conn", "net", ".", "Conn", ",", "packetDecoder", "codec", ".", "PacketDecoder", ",", "packetEncoder", "codec", ".", "PacketEncoder", ",", "serializer", "serialize", ".", "Serializer", ",", "heartbeatTime", "time", ".", "Duration", ",", "messagesBufferSize", "int", ",", "dieChan", "chan", "bool", ",", "messageEncoder", "message", ".", "Encoder", ",", "metricsReporters", "[", "]", "metrics", ".", "Reporter", ",", ")", "*", "Agent", "{", "// initialize heartbeat and handshake data on first user connection", "once", ".", "Do", "(", "func", "(", ")", "{", "hbdEncode", "(", "heartbeatTime", ",", "packetEncoder", ",", "messageEncoder", ".", "IsCompressionEnabled", "(", ")", ",", "serializer", ".", "GetName", "(", ")", ")", "\n", "}", ")", "\n\n", "a", ":=", "&", "Agent", "{", "appDieChan", ":", "dieChan", ",", "chDie", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "chSend", ":", "make", "(", "chan", "pendingMessage", ",", "messagesBufferSize", ")", ",", "chStopHeartbeat", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "chStopWrite", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "messagesBufferSize", ":", "messagesBufferSize", ",", "conn", ":", "conn", ",", "decoder", ":", "packetDecoder", ",", "encoder", ":", "packetEncoder", ",", "heartbeatTimeout", ":", "heartbeatTime", ",", "lastAt", ":", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "serializer", ":", "serializer", ",", "state", ":", "constants", ".", "StatusStart", ",", "messageEncoder", ":", "messageEncoder", ",", "metricsReporters", ":", "metricsReporters", ",", "}", "\n\n", "// binding session", "s", ":=", "session", ".", "New", "(", "a", ",", "true", ")", "\n", "metrics", ".", "ReportNumberOfConnectedClients", "(", "metricsReporters", ",", "session", ".", "SessionCount", ")", "\n", "a", ".", "Session", "=", "s", "\n", "return", "a", "\n", "}" ]
// NewAgent create new agent instance
[ "NewAgent", "create", "new", "agent", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent.go#L93-L132
train
topfreegames/pitaya
agent/agent.go
Push
func (a *Agent) Push(route string, v interface{}) error { if a.GetStatus() == constants.StatusClosed { return constants.ErrBrokenPipe } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%dbytes", a.Session.ID(), a.Session.UID(), route, len(d)) default: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%+v", a.Session.ID(), a.Session.UID(), route, v) } return a.send(pendingMessage{typ: message.Push, route: route, payload: v}) }
go
func (a *Agent) Push(route string, v interface{}) error { if a.GetStatus() == constants.StatusClosed { return constants.ErrBrokenPipe } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%dbytes", a.Session.ID(), a.Session.UID(), route, len(d)) default: logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%+v", a.Session.ID(), a.Session.UID(), route, v) } return a.send(pendingMessage{typ: message.Push, route: route, payload: v}) }
[ "func", "(", "a", "*", "Agent", ")", "Push", "(", "route", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "a", ".", "GetStatus", "(", ")", "==", "constants", ".", "StatusClosed", "{", "return", "constants", ".", "ErrBrokenPipe", "\n", "}", "\n\n", "switch", "d", ":=", "v", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "route", ",", "len", "(", "d", ")", ")", "\n", "default", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "route", ",", "v", ")", "\n", "}", "\n", "return", "a", ".", "send", "(", "pendingMessage", "{", "typ", ":", "message", ".", "Push", ",", "route", ":", "route", ",", "payload", ":", "v", "}", ")", "\n", "}" ]
// Push implementation for session.NetworkEntity interface
[ "Push", "implementation", "for", "session", ".", "NetworkEntity", "interface" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent.go#L146-L160
train
topfreegames/pitaya
agent/agent.go
ResponseMID
func (a *Agent) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error { err := false if len(isError) > 0 { err = isError[0] } if a.GetStatus() == constants.StatusClosed { err := constants.ErrBrokenPipe tracing.FinishSpan(ctx, err) metrics.ReportTimingFromCtx(ctx, a.metricsReporters, handlerType, err) return err } if mid <= 0 { err := constants.ErrSessionOnNotify tracing.FinishSpan(ctx, err) metrics.ReportTimingFromCtx(ctx, a.metricsReporters, handlerType, err) return err } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Response, ID=%d, UID=%d, MID=%d, Data=%dbytes", a.Session.ID(), a.Session.UID(), mid, len(d)) default: logger.Log.Infof("Type=Response, ID=%d, UID=%d, MID=%d, Data=%+v", a.Session.ID(), a.Session.UID(), mid, v) } return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}) }
go
func (a *Agent) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error { err := false if len(isError) > 0 { err = isError[0] } if a.GetStatus() == constants.StatusClosed { err := constants.ErrBrokenPipe tracing.FinishSpan(ctx, err) metrics.ReportTimingFromCtx(ctx, a.metricsReporters, handlerType, err) return err } if mid <= 0 { err := constants.ErrSessionOnNotify tracing.FinishSpan(ctx, err) metrics.ReportTimingFromCtx(ctx, a.metricsReporters, handlerType, err) return err } switch d := v.(type) { case []byte: logger.Log.Debugf("Type=Response, ID=%d, UID=%d, MID=%d, Data=%dbytes", a.Session.ID(), a.Session.UID(), mid, len(d)) default: logger.Log.Infof("Type=Response, ID=%d, UID=%d, MID=%d, Data=%+v", a.Session.ID(), a.Session.UID(), mid, v) } return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}) }
[ "func", "(", "a", "*", "Agent", ")", "ResponseMID", "(", "ctx", "context", ".", "Context", ",", "mid", "uint", ",", "v", "interface", "{", "}", ",", "isError", "...", "bool", ")", "error", "{", "err", ":=", "false", "\n", "if", "len", "(", "isError", ")", ">", "0", "{", "err", "=", "isError", "[", "0", "]", "\n", "}", "\n", "if", "a", ".", "GetStatus", "(", ")", "==", "constants", ".", "StatusClosed", "{", "err", ":=", "constants", ".", "ErrBrokenPipe", "\n", "tracing", ".", "FinishSpan", "(", "ctx", ",", "err", ")", "\n", "metrics", ".", "ReportTimingFromCtx", "(", "ctx", ",", "a", ".", "metricsReporters", ",", "handlerType", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "mid", "<=", "0", "{", "err", ":=", "constants", ".", "ErrSessionOnNotify", "\n", "tracing", ".", "FinishSpan", "(", "ctx", ",", "err", ")", "\n", "metrics", ".", "ReportTimingFromCtx", "(", "ctx", ",", "a", ".", "metricsReporters", ",", "handlerType", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "switch", "d", ":=", "v", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "mid", ",", "len", "(", "d", ")", ")", "\n", "default", ":", "logger", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "a", ".", "Session", ".", "ID", "(", ")", ",", "a", ".", "Session", ".", "UID", "(", ")", ",", "mid", ",", "v", ")", "\n", "}", "\n\n", "return", "a", ".", "send", "(", "pendingMessage", "{", "ctx", ":", "ctx", ",", "typ", ":", "message", ".", "Response", ",", "mid", ":", "mid", ",", "payload", ":", "v", ",", "err", ":", "err", "}", ")", "\n", "}" ]
// ResponseMID implementation for session.NetworkEntity interface // Respond message to session
[ "ResponseMID", "implementation", "for", "session", ".", "NetworkEntity", "interface", "Respond", "message", "to", "session" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/agent/agent.go#L164-L193
train