repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
topfreegames/pitaya
service/remote.go
SessionBindRemote
func (r *RemoteService) SessionBindRemote(ctx context.Context, msg *protos.BindMsg) (*protos.Response, error) { for _, r := range r.remoteBindingListeners { r.OnUserBind(msg.Uid, msg.Fid) } return &protos.Response{ Data: []byte("ack"), }, nil }
go
func (r *RemoteService) SessionBindRemote(ctx context.Context, msg *protos.BindMsg) (*protos.Response, error) { for _, r := range r.remoteBindingListeners { r.OnUserBind(msg.Uid, msg.Fid) } return &protos.Response{ Data: []byte("ack"), }, nil }
[ "func", "(", "r", "*", "RemoteService", ")", "SessionBindRemote", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "protos", ".", "BindMsg", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "for", "_", ",", "r", ":=", "range", "r", ".", "remoteBindingListeners", "{", "r", ".", "OnUserBind", "(", "msg", ".", "Uid", ",", "msg", ".", "Fid", ")", "\n", "}", "\n", "return", "&", "protos", ".", "Response", "{", "Data", ":", "[", "]", "byte", "(", "\"ack\"", ")", ",", "}", ",", "nil", "\n", "}" ]
// SessionBindRemote is called when a remote server binds a user session and want us to acknowledge it
[ "SessionBindRemote", "is", "called", "when", "a", "remote", "server", "binds", "a", "user", "session", "and", "want", "us", "to", "acknowledge", "it" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L150-L157
train
topfreegames/pitaya
service/remote.go
PushToUser
func (r *RemoteService) PushToUser(ctx context.Context, push *protos.Push) (*protos.Response, error) { logger.Log.Debugf("sending push to user %s: %v", push.GetUid(), string(push.Data)) s := session.GetSessionByUID(push.GetUid()) if s != nil { err := s.Push(push.Route, push.Data) if err != nil { return nil, err } return &protos.Response{ Data: []byte("ack"), }, nil } return nil, constants.ErrSessionNotFound }
go
func (r *RemoteService) PushToUser(ctx context.Context, push *protos.Push) (*protos.Response, error) { logger.Log.Debugf("sending push to user %s: %v", push.GetUid(), string(push.Data)) s := session.GetSessionByUID(push.GetUid()) if s != nil { err := s.Push(push.Route, push.Data) if err != nil { return nil, err } return &protos.Response{ Data: []byte("ack"), }, nil } return nil, constants.ErrSessionNotFound }
[ "func", "(", "r", "*", "RemoteService", ")", "PushToUser", "(", "ctx", "context", ".", "Context", ",", "push", "*", "protos", ".", "Push", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "logger", ".", "Log", ".", "Debugf", "(", "\"sending push to user %s: %v\"", ",", "push", ".", "GetUid", "(", ")", ",", "string", "(", "push", ".", "Data", ")", ")", "\n", "s", ":=", "session", ".", "GetSessionByUID", "(", "push", ".", "GetUid", "(", ")", ")", "\n", "if", "s", "!=", "nil", "{", "err", ":=", "s", ".", "Push", "(", "push", ".", "Route", ",", "push", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "protos", ".", "Response", "{", "Data", ":", "[", "]", "byte", "(", "\"ack\"", ")", ",", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "constants", ".", "ErrSessionNotFound", "\n", "}" ]
// PushToUser sends a push to user
[ "PushToUser", "sends", "a", "push", "to", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L160-L173
train
topfreegames/pitaya
service/remote.go
KickUser
func (r *RemoteService) KickUser(ctx context.Context, kick *protos.KickMsg) (*protos.KickAnswer, error) { logger.Log.Debugf("sending kick to user %s", kick.GetUserId()) s := session.GetSessionByUID(kick.GetUserId()) if s != nil { err := s.Kick(ctx) if err != nil { return nil, err } return &protos.KickAnswer{ Kicked: true, }, nil } return nil, constants.ErrSessionNotFound }
go
func (r *RemoteService) KickUser(ctx context.Context, kick *protos.KickMsg) (*protos.KickAnswer, error) { logger.Log.Debugf("sending kick to user %s", kick.GetUserId()) s := session.GetSessionByUID(kick.GetUserId()) if s != nil { err := s.Kick(ctx) if err != nil { return nil, err } return &protos.KickAnswer{ Kicked: true, }, nil } return nil, constants.ErrSessionNotFound }
[ "func", "(", "r", "*", "RemoteService", ")", "KickUser", "(", "ctx", "context", ".", "Context", ",", "kick", "*", "protos", ".", "KickMsg", ")", "(", "*", "protos", ".", "KickAnswer", ",", "error", ")", "{", "logger", ".", "Log", ".", "Debugf", "(", "\"sending kick to user %s\"", ",", "kick", ".", "GetUserId", "(", ")", ")", "\n", "s", ":=", "session", ".", "GetSessionByUID", "(", "kick", ".", "GetUserId", "(", ")", ")", "\n", "if", "s", "!=", "nil", "{", "err", ":=", "s", ".", "Kick", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "protos", ".", "KickAnswer", "{", "Kicked", ":", "true", ",", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "constants", ".", "ErrSessionNotFound", "\n", "}" ]
// KickUser sends a kick to user
[ "KickUser", "sends", "a", "kick", "to", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L176-L189
train
topfreegames/pitaya
service/remote.go
DoRPC
func (r *RemoteService) DoRPC(ctx context.Context, serverID string, route *route.Route, protoData []byte) (*protos.Response, error) { msg := &message.Message{ Type: message.Request, Route: route.Short(), Data: protoData, } target, _ := r.serviceDiscovery.GetServer(serverID) if serverID != "" && target == nil { return nil, constants.ErrServerNotFound } return r.remoteCall(ctx, target, protos.RPCType_User, route, nil, msg) }
go
func (r *RemoteService) DoRPC(ctx context.Context, serverID string, route *route.Route, protoData []byte) (*protos.Response, error) { msg := &message.Message{ Type: message.Request, Route: route.Short(), Data: protoData, } target, _ := r.serviceDiscovery.GetServer(serverID) if serverID != "" && target == nil { return nil, constants.ErrServerNotFound } return r.remoteCall(ctx, target, protos.RPCType_User, route, nil, msg) }
[ "func", "(", "r", "*", "RemoteService", ")", "DoRPC", "(", "ctx", "context", ".", "Context", ",", "serverID", "string", ",", "route", "*", "route", ".", "Route", ",", "protoData", "[", "]", "byte", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "msg", ":=", "&", "message", ".", "Message", "{", "Type", ":", "message", ".", "Request", ",", "Route", ":", "route", ".", "Short", "(", ")", ",", "Data", ":", "protoData", ",", "}", "\n", "target", ",", "_", ":=", "r", ".", "serviceDiscovery", ".", "GetServer", "(", "serverID", ")", "\n", "if", "serverID", "!=", "\"\"", "&&", "target", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrServerNotFound", "\n", "}", "\n", "return", "r", ".", "remoteCall", "(", "ctx", ",", "target", ",", "protos", ".", "RPCType_User", ",", "route", ",", "nil", ",", "msg", ")", "\n", "}" ]
// DoRPC do rpc and get answer
[ "DoRPC", "do", "rpc", "and", "get", "answer" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L192-L205
train
topfreegames/pitaya
service/remote.go
RPC
func (r *RemoteService) RPC(ctx context.Context, serverID string, route *route.Route, reply proto.Message, arg proto.Message) error { var data []byte var err error if arg != nil { data, err = proto.Marshal(arg) if err != nil { return err } } res, err := r.DoRPC(ctx, serverID, route, data) if err != nil { return err } if res.Error != nil { return &e.Error{ Code: res.Error.Code, Message: res.Error.Msg, Metadata: res.Error.Metadata, } } if reply != nil { err = proto.Unmarshal(res.GetData(), reply) if err != nil { return err } } return nil }
go
func (r *RemoteService) RPC(ctx context.Context, serverID string, route *route.Route, reply proto.Message, arg proto.Message) error { var data []byte var err error if arg != nil { data, err = proto.Marshal(arg) if err != nil { return err } } res, err := r.DoRPC(ctx, serverID, route, data) if err != nil { return err } if res.Error != nil { return &e.Error{ Code: res.Error.Code, Message: res.Error.Msg, Metadata: res.Error.Metadata, } } if reply != nil { err = proto.Unmarshal(res.GetData(), reply) if err != nil { return err } } return nil }
[ "func", "(", "r", "*", "RemoteService", ")", "RPC", "(", "ctx", "context", ".", "Context", ",", "serverID", "string", ",", "route", "*", "route", ".", "Route", ",", "reply", "proto", ".", "Message", ",", "arg", "proto", ".", "Message", ")", "error", "{", "var", "data", "[", "]", "byte", "\n", "var", "err", "error", "\n", "if", "arg", "!=", "nil", "{", "data", ",", "err", "=", "proto", ".", "Marshal", "(", "arg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "res", ",", "err", ":=", "r", ".", "DoRPC", "(", "ctx", ",", "serverID", ",", "route", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "res", ".", "Error", "!=", "nil", "{", "return", "&", "e", ".", "Error", "{", "Code", ":", "res", ".", "Error", ".", "Code", ",", "Message", ":", "res", ".", "Error", ".", "Msg", ",", "Metadata", ":", "res", ".", "Error", ".", "Metadata", ",", "}", "\n", "}", "\n", "if", "reply", "!=", "nil", "{", "err", "=", "proto", ".", "Unmarshal", "(", "res", ".", "GetData", "(", ")", ",", "reply", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RPC makes rpcs
[ "RPC", "makes", "rpcs" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L208-L237
train
topfreegames/pitaya
service/remote.go
Docs
func (r *RemoteService) Docs(getPtrNames bool) (map[string]interface{}, error) { if r == nil { return map[string]interface{}{}, nil } return docgenerator.RemotesDocs(r.server.Type, r.services, getPtrNames) }
go
func (r *RemoteService) Docs(getPtrNames bool) (map[string]interface{}, error) { if r == nil { return map[string]interface{}{}, nil } return docgenerator.RemotesDocs(r.server.Type, r.services, getPtrNames) }
[ "func", "(", "r", "*", "RemoteService", ")", "Docs", "(", "getPtrNames", "bool", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "r", "==", "nil", "{", "return", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "nil", "\n", "}", "\n", "return", "docgenerator", ".", "RemotesDocs", "(", "r", ".", "server", ".", "Type", ",", "r", ".", "services", ",", "getPtrNames", ")", "\n", "}" ]
// Docs returns documentation for remotes
[ "Docs", "returns", "documentation", "for", "remotes" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/service/remote.go#L450-L455
train
topfreegames/pitaya
component/method.go
isRemoteMethod
func isRemoteMethod(method reflect.Method) bool { mt := method.Type // Method must be exported. if method.PkgPath != "" { return false } // Method needs at least two ins: receiver and context.Context if mt.NumIn() != 2 && mt.NumIn() != 3 { return false } if t1 := mt.In(1); !t1.Implements(typeOfContext) { return false } if mt.NumIn() == 3 { if t2 := mt.In(2); !t2.Implements(typeOfProtoMsg) { return false } } // Method needs two outs: interface{}(that implements proto.Message), error if mt.NumOut() != 2 { return false } if (mt.Out(0).Kind() != reflect.Ptr) || mt.Out(1) != typeOfError { return false } if o0 := mt.Out(0); !o0.Implements(typeOfProtoMsg) { return false } return true }
go
func isRemoteMethod(method reflect.Method) bool { mt := method.Type // Method must be exported. if method.PkgPath != "" { return false } // Method needs at least two ins: receiver and context.Context if mt.NumIn() != 2 && mt.NumIn() != 3 { return false } if t1 := mt.In(1); !t1.Implements(typeOfContext) { return false } if mt.NumIn() == 3 { if t2 := mt.In(2); !t2.Implements(typeOfProtoMsg) { return false } } // Method needs two outs: interface{}(that implements proto.Message), error if mt.NumOut() != 2 { return false } if (mt.Out(0).Kind() != reflect.Ptr) || mt.Out(1) != typeOfError { return false } if o0 := mt.Out(0); !o0.Implements(typeOfProtoMsg) { return false } return true }
[ "func", "isRemoteMethod", "(", "method", "reflect", ".", "Method", ")", "bool", "{", "mt", ":=", "method", ".", "Type", "\n", "if", "method", ".", "PkgPath", "!=", "\"\"", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumIn", "(", ")", "!=", "2", "&&", "mt", ".", "NumIn", "(", ")", "!=", "3", "{", "return", "false", "\n", "}", "\n", "if", "t1", ":=", "mt", ".", "In", "(", "1", ")", ";", "!", "t1", ".", "Implements", "(", "typeOfContext", ")", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumIn", "(", ")", "==", "3", "{", "if", "t2", ":=", "mt", ".", "In", "(", "2", ")", ";", "!", "t2", ".", "Implements", "(", "typeOfProtoMsg", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "mt", ".", "NumOut", "(", ")", "!=", "2", "{", "return", "false", "\n", "}", "\n", "if", "(", "mt", ".", "Out", "(", "0", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", ")", "||", "mt", ".", "Out", "(", "1", ")", "!=", "typeOfError", "{", "return", "false", "\n", "}", "\n", "if", "o0", ":=", "mt", ".", "Out", "(", "0", ")", ";", "!", "o0", ".", "Implements", "(", "typeOfProtoMsg", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isRemoteMethod decide a method is suitable remote method
[ "isRemoteMethod", "decide", "a", "method", "is", "suitable", "remote", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/component/method.go#L46-L82
train
topfreegames/pitaya
component/method.go
isHandlerMethod
func isHandlerMethod(method reflect.Method) bool { mt := method.Type // Method must be exported. if method.PkgPath != "" { return false } // Method needs two or three ins: receiver, context.Context and optional []byte or pointer. if mt.NumIn() != 2 && mt.NumIn() != 3 { return false } if t1 := mt.In(1); !t1.Implements(typeOfContext) { return false } if mt.NumIn() == 3 && mt.In(2).Kind() != reflect.Ptr && mt.In(2) != typeOfBytes { return false } // Method needs either no out or two outs: interface{}(or []byte), error if mt.NumOut() != 0 && mt.NumOut() != 2 { return false } if mt.NumOut() == 2 && (mt.Out(1) != typeOfError || mt.Out(0) != typeOfBytes && mt.Out(0).Kind() != reflect.Ptr) { return false } return true }
go
func isHandlerMethod(method reflect.Method) bool { mt := method.Type // Method must be exported. if method.PkgPath != "" { return false } // Method needs two or three ins: receiver, context.Context and optional []byte or pointer. if mt.NumIn() != 2 && mt.NumIn() != 3 { return false } if t1 := mt.In(1); !t1.Implements(typeOfContext) { return false } if mt.NumIn() == 3 && mt.In(2).Kind() != reflect.Ptr && mt.In(2) != typeOfBytes { return false } // Method needs either no out or two outs: interface{}(or []byte), error if mt.NumOut() != 0 && mt.NumOut() != 2 { return false } if mt.NumOut() == 2 && (mt.Out(1) != typeOfError || mt.Out(0) != typeOfBytes && mt.Out(0).Kind() != reflect.Ptr) { return false } return true }
[ "func", "isHandlerMethod", "(", "method", "reflect", ".", "Method", ")", "bool", "{", "mt", ":=", "method", ".", "Type", "\n", "if", "method", ".", "PkgPath", "!=", "\"\"", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumIn", "(", ")", "!=", "2", "&&", "mt", ".", "NumIn", "(", ")", "!=", "3", "{", "return", "false", "\n", "}", "\n", "if", "t1", ":=", "mt", ".", "In", "(", "1", ")", ";", "!", "t1", ".", "Implements", "(", "typeOfContext", ")", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumIn", "(", ")", "==", "3", "&&", "mt", ".", "In", "(", "2", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "&&", "mt", ".", "In", "(", "2", ")", "!=", "typeOfBytes", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumOut", "(", ")", "!=", "0", "&&", "mt", ".", "NumOut", "(", ")", "!=", "2", "{", "return", "false", "\n", "}", "\n", "if", "mt", ".", "NumOut", "(", ")", "==", "2", "&&", "(", "mt", ".", "Out", "(", "1", ")", "!=", "typeOfError", "||", "mt", ".", "Out", "(", "0", ")", "!=", "typeOfBytes", "&&", "mt", ".", "Out", "(", "0", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isHandlerMethod decide a method is suitable handler method
[ "isHandlerMethod", "decide", "a", "method", "is", "suitable", "handler", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/component/method.go#L85-L115
train
topfreegames/pitaya
remote/sys.go
BindSession
func (s *Sys) BindSession(ctx context.Context, sessionData *protos.Session) (*protos.Response, error) { sess := session.GetSessionByID(sessionData.Id) if sess == nil { return nil, constants.ErrSessionNotFound } if err := sess.Bind(ctx, sessionData.Uid); err != nil { return nil, err } return &protos.Response{Data: []byte("ack")}, nil }
go
func (s *Sys) BindSession(ctx context.Context, sessionData *protos.Session) (*protos.Response, error) { sess := session.GetSessionByID(sessionData.Id) if sess == nil { return nil, constants.ErrSessionNotFound } if err := sess.Bind(ctx, sessionData.Uid); err != nil { return nil, err } return &protos.Response{Data: []byte("ack")}, nil }
[ "func", "(", "s", "*", "Sys", ")", "BindSession", "(", "ctx", "context", ".", "Context", ",", "sessionData", "*", "protos", ".", "Session", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "sess", ":=", "session", ".", "GetSessionByID", "(", "sessionData", ".", "Id", ")", "\n", "if", "sess", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrSessionNotFound", "\n", "}", "\n", "if", "err", ":=", "sess", ".", "Bind", "(", "ctx", ",", "sessionData", ".", "Uid", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "protos", ".", "Response", "{", "Data", ":", "[", "]", "byte", "(", "\"ack\"", ")", "}", ",", "nil", "\n", "}" ]
// BindSession binds the local session
[ "BindSession", "binds", "the", "local", "session" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/remote/sys.go#L38-L47
train
topfreegames/pitaya
remote/sys.go
Kick
func (s *Sys) Kick(ctx context.Context, msg *protos.KickMsg) (*protos.KickAnswer, error) { res := &protos.KickAnswer{ Kicked: false, } sess := session.GetSessionByUID(msg.GetUserId()) if sess == nil { return res, constants.ErrSessionNotFound } err := sess.Kick(ctx) if err != nil { return res, err } res.Kicked = true return res, nil }
go
func (s *Sys) Kick(ctx context.Context, msg *protos.KickMsg) (*protos.KickAnswer, error) { res := &protos.KickAnswer{ Kicked: false, } sess := session.GetSessionByUID(msg.GetUserId()) if sess == nil { return res, constants.ErrSessionNotFound } err := sess.Kick(ctx) if err != nil { return res, err } res.Kicked = true return res, nil }
[ "func", "(", "s", "*", "Sys", ")", "Kick", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "protos", ".", "KickMsg", ")", "(", "*", "protos", ".", "KickAnswer", ",", "error", ")", "{", "res", ":=", "&", "protos", ".", "KickAnswer", "{", "Kicked", ":", "false", ",", "}", "\n", "sess", ":=", "session", ".", "GetSessionByUID", "(", "msg", ".", "GetUserId", "(", ")", ")", "\n", "if", "sess", "==", "nil", "{", "return", "res", ",", "constants", ".", "ErrSessionNotFound", "\n", "}", "\n", "err", ":=", "sess", ".", "Kick", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n", "res", ".", "Kicked", "=", "true", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Kick kicks a local user
[ "Kick", "kicks", "a", "local", "user" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/remote/sys.go#L62-L76
train
topfreegames/pitaya
examples/demo/cluster_protobuf/services/connector.go
RemoteFunc
func (c *ConnectorRemote) RemoteFunc(ctx context.Context, message []byte) (*protos.Response, error) { fmt.Printf("received a remote call with this message: %s\n", message) return &protos.Response{ Msg: string(message), }, nil }
go
func (c *ConnectorRemote) RemoteFunc(ctx context.Context, message []byte) (*protos.Response, error) { fmt.Printf("received a remote call with this message: %s\n", message) return &protos.Response{ Msg: string(message), }, nil }
[ "func", "(", "c", "*", "ConnectorRemote", ")", "RemoteFunc", "(", "ctx", "context", ".", "Context", ",", "message", "[", "]", "byte", ")", "(", "*", "protos", ".", "Response", ",", "error", ")", "{", "fmt", ".", "Printf", "(", "\"received a remote call with this message: %s\\n\"", ",", "\\n", ")", "\n", "message", "\n", "}" ]
// RemoteFunc is a function that will be called remotelly
[ "RemoteFunc", "is", "a", "function", "that", "will", "be", "called", "remotelly" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/examples/demo/cluster_protobuf/services/connector.go#L27-L32
train
topfreegames/pitaya
module.go
RegisterModule
func RegisterModule(module interfaces.Module, name string) error { return RegisterModuleAfter(module, name) }
go
func RegisterModule(module interfaces.Module, name string) error { return RegisterModuleAfter(module, name) }
[ "func", "RegisterModule", "(", "module", "interfaces", ".", "Module", ",", "name", "string", ")", "error", "{", "return", "RegisterModuleAfter", "(", "module", ",", "name", ")", "\n", "}" ]
// RegisterModule registers a module, by default it register after registered modules
[ "RegisterModule", "registers", "a", "module", "by", "default", "it", "register", "after", "registered", "modules" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/module.go#L41-L43
train
topfreegames/pitaya
module.go
RegisterModuleAfter
func RegisterModuleAfter(module interfaces.Module, name string) error { if err := alreadyRegistered(name); err != nil { return err } modulesMap[name] = module modulesArr = append(modulesArr, moduleWrapper{ module: module, name: name, }) return nil }
go
func RegisterModuleAfter(module interfaces.Module, name string) error { if err := alreadyRegistered(name); err != nil { return err } modulesMap[name] = module modulesArr = append(modulesArr, moduleWrapper{ module: module, name: name, }) return nil }
[ "func", "RegisterModuleAfter", "(", "module", "interfaces", ".", "Module", ",", "name", "string", ")", "error", "{", "if", "err", ":=", "alreadyRegistered", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "modulesMap", "[", "name", "]", "=", "module", "\n", "modulesArr", "=", "append", "(", "modulesArr", ",", "moduleWrapper", "{", "module", ":", "module", ",", "name", ":", "name", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// RegisterModuleAfter registers a module after all registered modules
[ "RegisterModuleAfter", "registers", "a", "module", "after", "all", "registered", "modules" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/module.go#L46-L58
train
topfreegames/pitaya
module.go
GetModule
func GetModule(name string) (interfaces.Module, error) { if m, ok := modulesMap[name]; ok { return m, nil } return nil, fmt.Errorf("module with name %s not found", name) }
go
func GetModule(name string) (interfaces.Module, error) { if m, ok := modulesMap[name]; ok { return m, nil } return nil, fmt.Errorf("module with name %s not found", name) }
[ "func", "GetModule", "(", "name", "string", ")", "(", "interfaces", ".", "Module", ",", "error", ")", "{", "if", "m", ",", "ok", ":=", "modulesMap", "[", "name", "]", ";", "ok", "{", "return", "m", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"module with name %s not found\"", ",", "name", ")", "\n", "}" ]
// GetModule gets a module with a name
[ "GetModule", "gets", "a", "module", "with", "a", "name" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/module.go#L78-L83
train
topfreegames/pitaya
module.go
startModules
func startModules() { logger.Log.Debug("initializing all modules") for _, modWrapper := range modulesArr { logger.Log.Debugf("initializing module: %s", modWrapper.name) if err := modWrapper.module.Init(); err != nil { logger.Log.Fatalf("error starting module %s, error: %s", modWrapper.name, err.Error()) } } for _, modWrapper := range modulesArr { modWrapper.module.AfterInit() logger.Log.Infof("module: %s successfully loaded", modWrapper.name) } }
go
func startModules() { logger.Log.Debug("initializing all modules") for _, modWrapper := range modulesArr { logger.Log.Debugf("initializing module: %s", modWrapper.name) if err := modWrapper.module.Init(); err != nil { logger.Log.Fatalf("error starting module %s, error: %s", modWrapper.name, err.Error()) } } for _, modWrapper := range modulesArr { modWrapper.module.AfterInit() logger.Log.Infof("module: %s successfully loaded", modWrapper.name) } }
[ "func", "startModules", "(", ")", "{", "logger", ".", "Log", ".", "Debug", "(", "\"initializing all modules\"", ")", "\n", "for", "_", ",", "modWrapper", ":=", "range", "modulesArr", "{", "logger", ".", "Log", ".", "Debugf", "(", "\"initializing module: %s\"", ",", "modWrapper", ".", "name", ")", "\n", "if", "err", ":=", "modWrapper", ".", "module", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Fatalf", "(", "\"error starting module %s, error: %s\"", ",", "modWrapper", ".", "name", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "modWrapper", ":=", "range", "modulesArr", "{", "modWrapper", ".", "module", ".", "AfterInit", "(", ")", "\n", "logger", ".", "Log", ".", "Infof", "(", "\"module: %s successfully loaded\"", ",", "modWrapper", ".", "name", ")", "\n", "}", "\n", "}" ]
// startModules starts all modules in order
[ "startModules", "starts", "all", "modules", "in", "order" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/module.go#L94-L107
train
topfreegames/pitaya
module.go
shutdownModules
func shutdownModules() { for i := len(modulesArr) - 1; i >= 0; i-- { modulesArr[i].module.BeforeShutdown() } for i := len(modulesArr) - 1; i >= 0; i-- { name := modulesArr[i].name mod := modulesArr[i].module logger.Log.Debugf("stopping module: %s", name) if err := mod.Shutdown(); err != nil { logger.Log.Warnf("error stopping module: %s", name) } logger.Log.Infof("module: %s stopped!", name) } }
go
func shutdownModules() { for i := len(modulesArr) - 1; i >= 0; i-- { modulesArr[i].module.BeforeShutdown() } for i := len(modulesArr) - 1; i >= 0; i-- { name := modulesArr[i].name mod := modulesArr[i].module logger.Log.Debugf("stopping module: %s", name) if err := mod.Shutdown(); err != nil { logger.Log.Warnf("error stopping module: %s", name) } logger.Log.Infof("module: %s stopped!", name) } }
[ "func", "shutdownModules", "(", ")", "{", "for", "i", ":=", "len", "(", "modulesArr", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "modulesArr", "[", "i", "]", ".", "module", ".", "BeforeShutdown", "(", ")", "\n", "}", "\n", "for", "i", ":=", "len", "(", "modulesArr", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "name", ":=", "modulesArr", "[", "i", "]", ".", "name", "\n", "mod", ":=", "modulesArr", "[", "i", "]", ".", "module", "\n", "logger", ".", "Log", ".", "Debugf", "(", "\"stopping module: %s\"", ",", "name", ")", "\n", "if", "err", ":=", "mod", ".", "Shutdown", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Warnf", "(", "\"error stopping module: %s\"", ",", "name", ")", "\n", "}", "\n", "logger", ".", "Log", ".", "Infof", "(", "\"module: %s stopped!\"", ",", "name", ")", "\n", "}", "\n", "}" ]
// shutdownModules starts all modules in reverse order
[ "shutdownModules", "starts", "all", "modules", "in", "reverse", "order" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/module.go#L110-L125
train
topfreegames/pitaya
metrics/statsd_reporter.go
NewStatsdReporter
func NewStatsdReporter( config *config.Config, serverType string, tagsMap map[string]string, clientOrNil ...Client, ) (*StatsdReporter, error) { host := config.GetString("pitaya.metrics.statsd.host") prefix := config.GetString("pitaya.metrics.statsd.prefix") rate, err := strconv.ParseFloat(config.GetString("pitaya.metrics.statsd.rate"), 64) if err != nil { return nil, err } sr := &StatsdReporter{ rate: rate, serverType: serverType, } sr.buildDefaultTags(tagsMap) if len(clientOrNil) > 0 { sr.client = clientOrNil[0] } else { c, err := statsd.New(host) if err != nil { return nil, err } c.Namespace = prefix sr.client = c } return sr, nil }
go
func NewStatsdReporter( config *config.Config, serverType string, tagsMap map[string]string, clientOrNil ...Client, ) (*StatsdReporter, error) { host := config.GetString("pitaya.metrics.statsd.host") prefix := config.GetString("pitaya.metrics.statsd.prefix") rate, err := strconv.ParseFloat(config.GetString("pitaya.metrics.statsd.rate"), 64) if err != nil { return nil, err } sr := &StatsdReporter{ rate: rate, serverType: serverType, } sr.buildDefaultTags(tagsMap) if len(clientOrNil) > 0 { sr.client = clientOrNil[0] } else { c, err := statsd.New(host) if err != nil { return nil, err } c.Namespace = prefix sr.client = c } return sr, nil }
[ "func", "NewStatsdReporter", "(", "config", "*", "config", ".", "Config", ",", "serverType", "string", ",", "tagsMap", "map", "[", "string", "]", "string", ",", "clientOrNil", "...", "Client", ",", ")", "(", "*", "StatsdReporter", ",", "error", ")", "{", "host", ":=", "config", ".", "GetString", "(", "\"pitaya.metrics.statsd.host\"", ")", "\n", "prefix", ":=", "config", ".", "GetString", "(", "\"pitaya.metrics.statsd.prefix\"", ")", "\n", "rate", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "config", ".", "GetString", "(", "\"pitaya.metrics.statsd.rate\"", ")", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sr", ":=", "&", "StatsdReporter", "{", "rate", ":", "rate", ",", "serverType", ":", "serverType", ",", "}", "\n", "sr", ".", "buildDefaultTags", "(", "tagsMap", ")", "\n", "if", "len", "(", "clientOrNil", ")", ">", "0", "{", "sr", ".", "client", "=", "clientOrNil", "[", "0", "]", "\n", "}", "else", "{", "c", ",", "err", ":=", "statsd", ".", "New", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "Namespace", "=", "prefix", "\n", "sr", ".", "client", "=", "c", "\n", "}", "\n", "return", "sr", ",", "nil", "\n", "}" ]
// NewStatsdReporter returns an instance of statsd reportar and an error if something fails
[ "NewStatsdReporter", "returns", "an", "instance", "of", "statsd", "reportar", "and", "an", "error", "if", "something", "fails" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/statsd_reporter.go#L48-L78
train
topfreegames/pitaya
metrics/statsd_reporter.go
ReportCount
func (s *StatsdReporter) ReportCount(metric string, tagsMap map[string]string, count float64) error { fullTags := s.defaultTags for k, v := range tagsMap { fullTags = append(fullTags, fmt.Sprintf("%s:%s", k, v)) } err := s.client.Count(metric, int64(count), fullTags, s.rate) if err != nil { logger.Log.Errorf("failed to report count: %q", err) } return err }
go
func (s *StatsdReporter) ReportCount(metric string, tagsMap map[string]string, count float64) error { fullTags := s.defaultTags for k, v := range tagsMap { fullTags = append(fullTags, fmt.Sprintf("%s:%s", k, v)) } err := s.client.Count(metric, int64(count), fullTags, s.rate) if err != nil { logger.Log.Errorf("failed to report count: %q", err) } return err }
[ "func", "(", "s", "*", "StatsdReporter", ")", "ReportCount", "(", "metric", "string", ",", "tagsMap", "map", "[", "string", "]", "string", ",", "count", "float64", ")", "error", "{", "fullTags", ":=", "s", ".", "defaultTags", "\n", "for", "k", ",", "v", ":=", "range", "tagsMap", "{", "fullTags", "=", "append", "(", "fullTags", ",", "fmt", ".", "Sprintf", "(", "\"%s:%s\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "err", ":=", "s", ".", "client", ".", "Count", "(", "metric", ",", "int64", "(", "count", ")", ",", "fullTags", ",", "s", ".", "rate", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Errorf", "(", "\"failed to report count: %q\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ReportCount sends count reports to statsd
[ "ReportCount", "sends", "count", "reports", "to", "statsd" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/statsd_reporter.go#L95-L108
train
topfreegames/pitaya
metrics/statsd_reporter.go
ReportGauge
func (s *StatsdReporter) ReportGauge(metric string, tagsMap map[string]string, value float64) error { fullTags := s.defaultTags for k, v := range tagsMap { fullTags = append(fullTags, fmt.Sprintf("%s:%s", k, v)) } err := s.client.Gauge(metric, value, fullTags, s.rate) if err != nil { logger.Log.Errorf("failed to report gauge: %q", err) } return err }
go
func (s *StatsdReporter) ReportGauge(metric string, tagsMap map[string]string, value float64) error { fullTags := s.defaultTags for k, v := range tagsMap { fullTags = append(fullTags, fmt.Sprintf("%s:%s", k, v)) } err := s.client.Gauge(metric, value, fullTags, s.rate) if err != nil { logger.Log.Errorf("failed to report gauge: %q", err) } return err }
[ "func", "(", "s", "*", "StatsdReporter", ")", "ReportGauge", "(", "metric", "string", ",", "tagsMap", "map", "[", "string", "]", "string", ",", "value", "float64", ")", "error", "{", "fullTags", ":=", "s", ".", "defaultTags", "\n", "for", "k", ",", "v", ":=", "range", "tagsMap", "{", "fullTags", "=", "append", "(", "fullTags", ",", "fmt", ".", "Sprintf", "(", "\"%s:%s\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "err", ":=", "s", ".", "client", ".", "Gauge", "(", "metric", ",", "value", ",", "fullTags", ",", "s", ".", "rate", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Errorf", "(", "\"failed to report gauge: %q\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ReportGauge sents the gauge value and reports to statsd
[ "ReportGauge", "sents", "the", "gauge", "value", "and", "reports", "to", "statsd" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/statsd_reporter.go#L111-L124
train
topfreegames/pitaya
group.go
GroupCreate
func GroupCreate(ctx context.Context, groupName string) error { return groupServiceInstance.GroupCreate(ctx, groupName) }
go
func GroupCreate(ctx context.Context, groupName string) error { return groupServiceInstance.GroupCreate(ctx, groupName) }
[ "func", "GroupCreate", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupCreate", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupCreate creates a group
[ "GroupCreate", "creates", "a", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L49-L51
train
topfreegames/pitaya
group.go
GroupCreateWithTTL
func GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { return groupServiceInstance.GroupCreateWithTTL(ctx, groupName, ttlTime) }
go
func GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { return groupServiceInstance.GroupCreateWithTTL(ctx, groupName, ttlTime) }
[ "func", "GroupCreateWithTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ",", "ttlTime", "time", ".", "Duration", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupCreateWithTTL", "(", "ctx", ",", "groupName", ",", "ttlTime", ")", "\n", "}" ]
// GroupCreateWithTTL creates a group with given TTL
[ "GroupCreateWithTTL", "creates", "a", "group", "with", "given", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L54-L56
train
topfreegames/pitaya
group.go
GroupBroadcast
func GroupBroadcast(ctx context.Context, frontendType, groupName, route string, v interface{}) error { logger.Log.Debugf("Type=Broadcast Route=%s, Data=%+v", route, v) members, err := GroupMembers(ctx, groupName) if err != nil { return err } return sendDataToMembers(members, frontendType, route, v) }
go
func GroupBroadcast(ctx context.Context, frontendType, groupName, route string, v interface{}) error { logger.Log.Debugf("Type=Broadcast Route=%s, Data=%+v", route, v) members, err := GroupMembers(ctx, groupName) if err != nil { return err } return sendDataToMembers(members, frontendType, route, v) }
[ "func", "GroupBroadcast", "(", "ctx", "context", ".", "Context", ",", "frontendType", ",", "groupName", ",", "route", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "logger", ".", "Log", ".", "Debugf", "(", "\"Type=Broadcast Route=%s, Data=%+v\"", ",", "route", ",", "v", ")", "\n", "members", ",", "err", ":=", "GroupMembers", "(", "ctx", ",", "groupName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "sendDataToMembers", "(", "members", ",", "frontendType", ",", "route", ",", "v", ")", "\n", "}" ]
// GroupBroadcast pushes the message to all members inside group
[ "GroupBroadcast", "pushes", "the", "message", "to", "all", "members", "inside", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L64-L72
train
topfreegames/pitaya
group.go
GroupContainsMember
func GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { if uid == "" { return false, constants.ErrEmptyUID } return groupServiceInstance.GroupContainsMember(ctx, groupName, uid) }
go
func GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { if uid == "" { return false, constants.ErrEmptyUID } return groupServiceInstance.GroupContainsMember(ctx, groupName, uid) }
[ "func", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "uid", "==", "\"\"", "{", "return", "false", ",", "constants", ".", "ErrEmptyUID", "\n", "}", "\n", "return", "groupServiceInstance", ".", "GroupContainsMember", "(", "ctx", ",", "groupName", ",", "uid", ")", "\n", "}" ]
// GroupContainsMember checks whether an UID is contained in group or not
[ "GroupContainsMember", "checks", "whether", "an", "UID", "is", "contained", "in", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L84-L89
train
topfreegames/pitaya
group.go
GroupRemoveAll
func GroupRemoveAll(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRemoveAll(ctx, groupName) }
go
func GroupRemoveAll(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRemoveAll(ctx, groupName) }
[ "func", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupRemoveAll", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupRemoveAll clears all UIDs
[ "GroupRemoveAll", "clears", "all", "UIDs" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L107-L109
train
topfreegames/pitaya
group.go
GroupRenewTTL
func GroupRenewTTL(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRenewTTL(ctx, groupName) }
go
func GroupRenewTTL(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRenewTTL(ctx, groupName) }
[ "func", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupRenewTTL", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupRenewTTL renews group with the initial TTL
[ "GroupRenewTTL", "renews", "group", "with", "the", "initial", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L117-L119
train
topfreegames/pitaya
group.go
GroupDelete
func GroupDelete(ctx context.Context, groupName string) error { return groupServiceInstance.GroupDelete(ctx, groupName) }
go
func GroupDelete(ctx context.Context, groupName string) error { return groupServiceInstance.GroupDelete(ctx, groupName) }
[ "func", "GroupDelete", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupDelete", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupDelete deletes whole group, including UIDs and base group
[ "GroupDelete", "deletes", "whole", "group", "including", "UIDs", "and", "base", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L122-L124
train
topfreegames/pitaya
push.go
SendPushToUsers
func SendPushToUsers(route string, v interface{}, uids []string, frontendType string) ([]string, error) { data, err := util.SerializeOrRaw(app.serializer, v) if err != nil { return uids, err } if !app.server.Frontend && frontendType == "" { return uids, constants.ErrFrontendTypeNotSpecified } var notPushedUids []string logger.Log.Debugf("Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d", route, v, frontendType, len(uids)) for _, uid := range uids { if s := session.GetSessionByUID(uid); s != nil && app.server.Type == frontendType { if err := s.Push(route, data); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("Session push message error, ID=%d, UID=%d, Error=%s", s.ID(), s.UID(), err.Error()) } } else if app.rpcClient != nil { push := &protos.Push{ Route: route, Uid: uid, Data: data, } if err = app.rpcClient.SendPush(uid, &cluster.Server{Type: frontendType}, push); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("RPCClient send message error, UID=%s, SvType=%s, Error=%s", uid, frontendType, err.Error()) } } else { notPushedUids = append(notPushedUids, uid) } } if len(notPushedUids) != 0 { return notPushedUids, constants.ErrPushingToUsers } return nil, nil }
go
func SendPushToUsers(route string, v interface{}, uids []string, frontendType string) ([]string, error) { data, err := util.SerializeOrRaw(app.serializer, v) if err != nil { return uids, err } if !app.server.Frontend && frontendType == "" { return uids, constants.ErrFrontendTypeNotSpecified } var notPushedUids []string logger.Log.Debugf("Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d", route, v, frontendType, len(uids)) for _, uid := range uids { if s := session.GetSessionByUID(uid); s != nil && app.server.Type == frontendType { if err := s.Push(route, data); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("Session push message error, ID=%d, UID=%d, Error=%s", s.ID(), s.UID(), err.Error()) } } else if app.rpcClient != nil { push := &protos.Push{ Route: route, Uid: uid, Data: data, } if err = app.rpcClient.SendPush(uid, &cluster.Server{Type: frontendType}, push); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("RPCClient send message error, UID=%s, SvType=%s, Error=%s", uid, frontendType, err.Error()) } } else { notPushedUids = append(notPushedUids, uid) } } if len(notPushedUids) != 0 { return notPushedUids, constants.ErrPushingToUsers } return nil, nil }
[ "func", "SendPushToUsers", "(", "route", "string", ",", "v", "interface", "{", "}", ",", "uids", "[", "]", "string", ",", "frontendType", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "data", ",", "err", ":=", "util", ".", "SerializeOrRaw", "(", "app", ".", "serializer", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "uids", ",", "err", "\n", "}", "\n", "if", "!", "app", ".", "server", ".", "Frontend", "&&", "frontendType", "==", "\"\"", "{", "return", "uids", ",", "constants", ".", "ErrFrontendTypeNotSpecified", "\n", "}", "\n", "var", "notPushedUids", "[", "]", "string", "\n", "logger", ".", "Log", ".", "Debugf", "(", "\"Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d\"", ",", "route", ",", "v", ",", "frontendType", ",", "len", "(", "uids", ")", ")", "\n", "for", "_", ",", "uid", ":=", "range", "uids", "{", "if", "s", ":=", "session", ".", "GetSessionByUID", "(", "uid", ")", ";", "s", "!=", "nil", "&&", "app", ".", "server", ".", "Type", "==", "frontendType", "{", "if", "err", ":=", "s", ".", "Push", "(", "route", ",", "data", ")", ";", "err", "!=", "nil", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "logger", ".", "Log", ".", "Errorf", "(", "\"Session push message error, ID=%d, UID=%d, Error=%s\"", ",", "s", ".", "ID", "(", ")", ",", "s", ".", "UID", "(", ")", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "if", "app", ".", "rpcClient", "!=", "nil", "{", "push", ":=", "&", "protos", ".", "Push", "{", "Route", ":", "route", ",", "Uid", ":", "uid", ",", "Data", ":", "data", ",", "}", "\n", "if", "err", "=", "app", ".", "rpcClient", ".", "SendPush", "(", "uid", ",", "&", "cluster", ".", "Server", "{", "Type", ":", "frontendType", "}", ",", "push", ")", ";", "err", "!=", "nil", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "logger", ".", "Log", ".", "Errorf", "(", "\"RPCClient send message error, UID=%s, SvType=%s, Error=%s\"", ",", "uid", ",", "frontendType", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "notPushedUids", ")", "!=", "0", "{", "return", "notPushedUids", ",", "constants", ".", "ErrPushingToUsers", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// SendPushToUsers sends a message to the given list of users
[ "SendPushToUsers", "sends", "a", "message", "to", "the", "given", "list", "of", "users" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/push.go#L33-L74
train
topfreegames/pitaya
cluster/grpc_rpc_server.go
Init
func (gs *GRPCServer) Init() error { port := gs.config.GetInt("pitaya.cluster.rpc.server.grpc.port") lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { return err } gs.grpcSv = grpc.NewServer() protos.RegisterPitayaServer(gs.grpcSv, gs.pitayaServer) go gs.grpcSv.Serve(lis) return nil }
go
func (gs *GRPCServer) Init() error { port := gs.config.GetInt("pitaya.cluster.rpc.server.grpc.port") lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { return err } gs.grpcSv = grpc.NewServer() protos.RegisterPitayaServer(gs.grpcSv, gs.pitayaServer) go gs.grpcSv.Serve(lis) return nil }
[ "func", "(", "gs", "*", "GRPCServer", ")", "Init", "(", ")", "error", "{", "port", ":=", "gs", ".", "config", ".", "GetInt", "(", "\"pitaya.cluster.rpc.server.grpc.port\"", ")", "\n", "lis", ",", "err", ":=", "net", ".", "Listen", "(", "\"tcp\"", ",", "fmt", ".", "Sprintf", "(", "\":%d\"", ",", "port", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "gs", ".", "grpcSv", "=", "grpc", ".", "NewServer", "(", ")", "\n", "protos", ".", "RegisterPitayaServer", "(", "gs", ".", "grpcSv", ",", "gs", ".", "pitayaServer", ")", "\n", "go", "gs", ".", "grpcSv", ".", "Serve", "(", "lis", ")", "\n", "return", "nil", "\n", "}" ]
// Init inits grpc rpc server
[ "Init", "inits", "grpc", "rpc", "server" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/grpc_rpc_server.go#L54-L64
train
topfreegames/pitaya
metrics/report.go
ReportTimingFromCtx
func ReportTimingFromCtx(ctx context.Context, reporters []Reporter, typ string, err error) { code := errors.CodeFromError(err) status := "ok" if err != nil { status = "failed" } if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) tags := getTags(ctx, map[string]string{ "route": route.(string), "status": status, "type": typ, "code": code, }) for _, r := range reporters { r.ReportSummary(ResponseTime, tags, float64(elapsed.Nanoseconds())) } } }
go
func ReportTimingFromCtx(ctx context.Context, reporters []Reporter, typ string, err error) { code := errors.CodeFromError(err) status := "ok" if err != nil { status = "failed" } if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) tags := getTags(ctx, map[string]string{ "route": route.(string), "status": status, "type": typ, "code": code, }) for _, r := range reporters { r.ReportSummary(ResponseTime, tags, float64(elapsed.Nanoseconds())) } } }
[ "func", "ReportTimingFromCtx", "(", "ctx", "context", ".", "Context", ",", "reporters", "[", "]", "Reporter", ",", "typ", "string", ",", "err", "error", ")", "{", "code", ":=", "errors", ".", "CodeFromError", "(", "err", ")", "\n", "status", ":=", "\"ok\"", "\n", "if", "err", "!=", "nil", "{", "status", "=", "\"failed\"", "\n", "}", "\n", "if", "len", "(", "reporters", ")", ">", "0", "{", "startTime", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "StartTimeKey", ")", "\n", "route", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RouteKey", ")", "\n", "elapsed", ":=", "time", ".", "Since", "(", "time", ".", "Unix", "(", "0", ",", "startTime", ".", "(", "int64", ")", ")", ")", "\n", "tags", ":=", "getTags", "(", "ctx", ",", "map", "[", "string", "]", "string", "{", "\"route\"", ":", "route", ".", "(", "string", ")", ",", "\"status\"", ":", "status", ",", "\"type\"", ":", "typ", ",", "\"code\"", ":", "code", ",", "}", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportSummary", "(", "ResponseTime", ",", "tags", ",", "float64", "(", "elapsed", ".", "Nanoseconds", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ReportTimingFromCtx reports the latency from the context
[ "ReportTimingFromCtx", "reports", "the", "latency", "from", "the", "context" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L35-L55
train
topfreegames/pitaya
metrics/report.go
ReportMessageProcessDelayFromCtx
func ReportMessageProcessDelayFromCtx(ctx context.Context, reporters []Reporter, typ string) { if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) tags := getTags(ctx, map[string]string{ "route": route.(string), "type": typ, }) for _, r := range reporters { r.ReportSummary(ProcessDelay, tags, float64(elapsed.Nanoseconds())) } } }
go
func ReportMessageProcessDelayFromCtx(ctx context.Context, reporters []Reporter, typ string) { if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) tags := getTags(ctx, map[string]string{ "route": route.(string), "type": typ, }) for _, r := range reporters { r.ReportSummary(ProcessDelay, tags, float64(elapsed.Nanoseconds())) } } }
[ "func", "ReportMessageProcessDelayFromCtx", "(", "ctx", "context", ".", "Context", ",", "reporters", "[", "]", "Reporter", ",", "typ", "string", ")", "{", "if", "len", "(", "reporters", ")", ">", "0", "{", "startTime", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "StartTimeKey", ")", "\n", "elapsed", ":=", "time", ".", "Since", "(", "time", ".", "Unix", "(", "0", ",", "startTime", ".", "(", "int64", ")", ")", ")", "\n", "route", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RouteKey", ")", "\n", "tags", ":=", "getTags", "(", "ctx", ",", "map", "[", "string", "]", "string", "{", "\"route\"", ":", "route", ".", "(", "string", ")", ",", "\"type\"", ":", "typ", ",", "}", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportSummary", "(", "ProcessDelay", ",", "tags", ",", "float64", "(", "elapsed", ".", "Nanoseconds", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ReportMessageProcessDelayFromCtx reports the delay to process the messages
[ "ReportMessageProcessDelayFromCtx", "reports", "the", "delay", "to", "process", "the", "messages" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L58-L71
train
topfreegames/pitaya
metrics/report.go
ReportNumberOfConnectedClients
func ReportNumberOfConnectedClients(reporters []Reporter, number int64) { for _, r := range reporters { r.ReportGauge(ConnectedClients, map[string]string{}, float64(number)) } }
go
func ReportNumberOfConnectedClients(reporters []Reporter, number int64) { for _, r := range reporters { r.ReportGauge(ConnectedClients, map[string]string{}, float64(number)) } }
[ "func", "ReportNumberOfConnectedClients", "(", "reporters", "[", "]", "Reporter", ",", "number", "int64", ")", "{", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportGauge", "(", "ConnectedClients", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "number", ")", ")", "\n", "}", "\n", "}" ]
// ReportNumberOfConnectedClients reports the number of connected clients
[ "ReportNumberOfConnectedClients", "reports", "the", "number", "of", "connected", "clients" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L74-L78
train
topfreegames/pitaya
metrics/report.go
ReportSysMetrics
func ReportSysMetrics(reporters []Reporter, period time.Duration) { for { for _, r := range reporters { num := runtime.NumGoroutine() m := &runtime.MemStats{} runtime.ReadMemStats(m) r.ReportGauge(Goroutines, map[string]string{}, float64(num)) r.ReportGauge(HeapSize, map[string]string{}, float64(m.Alloc)) r.ReportGauge(HeapObjects, map[string]string{}, float64(m.HeapObjects)) } time.Sleep(period) } }
go
func ReportSysMetrics(reporters []Reporter, period time.Duration) { for { for _, r := range reporters { num := runtime.NumGoroutine() m := &runtime.MemStats{} runtime.ReadMemStats(m) r.ReportGauge(Goroutines, map[string]string{}, float64(num)) r.ReportGauge(HeapSize, map[string]string{}, float64(m.Alloc)) r.ReportGauge(HeapObjects, map[string]string{}, float64(m.HeapObjects)) } time.Sleep(period) } }
[ "func", "ReportSysMetrics", "(", "reporters", "[", "]", "Reporter", ",", "period", "time", ".", "Duration", ")", "{", "for", "{", "for", "_", ",", "r", ":=", "range", "reporters", "{", "num", ":=", "runtime", ".", "NumGoroutine", "(", ")", "\n", "m", ":=", "&", "runtime", ".", "MemStats", "{", "}", "\n", "runtime", ".", "ReadMemStats", "(", "m", ")", "\n", "r", ".", "ReportGauge", "(", "Goroutines", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "num", ")", ")", "\n", "r", ".", "ReportGauge", "(", "HeapSize", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "m", ".", "Alloc", ")", ")", "\n", "r", ".", "ReportGauge", "(", "HeapObjects", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "m", ".", "HeapObjects", ")", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "period", ")", "\n", "}", "\n", "}" ]
// ReportSysMetrics reports sys metrics
[ "ReportSysMetrics", "reports", "sys", "metrics" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L81-L95
train
topfreegames/pitaya
groups/memory_group_service.go
NewMemoryGroupService
func NewMemoryGroupService(conf *config.Config) *MemoryGroupService { memoryOnce.Do(func() { memoryGroups = make(map[string]*MemoryGroup) go groupTTLCleanup(conf) }) return &MemoryGroupService{} }
go
func NewMemoryGroupService(conf *config.Config) *MemoryGroupService { memoryOnce.Do(func() { memoryGroups = make(map[string]*MemoryGroup) go groupTTLCleanup(conf) }) return &MemoryGroupService{} }
[ "func", "NewMemoryGroupService", "(", "conf", "*", "config", ".", "Config", ")", "*", "MemoryGroupService", "{", "memoryOnce", ".", "Do", "(", "func", "(", ")", "{", "memoryGroups", "=", "make", "(", "map", "[", "string", "]", "*", "MemoryGroup", ")", "\n", "go", "groupTTLCleanup", "(", "conf", ")", "\n", "}", ")", "\n", "return", "&", "MemoryGroupService", "{", "}", "\n", "}" ]
// NewMemoryGroupService returns a new group instance
[ "NewMemoryGroupService", "returns", "a", "new", "group", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L30-L36
train
topfreegames/pitaya
groups/memory_group_service.go
GroupCreate
func (c *MemoryGroupService) GroupCreate(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{} return nil }
go
func (c *MemoryGroupService) GroupCreate(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupCreate", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", ";", "ok", "{", "return", "constants", ".", "ErrGroupAlreadyExists", "\n", "}", "\n", "memoryGroups", "[", "groupName", "]", "=", "&", "MemoryGroup", "{", "}", "\n", "return", "nil", "\n", "}" ]
// GroupCreate creates a group without TTL
[ "GroupCreate", "creates", "a", "group", "without", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L51-L61
train
topfreegames/pitaya
groups/memory_group_service.go
GroupCreateWithTTL
func (c *MemoryGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{LastRefresh: time.Now().UnixNano(), TTL: ttlTime.Nanoseconds()} return nil }
go
func (c *MemoryGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{LastRefresh: time.Now().UnixNano(), TTL: ttlTime.Nanoseconds()} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupCreateWithTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ",", "ttlTime", "time", ".", "Duration", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", ";", "ok", "{", "return", "constants", ".", "ErrGroupAlreadyExists", "\n", "}", "\n", "memoryGroups", "[", "groupName", "]", "=", "&", "MemoryGroup", "{", "LastRefresh", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "TTL", ":", "ttlTime", ".", "Nanoseconds", "(", ")", "}", "\n", "return", "nil", "\n", "}" ]
// GroupCreateWithTTL creates a group with TTL, which the go routine will clean later
[ "GroupCreateWithTTL", "creates", "a", "group", "with", "TTL", "which", "the", "go", "routine", "will", "clean", "later" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L64-L74
train
topfreegames/pitaya
groups/memory_group_service.go
GroupMembers
func (c *MemoryGroupService) GroupMembers(ctx context.Context, groupName string) ([]string, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return nil, constants.ErrGroupNotFound } uids := make([]string, len(mg.Uids)) copy(uids, mg.Uids) return uids, nil }
go
func (c *MemoryGroupService) GroupMembers(ctx context.Context, groupName string) ([]string, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return nil, constants.ErrGroupNotFound } uids := make([]string, len(mg.Uids)) copy(uids, mg.Uids) return uids, nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupMembers", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "uids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "mg", ".", "Uids", ")", ")", "\n", "copy", "(", "uids", ",", "mg", ".", "Uids", ")", "\n", "return", "uids", ",", "nil", "\n", "}" ]
// GroupMembers returns all member's UID in given group
[ "GroupMembers", "returns", "all", "member", "s", "UID", "in", "given", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L77-L90
train
topfreegames/pitaya
groups/memory_group_service.go
GroupContainsMember
func (c *MemoryGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return false, constants.ErrGroupNotFound } _, contains := elementIndex(mg.Uids, uid) return contains, nil }
go
func (c *MemoryGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return false, constants.ErrGroupNotFound } _, contains := elementIndex(mg.Uids, uid) return contains, nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "false", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "_", ",", "contains", ":=", "elementIndex", "(", "mg", ".", "Uids", ",", "uid", ")", "\n", "return", "contains", ",", "nil", "\n", "}" ]
// GroupContainsMember check whether an UID is contained in given group or not
[ "GroupContainsMember", "check", "whether", "an", "UID", "is", "contained", "in", "given", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L93-L104
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRemoveMember
func (c *MemoryGroupService) GroupRemoveMember(ctx context.Context, groupName, uid string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } index, contains := elementIndex(mg.Uids, uid) if contains { mg.Uids[index] = mg.Uids[len(mg.Uids)-1] mg.Uids = mg.Uids[:len(mg.Uids)-1] memoryGroups[groupName] = mg return nil } return constants.ErrMemberNotFound }
go
func (c *MemoryGroupService) GroupRemoveMember(ctx context.Context, groupName, uid string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } index, contains := elementIndex(mg.Uids, uid) if contains { mg.Uids[index] = mg.Uids[len(mg.Uids)-1] mg.Uids = mg.Uids[:len(mg.Uids)-1] memoryGroups[groupName] = mg return nil } return constants.ErrMemberNotFound }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRemoveMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "index", ",", "contains", ":=", "elementIndex", "(", "mg", ".", "Uids", ",", "uid", ")", "\n", "if", "contains", "{", "mg", ".", "Uids", "[", "index", "]", "=", "mg", ".", "Uids", "[", "len", "(", "mg", ".", "Uids", ")", "-", "1", "]", "\n", "mg", ".", "Uids", "=", "mg", ".", "Uids", "[", ":", "len", "(", "mg", ".", "Uids", ")", "-", "1", "]", "\n", "memoryGroups", "[", "groupName", "]", "=", "mg", "\n", "return", "nil", "\n", "}", "\n", "return", "constants", ".", "ErrMemberNotFound", "\n", "}" ]
// GroupRemoveMember removes specific UID from group
[ "GroupRemoveMember", "removes", "specific", "UID", "from", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L127-L144
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRemoveAll
func (c *MemoryGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } mg.Uids = []string{} return nil }
go
func (c *MemoryGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } mg.Uids = []string{} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "mg", ".", "Uids", "=", "[", "]", "string", "{", "}", "\n", "return", "nil", "\n", "}" ]
// GroupRemoveAll clears all UIDs from group
[ "GroupRemoveAll", "clears", "all", "UIDs", "from", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L147-L158
train
topfreegames/pitaya
groups/memory_group_service.go
GroupDelete
func (c *MemoryGroupService) GroupDelete(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() _, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } delete(memoryGroups, groupName) return nil }
go
func (c *MemoryGroupService) GroupDelete(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() _, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } delete(memoryGroups, groupName) return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupDelete", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "delete", "(", "memoryGroups", ",", "groupName", ")", "\n", "return", "nil", "\n", "}" ]
// GroupDelete deletes the whole group, including members and base group
[ "GroupDelete", "deletes", "the", "whole", "group", "including", "members", "and", "base", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L161-L172
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRenewTTL
func (c *MemoryGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } if mg.TTL != 0 { mg.LastRefresh = time.Now().UnixNano() memoryGroups[groupName] = mg return nil } return constants.ErrMemoryTTLNotFound }
go
func (c *MemoryGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } if mg.TTL != 0 { mg.LastRefresh = time.Now().UnixNano() memoryGroups[groupName] = mg return nil } return constants.ErrMemoryTTLNotFound }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "if", "mg", ".", "TTL", "!=", "0", "{", "mg", ".", "LastRefresh", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "memoryGroups", "[", "groupName", "]", "=", "mg", "\n", "return", "nil", "\n", "}", "\n", "return", "constants", ".", "ErrMemoryTTLNotFound", "\n", "}" ]
// GroupRenewTTL will renew lease TTL
[ "GroupRenewTTL", "will", "renew", "lease", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L188-L203
train
topfreegames/pitaya
modules/binding_storage.go
NewETCDBindingStorage
func NewETCDBindingStorage(server *cluster.Server, conf *config.Config) *ETCDBindingStorage { b := &ETCDBindingStorage{ config: conf, thisServer: server, stopChan: make(chan struct{}), } b.configure() return b }
go
func NewETCDBindingStorage(server *cluster.Server, conf *config.Config) *ETCDBindingStorage { b := &ETCDBindingStorage{ config: conf, thisServer: server, stopChan: make(chan struct{}), } b.configure() return b }
[ "func", "NewETCDBindingStorage", "(", "server", "*", "cluster", ".", "Server", ",", "conf", "*", "config", ".", "Config", ")", "*", "ETCDBindingStorage", "{", "b", ":=", "&", "ETCDBindingStorage", "{", "config", ":", "conf", ",", "thisServer", ":", "server", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "b", ".", "configure", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewETCDBindingStorage returns a new instance of BindingStorage
[ "NewETCDBindingStorage", "returns", "a", "new", "instance", "of", "BindingStorage" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L52-L60
train
topfreegames/pitaya
modules/binding_storage.go
PutBinding
func (b *ETCDBindingStorage) PutBinding(uid string) error { _, err := b.cli.Put(context.Background(), getUserBindingKey(uid, b.thisServer.Type), b.thisServer.ID, clientv3.WithLease(b.leaseID)) return err }
go
func (b *ETCDBindingStorage) PutBinding(uid string) error { _, err := b.cli.Put(context.Background(), getUserBindingKey(uid, b.thisServer.Type), b.thisServer.ID, clientv3.WithLease(b.leaseID)) return err }
[ "func", "(", "b", "*", "ETCDBindingStorage", ")", "PutBinding", "(", "uid", "string", ")", "error", "{", "_", ",", "err", ":=", "b", ".", "cli", ".", "Put", "(", "context", ".", "Background", "(", ")", ",", "getUserBindingKey", "(", "uid", ",", "b", ".", "thisServer", ".", "Type", ")", ",", "b", ".", "thisServer", ".", "ID", ",", "clientv3", ".", "WithLease", "(", "b", ".", "leaseID", ")", ")", "\n", "return", "err", "\n", "}" ]
// PutBinding puts the binding info into etcd
[ "PutBinding", "puts", "the", "binding", "info", "into", "etcd" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L74-L77
train
topfreegames/pitaya
modules/binding_storage.go
Init
func (b *ETCDBindingStorage) Init() error { var cli *clientv3.Client var err error if b.cli == nil { cli, err = clientv3.New(clientv3.Config{ Endpoints: b.etcdEndpoints, DialTimeout: b.etcdDialTimeout, }) if err != nil { return err } b.cli = cli } // namespaced etcd :) b.cli.KV = namespace.NewKV(b.cli.KV, b.etcdPrefix) err = b.bootstrapLease() if err != nil { return err } if b.thisServer.Frontend { b.setupOnSessionCloseCB() b.setupOnAfterSessionBindCB() } return nil }
go
func (b *ETCDBindingStorage) Init() error { var cli *clientv3.Client var err error if b.cli == nil { cli, err = clientv3.New(clientv3.Config{ Endpoints: b.etcdEndpoints, DialTimeout: b.etcdDialTimeout, }) if err != nil { return err } b.cli = cli } // namespaced etcd :) b.cli.KV = namespace.NewKV(b.cli.KV, b.etcdPrefix) err = b.bootstrapLease() if err != nil { return err } if b.thisServer.Frontend { b.setupOnSessionCloseCB() b.setupOnAfterSessionBindCB() } return nil }
[ "func", "(", "b", "*", "ETCDBindingStorage", ")", "Init", "(", ")", "error", "{", "var", "cli", "*", "clientv3", ".", "Client", "\n", "var", "err", "error", "\n", "if", "b", ".", "cli", "==", "nil", "{", "cli", ",", "err", "=", "clientv3", ".", "New", "(", "clientv3", ".", "Config", "{", "Endpoints", ":", "b", ".", "etcdEndpoints", ",", "DialTimeout", ":", "b", ".", "etcdDialTimeout", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "cli", "=", "cli", "\n", "}", "\n", "b", ".", "cli", ".", "KV", "=", "namespace", ".", "NewKV", "(", "b", ".", "cli", ".", "KV", ",", "b", ".", "etcdPrefix", ")", "\n", "err", "=", "b", ".", "bootstrapLease", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "b", ".", "thisServer", ".", "Frontend", "{", "b", ".", "setupOnSessionCloseCB", "(", ")", "\n", "b", ".", "setupOnAfterSessionBindCB", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init starts the binding storage module
[ "Init", "starts", "the", "binding", "storage", "module" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L159-L185
train
topfreegames/pitaya
modules/api_docs_gen.go
NewAPIDocsGen
func NewAPIDocsGen(basePath string, services []*component.Service) *APIDocsGen { return &APIDocsGen{ basePath: basePath, services: services, } }
go
func NewAPIDocsGen(basePath string, services []*component.Service) *APIDocsGen { return &APIDocsGen{ basePath: basePath, services: services, } }
[ "func", "NewAPIDocsGen", "(", "basePath", "string", ",", "services", "[", "]", "*", "component", ".", "Service", ")", "*", "APIDocsGen", "{", "return", "&", "APIDocsGen", "{", "basePath", ":", "basePath", ",", "services", ":", "services", ",", "}", "\n", "}" ]
// NewAPIDocsGen creates a new APIDocsGen
[ "NewAPIDocsGen", "creates", "a", "new", "APIDocsGen" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/api_docs_gen.go#L36-L41
train
topfreegames/pitaya
modules/api_docs_gen.go
Init
func (a *APIDocsGen) Init() error { for _, s := range a.services { logger.Log.Infof("loaded svc: %s", s.Name) } return nil }
go
func (a *APIDocsGen) Init() error { for _, s := range a.services { logger.Log.Infof("loaded svc: %s", s.Name) } return nil }
[ "func", "(", "a", "*", "APIDocsGen", ")", "Init", "(", ")", "error", "{", "for", "_", ",", "s", ":=", "range", "a", ".", "services", "{", "logger", ".", "Log", ".", "Infof", "(", "\"loaded svc: %s\"", ",", "s", ".", "Name", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init is called on init method
[ "Init", "is", "called", "on", "init", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/api_docs_gen.go#L44-L49
train
topfreegames/pitaya
tracing/jaeger/config.go
Configure
func Configure(options Options) (io.Closer, error) { cfg := config.Configuration{ Disabled: options.Disabled, Sampler: &config.SamplerConfig{ Type: jaeger.SamplerTypeProbabilistic, Param: options.Probability, }, } return cfg.InitGlobalTracer(options.ServiceName) }
go
func Configure(options Options) (io.Closer, error) { cfg := config.Configuration{ Disabled: options.Disabled, Sampler: &config.SamplerConfig{ Type: jaeger.SamplerTypeProbabilistic, Param: options.Probability, }, } return cfg.InitGlobalTracer(options.ServiceName) }
[ "func", "Configure", "(", "options", "Options", ")", "(", "io", ".", "Closer", ",", "error", ")", "{", "cfg", ":=", "config", ".", "Configuration", "{", "Disabled", ":", "options", ".", "Disabled", ",", "Sampler", ":", "&", "config", ".", "SamplerConfig", "{", "Type", ":", "jaeger", ".", "SamplerTypeProbabilistic", ",", "Param", ":", "options", ".", "Probability", ",", "}", ",", "}", "\n", "return", "cfg", ".", "InitGlobalTracer", "(", "options", ".", "ServiceName", ")", "\n", "}" ]
// Configure configures a global Jaeger tracer
[ "Configure", "configures", "a", "global", "Jaeger", "tracer" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/jaeger/config.go#L40-L50
train
topfreegames/pitaya
config/config.go
NewConfig
func NewConfig(cfgs ...*viper.Viper) *Config { var cfg *viper.Viper if len(cfgs) > 0 { cfg = cfgs[0] } else { cfg = viper.New() } cfg.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) cfg.AutomaticEnv() c := &Config{config: cfg} c.fillDefaultValues() return c }
go
func NewConfig(cfgs ...*viper.Viper) *Config { var cfg *viper.Viper if len(cfgs) > 0 { cfg = cfgs[0] } else { cfg = viper.New() } cfg.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) cfg.AutomaticEnv() c := &Config{config: cfg} c.fillDefaultValues() return c }
[ "func", "NewConfig", "(", "cfgs", "...", "*", "viper", ".", "Viper", ")", "*", "Config", "{", "var", "cfg", "*", "viper", ".", "Viper", "\n", "if", "len", "(", "cfgs", ")", ">", "0", "{", "cfg", "=", "cfgs", "[", "0", "]", "\n", "}", "else", "{", "cfg", "=", "viper", ".", "New", "(", ")", "\n", "}", "\n", "cfg", ".", "SetEnvKeyReplacer", "(", "strings", ".", "NewReplacer", "(", "\".\"", ",", "\"_\"", ")", ")", "\n", "cfg", ".", "AutomaticEnv", "(", ")", "\n", "c", ":=", "&", "Config", "{", "config", ":", "cfg", "}", "\n", "c", ".", "fillDefaultValues", "(", ")", "\n", "return", "c", "\n", "}" ]
// NewConfig creates a new config with a given viper config if given
[ "NewConfig", "creates", "a", "new", "config", "with", "a", "given", "viper", "config", "if", "given" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L36-L49
train
topfreegames/pitaya
config/config.go
GetDuration
func (c *Config) GetDuration(s string) time.Duration { return c.config.GetDuration(s) }
go
func (c *Config) GetDuration(s string) time.Duration { return c.config.GetDuration(s) }
[ "func", "(", "c", "*", "Config", ")", "GetDuration", "(", "s", "string", ")", "time", ".", "Duration", "{", "return", "c", ".", "config", ".", "GetDuration", "(", "s", ")", "\n", "}" ]
// GetDuration returns a duration from the inner config
[ "GetDuration", "returns", "a", "duration", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L128-L130
train
topfreegames/pitaya
config/config.go
GetString
func (c *Config) GetString(s string) string { return c.config.GetString(s) }
go
func (c *Config) GetString(s string) string { return c.config.GetString(s) }
[ "func", "(", "c", "*", "Config", ")", "GetString", "(", "s", "string", ")", "string", "{", "return", "c", ".", "config", ".", "GetString", "(", "s", ")", "\n", "}" ]
// GetString returns a string from the inner config
[ "GetString", "returns", "a", "string", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L133-L135
train
topfreegames/pitaya
config/config.go
GetInt
func (c *Config) GetInt(s string) int { return c.config.GetInt(s) }
go
func (c *Config) GetInt(s string) int { return c.config.GetInt(s) }
[ "func", "(", "c", "*", "Config", ")", "GetInt", "(", "s", "string", ")", "int", "{", "return", "c", ".", "config", ".", "GetInt", "(", "s", ")", "\n", "}" ]
// GetInt returns an int from the inner config
[ "GetInt", "returns", "an", "int", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L138-L140
train
topfreegames/pitaya
config/config.go
GetBool
func (c *Config) GetBool(s string) bool { return c.config.GetBool(s) }
go
func (c *Config) GetBool(s string) bool { return c.config.GetBool(s) }
[ "func", "(", "c", "*", "Config", ")", "GetBool", "(", "s", "string", ")", "bool", "{", "return", "c", ".", "config", ".", "GetBool", "(", "s", ")", "\n", "}" ]
// GetBool returns an boolean from the inner config
[ "GetBool", "returns", "an", "boolean", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L143-L145
train
topfreegames/pitaya
config/config.go
GetStringSlice
func (c *Config) GetStringSlice(s string) []string { return c.config.GetStringSlice(s) }
go
func (c *Config) GetStringSlice(s string) []string { return c.config.GetStringSlice(s) }
[ "func", "(", "c", "*", "Config", ")", "GetStringSlice", "(", "s", "string", ")", "[", "]", "string", "{", "return", "c", ".", "config", ".", "GetStringSlice", "(", "s", ")", "\n", "}" ]
// GetStringSlice returns a string slice from the inner config
[ "GetStringSlice", "returns", "a", "string", "slice", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L148-L150
train
topfreegames/pitaya
config/config.go
GetStringMapString
func (c *Config) GetStringMapString(s string) map[string]string { return c.config.GetStringMapString(s) }
go
func (c *Config) GetStringMapString(s string) map[string]string { return c.config.GetStringMapString(s) }
[ "func", "(", "c", "*", "Config", ")", "GetStringMapString", "(", "s", "string", ")", "map", "[", "string", "]", "string", "{", "return", "c", ".", "config", ".", "GetStringMapString", "(", "s", ")", "\n", "}" ]
// GetStringMapString returns a string map string from the inner config
[ "GetStringMapString", "returns", "a", "string", "map", "string", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L158-L160
train
topfreegames/pitaya
config/config.go
UnmarshalKey
func (c *Config) UnmarshalKey(s string, v interface{}) error { return c.config.UnmarshalKey(s, v) }
go
func (c *Config) UnmarshalKey(s string, v interface{}) error { return c.config.UnmarshalKey(s, v) }
[ "func", "(", "c", "*", "Config", ")", "UnmarshalKey", "(", "s", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "config", ".", "UnmarshalKey", "(", "s", ",", "v", ")", "\n", "}" ]
// UnmarshalKey unmarshals key into v
[ "UnmarshalKey", "unmarshals", "key", "into", "v" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L163-L165
train
topfreegames/pitaya
groups/etcd_group_service.go
NewEtcdGroupService
func NewEtcdGroupService(conf *config.Config, clientOrNil *clientv3.Client) (*EtcdGroupService, error) { err := initClientInstance(conf, clientOrNil) if err != nil { return nil, err } return &EtcdGroupService{}, err }
go
func NewEtcdGroupService(conf *config.Config, clientOrNil *clientv3.Client) (*EtcdGroupService, error) { err := initClientInstance(conf, clientOrNil) if err != nil { return nil, err } return &EtcdGroupService{}, err }
[ "func", "NewEtcdGroupService", "(", "conf", "*", "config", ".", "Config", ",", "clientOrNil", "*", "clientv3", ".", "Client", ")", "(", "*", "EtcdGroupService", ",", "error", ")", "{", "err", ":=", "initClientInstance", "(", "conf", ",", "clientOrNil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "EtcdGroupService", "{", "}", ",", "err", "\n", "}" ]
// NewEtcdGroupService returns a new group instance
[ "NewEtcdGroupService", "returns", "a", "new", "group", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L28-L34
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupCreate
func (c *EtcdGroupService) GroupCreate(ctx context.Context, groupName string) error { return c.createGroup(ctx, groupName, 0) }
go
func (c *EtcdGroupService) GroupCreate(ctx context.Context, groupName string) error { return c.createGroup(ctx, groupName, 0) }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupCreate", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "c", ".", "createGroup", "(", "ctx", ",", "groupName", ",", "0", ")", "\n", "}" ]
// GroupCreate creates a group struct inside ETCD, without TTL
[ "GroupCreate", "creates", "a", "group", "struct", "inside", "ETCD", "without", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L114-L116
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupCreateWithTTL
func (c *EtcdGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() lease, err := clientInstance.Grant(ctxT, int64(ttlTime.Seconds())) if err != nil { return err } return c.createGroup(ctx, groupName, lease.ID) }
go
func (c *EtcdGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() lease, err := clientInstance.Grant(ctxT, int64(ttlTime.Seconds())) if err != nil { return err } return c.createGroup(ctx, groupName, lease.ID) }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupCreateWithTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ",", "ttlTime", "time", ".", "Duration", ")", "error", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "lease", ",", "err", ":=", "clientInstance", ".", "Grant", "(", "ctxT", ",", "int64", "(", "ttlTime", ".", "Seconds", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "createGroup", "(", "ctx", ",", "groupName", ",", "lease", ".", "ID", ")", "\n", "}" ]
// GroupCreateWithTTL creates a group struct inside ETCD, with TTL, using leaseID
[ "GroupCreateWithTTL", "creates", "a", "group", "struct", "inside", "ETCD", "with", "TTL", "using", "leaseID" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L119-L127
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupContainsMember
func (c *EtcdGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpGet(memberKey(groupName, uid), clientv3.WithCountOnly())). Commit() if err != nil { return false, err } if !etcdRes.Succeeded { return false, constants.ErrGroupNotFound } return etcdRes.Responses[0].GetResponseRange().GetCount() > 0, nil }
go
func (c *EtcdGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpGet(memberKey(groupName, uid), clientv3.WithCountOnly())). Commit() if err != nil { return false, err } if !etcdRes.Succeeded { return false, constants.ErrGroupNotFound } return etcdRes.Responses[0].GetResponseRange().GetCount() > 0, nil }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "etcdRes", ",", "err", ":=", "clientInstance", ".", "Txn", "(", "ctxT", ")", ".", "If", "(", "clientv3", ".", "Compare", "(", "clientv3", ".", "CreateRevision", "(", "groupKey", "(", "groupName", ")", ")", ",", "\">\"", ",", "0", ")", ")", ".", "Then", "(", "clientv3", ".", "OpGet", "(", "memberKey", "(", "groupName", ",", "uid", ")", ",", "clientv3", ".", "WithCountOnly", "(", ")", ")", ")", ".", "Commit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "!", "etcdRes", ".", "Succeeded", "{", "return", "false", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "return", "etcdRes", ".", "Responses", "[", "0", "]", ".", "GetResponseRange", "(", ")", ".", "GetCount", "(", ")", ">", "0", ",", "nil", "\n", "}" ]
// GroupContainsMember checks whether a UID is contained in current group or not
[ "GroupContainsMember", "checks", "whether", "a", "UID", "is", "contained", "in", "current", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L155-L170
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupRemoveAll
func (c *EtcdGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpDelete(memberKey(groupName, ""), clientv3.WithPrefix())). Commit() if err != nil { return err } if !etcdRes.Succeeded { return constants.ErrGroupNotFound } return nil }
go
func (c *EtcdGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpDelete(memberKey(groupName, ""), clientv3.WithPrefix())). Commit() if err != nil { return err } if !etcdRes.Succeeded { return constants.ErrGroupNotFound } return nil }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "etcdRes", ",", "err", ":=", "clientInstance", ".", "Txn", "(", "ctxT", ")", ".", "If", "(", "clientv3", ".", "Compare", "(", "clientv3", ".", "CreateRevision", "(", "groupKey", "(", "groupName", ")", ")", ",", "\">\"", ",", "0", ")", ")", ".", "Then", "(", "clientv3", ".", "OpDelete", "(", "memberKey", "(", "groupName", ",", "\"\"", ")", ",", "clientv3", ".", "WithPrefix", "(", ")", ")", ")", ".", "Commit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "etcdRes", ".", "Succeeded", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GroupRemoveAll clears all UIDs in the group
[ "GroupRemoveAll", "clears", "all", "UIDs", "in", "the", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L224-L239
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupRenewTTL
func (c *EtcdGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { kv, err := getGroupKV(ctx, groupName) if err != nil { return err } if kv.Lease != 0 { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() _, err = clientInstance.KeepAliveOnce(ctxT, clientv3.LeaseID(kv.Lease)) return err } return constants.ErrEtcdLeaseNotFound }
go
func (c *EtcdGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { kv, err := getGroupKV(ctx, groupName) if err != nil { return err } if kv.Lease != 0 { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() _, err = clientInstance.KeepAliveOnce(ctxT, clientv3.LeaseID(kv.Lease)) return err } return constants.ErrEtcdLeaseNotFound }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "kv", ",", "err", ":=", "getGroupKV", "(", "ctx", ",", "groupName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "kv", ".", "Lease", "!=", "0", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "err", "=", "clientInstance", ".", "KeepAliveOnce", "(", "ctxT", ",", "clientv3", ".", "LeaseID", "(", "kv", ".", "Lease", ")", ")", "\n", "return", "err", "\n", "}", "\n", "return", "constants", ".", "ErrEtcdLeaseNotFound", "\n", "}" ]
// GroupRenewTTL will renew ETCD lease TTL
[ "GroupRenewTTL", "will", "renew", "ETCD", "lease", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L272-L284
train
topfreegames/pitaya
worker/report.go
Report
func Report(reporters []metrics.Reporter, period time.Duration) { for { time.Sleep(period) workerStats := workers.GetStats() for _, r := range reporters { reportJobsRetry(r, workerStats.Retries) reportQueueSizes(r, workerStats.Enqueued) reportJobsTotal(r, workerStats.Failed, workerStats.Processed) } } }
go
func Report(reporters []metrics.Reporter, period time.Duration) { for { time.Sleep(period) workerStats := workers.GetStats() for _, r := range reporters { reportJobsRetry(r, workerStats.Retries) reportQueueSizes(r, workerStats.Enqueued) reportJobsTotal(r, workerStats.Failed, workerStats.Processed) } } }
[ "func", "Report", "(", "reporters", "[", "]", "metrics", ".", "Reporter", ",", "period", "time", ".", "Duration", ")", "{", "for", "{", "time", ".", "Sleep", "(", "period", ")", "\n", "workerStats", ":=", "workers", ".", "GetStats", "(", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "reportJobsRetry", "(", "r", ",", "workerStats", ".", "Retries", ")", "\n", "reportQueueSizes", "(", "r", ",", "workerStats", ".", "Enqueued", ")", "\n", "reportJobsTotal", "(", "r", ",", "workerStats", ".", "Failed", ",", "workerStats", ".", "Processed", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Report sends periodic of worker reports
[ "Report", "sends", "periodic", "of", "worker", "reports" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/report.go#L14-L25
train
topfreegames/pitaya
util/util.go
Pcall
func Pcall(method reflect.Method, args []reflect.Value) (rets interface{}, err error) { defer func() { if rec := recover(); rec != nil { // Try to use logger from context here to help trace error cause log := getLoggerFromArgs(args) log.Errorf("panic - pitaya/dispatch: %s: %v", method.Name, rec) log.Debugf("%s", debug.Stack()) if s, ok := rec.(string); ok { err = errors.New(s) } else { err = fmt.Errorf("rpc call internal error - %s: %v", method.Name, rec) } } }() r := method.Func.Call(args) // r can have 0 length in case of notify handlers // otherwise it will have 2 outputs: an interface and an error if len(r) == 2 { if v := r[1].Interface(); v != nil { err = v.(error) } else if !r[0].IsNil() { rets = r[0].Interface() } else { err = constants.ErrReplyShouldBeNotNull } } return }
go
func Pcall(method reflect.Method, args []reflect.Value) (rets interface{}, err error) { defer func() { if rec := recover(); rec != nil { // Try to use logger from context here to help trace error cause log := getLoggerFromArgs(args) log.Errorf("panic - pitaya/dispatch: %s: %v", method.Name, rec) log.Debugf("%s", debug.Stack()) if s, ok := rec.(string); ok { err = errors.New(s) } else { err = fmt.Errorf("rpc call internal error - %s: %v", method.Name, rec) } } }() r := method.Func.Call(args) // r can have 0 length in case of notify handlers // otherwise it will have 2 outputs: an interface and an error if len(r) == 2 { if v := r[1].Interface(); v != nil { err = v.(error) } else if !r[0].IsNil() { rets = r[0].Interface() } else { err = constants.ErrReplyShouldBeNotNull } } return }
[ "func", "Pcall", "(", "method", "reflect", ".", "Method", ",", "args", "[", "]", "reflect", ".", "Value", ")", "(", "rets", "interface", "{", "}", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "rec", ":=", "recover", "(", ")", ";", "rec", "!=", "nil", "{", "log", ":=", "getLoggerFromArgs", "(", "args", ")", "\n", "log", ".", "Errorf", "(", "\"panic - pitaya/dispatch: %s: %v\"", ",", "method", ".", "Name", ",", "rec", ")", "\n", "log", ".", "Debugf", "(", "\"%s\"", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "if", "s", ",", "ok", ":=", "rec", ".", "(", "string", ")", ";", "ok", "{", "err", "=", "errors", ".", "New", "(", "s", ")", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"rpc call internal error - %s: %v\"", ",", "method", ".", "Name", ",", "rec", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "r", ":=", "method", ".", "Func", ".", "Call", "(", "args", ")", "\n", "if", "len", "(", "r", ")", "==", "2", "{", "if", "v", ":=", "r", "[", "1", "]", ".", "Interface", "(", ")", ";", "v", "!=", "nil", "{", "err", "=", "v", ".", "(", "error", ")", "\n", "}", "else", "if", "!", "r", "[", "0", "]", ".", "IsNil", "(", ")", "{", "rets", "=", "r", "[", "0", "]", ".", "Interface", "(", ")", "\n", "}", "else", "{", "err", "=", "constants", ".", "ErrReplyShouldBeNotNull", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Pcall calls a method that returns an interface and an error and recovers in case of panic
[ "Pcall", "calls", "a", "method", "that", "returns", "an", "interface", "and", "an", "error", "and", "recovers", "in", "case", "of", "panic" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L61-L89
train
topfreegames/pitaya
util/util.go
SliceContainsString
func SliceContainsString(slice []string, str string) bool { for _, value := range slice { if value == str { return true } } return false }
go
func SliceContainsString(slice []string, str string) bool { for _, value := range slice { if value == str { return true } } return false }
[ "func", "SliceContainsString", "(", "slice", "[", "]", "string", ",", "str", "string", ")", "bool", "{", "for", "_", ",", "value", ":=", "range", "slice", "{", "if", "value", "==", "str", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// SliceContainsString returns true if a slice contains the string
[ "SliceContainsString", "returns", "true", "if", "a", "slice", "contains", "the", "string" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L92-L99
train
topfreegames/pitaya
util/util.go
SerializeOrRaw
func SerializeOrRaw(serializer serialize.Serializer, v interface{}) ([]byte, error) { if data, ok := v.([]byte); ok { return data, nil } data, err := serializer.Marshal(v) if err != nil { return nil, err } return data, nil }
go
func SerializeOrRaw(serializer serialize.Serializer, v interface{}) ([]byte, error) { if data, ok := v.([]byte); ok { return data, nil } data, err := serializer.Marshal(v) if err != nil { return nil, err } return data, nil }
[ "func", "SerializeOrRaw", "(", "serializer", "serialize", ".", "Serializer", ",", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "data", ",", "ok", ":=", "v", ".", "(", "[", "]", "byte", ")", ";", "ok", "{", "return", "data", ",", "nil", "\n", "}", "\n", "data", ",", "err", ":=", "serializer", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}" ]
// SerializeOrRaw serializes the interface if its not an array of bytes already
[ "SerializeOrRaw", "serializes", "the", "interface", "if", "its", "not", "an", "array", "of", "bytes", "already" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L102-L111
train
topfreegames/pitaya
util/util.go
GetErrorPayload
func GetErrorPayload(serializer serialize.Serializer, err error) ([]byte, error) { code := e.ErrUnknownCode msg := err.Error() metadata := map[string]string{} if val, ok := err.(*e.Error); ok { code = val.Code metadata = val.Metadata } errPayload := &protos.Error{ Code: code, Msg: msg, } if len(metadata) > 0 { errPayload.Metadata = metadata } return SerializeOrRaw(serializer, errPayload) }
go
func GetErrorPayload(serializer serialize.Serializer, err error) ([]byte, error) { code := e.ErrUnknownCode msg := err.Error() metadata := map[string]string{} if val, ok := err.(*e.Error); ok { code = val.Code metadata = val.Metadata } errPayload := &protos.Error{ Code: code, Msg: msg, } if len(metadata) > 0 { errPayload.Metadata = metadata } return SerializeOrRaw(serializer, errPayload) }
[ "func", "GetErrorPayload", "(", "serializer", "serialize", ".", "Serializer", ",", "err", "error", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "code", ":=", "e", ".", "ErrUnknownCode", "\n", "msg", ":=", "err", ".", "Error", "(", ")", "\n", "metadata", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "val", ",", "ok", ":=", "err", ".", "(", "*", "e", ".", "Error", ")", ";", "ok", "{", "code", "=", "val", ".", "Code", "\n", "metadata", "=", "val", ".", "Metadata", "\n", "}", "\n", "errPayload", ":=", "&", "protos", ".", "Error", "{", "Code", ":", "code", ",", "Msg", ":", "msg", ",", "}", "\n", "if", "len", "(", "metadata", ")", ">", "0", "{", "errPayload", ".", "Metadata", "=", "metadata", "\n", "}", "\n", "return", "SerializeOrRaw", "(", "serializer", ",", "errPayload", ")", "\n", "}" ]
// GetErrorPayload creates and serializes an error payload
[ "GetErrorPayload", "creates", "and", "serializes", "an", "error", "payload" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L120-L136
train
topfreegames/pitaya
util/util.go
ConvertProtoToMessageType
func ConvertProtoToMessageType(protoMsgType protos.MsgType) message.Type { var msgType message.Type switch protoMsgType { case protos.MsgType_MsgRequest: msgType = message.Request case protos.MsgType_MsgNotify: msgType = message.Notify } return msgType }
go
func ConvertProtoToMessageType(protoMsgType protos.MsgType) message.Type { var msgType message.Type switch protoMsgType { case protos.MsgType_MsgRequest: msgType = message.Request case protos.MsgType_MsgNotify: msgType = message.Notify } return msgType }
[ "func", "ConvertProtoToMessageType", "(", "protoMsgType", "protos", ".", "MsgType", ")", "message", ".", "Type", "{", "var", "msgType", "message", ".", "Type", "\n", "switch", "protoMsgType", "{", "case", "protos", ".", "MsgType_MsgRequest", ":", "msgType", "=", "message", ".", "Request", "\n", "case", "protos", ".", "MsgType_MsgNotify", ":", "msgType", "=", "message", ".", "Notify", "\n", "}", "\n", "return", "msgType", "\n", "}" ]
// ConvertProtoToMessageType converts a protos.MsgType to a message.Type
[ "ConvertProtoToMessageType", "converts", "a", "protos", ".", "MsgType", "to", "a", "message", ".", "Type" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L139-L148
train
topfreegames/pitaya
util/util.go
CtxWithDefaultLogger
func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Context { var defaultLogger logger.Logger logrusLogger, ok := logger.Log.(logrus.FieldLogger) if ok { requestID := pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey) if rID, ok := requestID.(string); ok { if rID == "" { requestID = uuid.New() } } else { requestID = uuid.New() } defaultLogger = logrusLogger.WithFields( logrus.Fields{ "route": route, "requestId": requestID, "userId": userID, }) } else { defaultLogger = logger.Log } return context.WithValue(ctx, constants.LoggerCtxKey, defaultLogger) }
go
func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Context { var defaultLogger logger.Logger logrusLogger, ok := logger.Log.(logrus.FieldLogger) if ok { requestID := pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey) if rID, ok := requestID.(string); ok { if rID == "" { requestID = uuid.New() } } else { requestID = uuid.New() } defaultLogger = logrusLogger.WithFields( logrus.Fields{ "route": route, "requestId": requestID, "userId": userID, }) } else { defaultLogger = logger.Log } return context.WithValue(ctx, constants.LoggerCtxKey, defaultLogger) }
[ "func", "CtxWithDefaultLogger", "(", "ctx", "context", ".", "Context", ",", "route", ",", "userID", "string", ")", "context", ".", "Context", "{", "var", "defaultLogger", "logger", ".", "Logger", "\n", "logrusLogger", ",", "ok", ":=", "logger", ".", "Log", ".", "(", "logrus", ".", "FieldLogger", ")", "\n", "if", "ok", "{", "requestID", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RequestIDKey", ")", "\n", "if", "rID", ",", "ok", ":=", "requestID", ".", "(", "string", ")", ";", "ok", "{", "if", "rID", "==", "\"\"", "{", "requestID", "=", "uuid", ".", "New", "(", ")", "\n", "}", "\n", "}", "else", "{", "requestID", "=", "uuid", ".", "New", "(", ")", "\n", "}", "\n", "defaultLogger", "=", "logrusLogger", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"route\"", ":", "route", ",", "\"requestId\"", ":", "requestID", ",", "\"userId\"", ":", "userID", ",", "}", ")", "\n", "}", "else", "{", "defaultLogger", "=", "logger", ".", "Log", "\n", "}", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "constants", ".", "LoggerCtxKey", ",", "defaultLogger", ")", "\n", "}" ]
// CtxWithDefaultLogger inserts a default logger on ctx to be used on handlers and remotes. // If using logrus, userId, route and requestId will be added as fields. // Otherwise the pitaya logger will be used as it is.
[ "CtxWithDefaultLogger", "inserts", "a", "default", "logger", "on", "ctx", "to", "be", "used", "on", "handlers", "and", "remotes", ".", "If", "using", "logrus", "userId", "route", "and", "requestId", "will", "be", "added", "as", "fields", ".", "Otherwise", "the", "pitaya", "logger", "will", "be", "used", "as", "it", "is", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L153-L176
train
topfreegames/pitaya
util/util.go
GetContextFromRequest
func GetContextFromRequest(req *protos.Request, serverID string) (context.Context, error) { ctx, err := pcontext.Decode(req.GetMetadata()) if err != nil { return nil, err } if ctx == nil { return nil, constants.ErrNoContextFound } tags := opentracing.Tags{ "local.id": serverID, "span.kind": "server", "peer.id": pcontext.GetFromPropagateCtx(ctx, constants.PeerIDKey), "peer.service": pcontext.GetFromPropagateCtx(ctx, constants.PeerServiceKey), "request.id": pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey), } parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } ctx = tracing.StartSpan(ctx, req.GetMsg().GetRoute(), tags, parent) ctx = CtxWithDefaultLogger(ctx, req.GetMsg().GetRoute(), "") return ctx, nil }
go
func GetContextFromRequest(req *protos.Request, serverID string) (context.Context, error) { ctx, err := pcontext.Decode(req.GetMetadata()) if err != nil { return nil, err } if ctx == nil { return nil, constants.ErrNoContextFound } tags := opentracing.Tags{ "local.id": serverID, "span.kind": "server", "peer.id": pcontext.GetFromPropagateCtx(ctx, constants.PeerIDKey), "peer.service": pcontext.GetFromPropagateCtx(ctx, constants.PeerServiceKey), "request.id": pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey), } parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } ctx = tracing.StartSpan(ctx, req.GetMsg().GetRoute(), tags, parent) ctx = CtxWithDefaultLogger(ctx, req.GetMsg().GetRoute(), "") return ctx, nil }
[ "func", "GetContextFromRequest", "(", "req", "*", "protos", ".", "Request", ",", "serverID", "string", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "ctx", ",", "err", ":=", "pcontext", ".", "Decode", "(", "req", ".", "GetMetadata", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ctx", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrNoContextFound", "\n", "}", "\n", "tags", ":=", "opentracing", ".", "Tags", "{", "\"local.id\"", ":", "serverID", ",", "\"span.kind\"", ":", "\"server\"", ",", "\"peer.id\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "PeerIDKey", ")", ",", "\"peer.service\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "PeerServiceKey", ")", ",", "\"request.id\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RequestIDKey", ")", ",", "}", "\n", "parent", ",", "err", ":=", "tracing", ".", "ExtractSpan", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Warnf", "(", "\"failed to retrieve parent span: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "ctx", "=", "tracing", ".", "StartSpan", "(", "ctx", ",", "req", ".", "GetMsg", "(", ")", ".", "GetRoute", "(", ")", ",", "tags", ",", "parent", ")", "\n", "ctx", "=", "CtxWithDefaultLogger", "(", "ctx", ",", "req", ".", "GetMsg", "(", ")", ".", "GetRoute", "(", ")", ",", "\"\"", ")", "\n", "return", "ctx", ",", "nil", "\n", "}" ]
// GetContextFromRequest gets the context from a request
[ "GetContextFromRequest", "gets", "the", "context", "from", "a", "request" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L179-L201
train
chrislusf/gleam
sql/sessionctx/variable/session.go
SetStatusFlag
func (s *SessionVars) SetStatusFlag(flag uint16, on bool) { if on { s.Status |= flag return } s.Status &= (^flag) }
go
func (s *SessionVars) SetStatusFlag(flag uint16, on bool) { if on { s.Status |= flag return } s.Status &= (^flag) }
[ "func", "(", "s", "*", "SessionVars", ")", "SetStatusFlag", "(", "flag", "uint16", ",", "on", "bool", ")", "{", "if", "on", "{", "s", ".", "Status", "|=", "flag", "\n", "return", "\n", "}", "\n", "s", ".", "Status", "&=", "(", "^", "flag", ")", "\n", "}" ]
// SetStatusFlag sets the session server status variable. // If on is ture sets the flag in session status, // otherwise removes the flag.
[ "SetStatusFlag", "sets", "the", "session", "server", "status", "variable", ".", "If", "on", "is", "ture", "sets", "the", "flag", "in", "session", "status", "otherwise", "removes", "the", "flag", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L160-L166
train
chrislusf/gleam
sql/sessionctx/variable/session.go
GetWarnings
func (sc *StatementContext) GetWarnings() []error { sc.mu.Lock() warns := make([]error, len(sc.mu.warnings)) copy(warns, sc.mu.warnings) sc.mu.Unlock() return warns }
go
func (sc *StatementContext) GetWarnings() []error { sc.mu.Lock() warns := make([]error, len(sc.mu.warnings)) copy(warns, sc.mu.warnings) sc.mu.Unlock() return warns }
[ "func", "(", "sc", "*", "StatementContext", ")", "GetWarnings", "(", ")", "[", "]", "error", "{", "sc", ".", "mu", ".", "Lock", "(", ")", "\n", "warns", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "sc", ".", "mu", ".", "warnings", ")", ")", "\n", "copy", "(", "warns", ",", "sc", ".", "mu", ".", "warnings", ")", "\n", "sc", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "warns", "\n", "}" ]
// GetWarnings gets warnings.
[ "GetWarnings", "gets", "warnings", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L240-L246
train
chrislusf/gleam
sql/sessionctx/variable/session.go
AppendWarning
func (sc *StatementContext) AppendWarning(warn error) { sc.mu.Lock() sc.mu.warnings = append(sc.mu.warnings, warn) sc.mu.Unlock() }
go
func (sc *StatementContext) AppendWarning(warn error) { sc.mu.Lock() sc.mu.warnings = append(sc.mu.warnings, warn) sc.mu.Unlock() }
[ "func", "(", "sc", "*", "StatementContext", ")", "AppendWarning", "(", "warn", "error", ")", "{", "sc", ".", "mu", ".", "Lock", "(", ")", "\n", "sc", ".", "mu", ".", "warnings", "=", "append", "(", "sc", ".", "mu", ".", "warnings", ",", "warn", ")", "\n", "sc", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// AppendWarning appends a warning.
[ "AppendWarning", "appends", "a", "warning", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L256-L260
train
chrislusf/gleam
sql/model/model.go
Clone
func (t *TableInfo) Clone() *TableInfo { nt := *t nt.Columns = make([]*ColumnInfo, len(t.Columns)) nt.Indices = make([]*IndexInfo, len(t.Indices)) for i := range t.Columns { nt.Columns[i] = t.Columns[i].Clone() } for i := range t.Indices { nt.Indices[i] = t.Indices[i].Clone() } return &nt }
go
func (t *TableInfo) Clone() *TableInfo { nt := *t nt.Columns = make([]*ColumnInfo, len(t.Columns)) nt.Indices = make([]*IndexInfo, len(t.Indices)) for i := range t.Columns { nt.Columns[i] = t.Columns[i].Clone() } for i := range t.Indices { nt.Indices[i] = t.Indices[i].Clone() } return &nt }
[ "func", "(", "t", "*", "TableInfo", ")", "Clone", "(", ")", "*", "TableInfo", "{", "nt", ":=", "*", "t", "\n", "nt", ".", "Columns", "=", "make", "(", "[", "]", "*", "ColumnInfo", ",", "len", "(", "t", ".", "Columns", ")", ")", "\n", "nt", ".", "Indices", "=", "make", "(", "[", "]", "*", "IndexInfo", ",", "len", "(", "t", ".", "Indices", ")", ")", "\n", "for", "i", ":=", "range", "t", ".", "Columns", "{", "nt", ".", "Columns", "[", "i", "]", "=", "t", ".", "Columns", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "for", "i", ":=", "range", "t", ".", "Indices", "{", "nt", ".", "Indices", "[", "i", "]", "=", "t", ".", "Indices", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "&", "nt", "\n", "}" ]
// Clone clones TableInfo.
[ "Clone", "clones", "TableInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L46-L60
train
chrislusf/gleam
sql/model/model.go
Clone
func (index *IndexInfo) Clone() *IndexInfo { ni := *index ni.Columns = make([]*IndexColumn, len(index.Columns)) for i := range index.Columns { ni.Columns[i] = index.Columns[i].Clone() } return &ni }
go
func (index *IndexInfo) Clone() *IndexInfo { ni := *index ni.Columns = make([]*IndexColumn, len(index.Columns)) for i := range index.Columns { ni.Columns[i] = index.Columns[i].Clone() } return &ni }
[ "func", "(", "index", "*", "IndexInfo", ")", "Clone", "(", ")", "*", "IndexInfo", "{", "ni", ":=", "*", "index", "\n", "ni", ".", "Columns", "=", "make", "(", "[", "]", "*", "IndexColumn", ",", "len", "(", "index", ".", "Columns", ")", ")", "\n", "for", "i", ":=", "range", "index", ".", "Columns", "{", "ni", ".", "Columns", "[", "i", "]", "=", "index", ".", "Columns", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "&", "ni", "\n", "}" ]
// Clone clones IndexInfo.
[ "Clone", "clones", "IndexInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L107-L114
train
chrislusf/gleam
sql/model/model.go
Clone
func (db *DBInfo) Clone() *DBInfo { newInfo := *db newInfo.Tables = make([]*TableInfo, len(db.Tables)) for i := range db.Tables { newInfo.Tables[i] = db.Tables[i].Clone() } return &newInfo }
go
func (db *DBInfo) Clone() *DBInfo { newInfo := *db newInfo.Tables = make([]*TableInfo, len(db.Tables)) for i := range db.Tables { newInfo.Tables[i] = db.Tables[i].Clone() } return &newInfo }
[ "func", "(", "db", "*", "DBInfo", ")", "Clone", "(", ")", "*", "DBInfo", "{", "newInfo", ":=", "*", "db", "\n", "newInfo", ".", "Tables", "=", "make", "(", "[", "]", "*", "TableInfo", ",", "len", "(", "db", ".", "Tables", ")", ")", "\n", "for", "i", ":=", "range", "db", ".", "Tables", "{", "newInfo", ".", "Tables", "[", "i", "]", "=", "db", ".", "Tables", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "&", "newInfo", "\n", "}" ]
// Clone clones DBInfo.
[ "Clone", "clones", "DBInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L123-L130
train
chrislusf/gleam
sql/model/model.go
NewCIStr
func NewCIStr(s string) (cs CIStr) { cs.O = s cs.L = strings.ToLower(s) return }
go
func NewCIStr(s string) (cs CIStr) { cs.O = s cs.L = strings.ToLower(s) return }
[ "func", "NewCIStr", "(", "s", "string", ")", "(", "cs", "CIStr", ")", "{", "cs", ".", "O", "=", "s", "\n", "cs", ".", "L", "=", "strings", ".", "ToLower", "(", "s", ")", "\n", "return", "\n", "}" ]
// NewCIStr creates a new CIStr.
[ "NewCIStr", "creates", "a", "new", "CIStr", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L144-L148
train
chrislusf/gleam
flow/dataset_output.go
Output
func (d *Dataset) Output(f func(io.Reader) error) *Dataset { step := d.Flow.AddAllToOneStep(d, nil) step.IsOnDriverSide = true step.Name = "Output" step.Function = func(readers []io.Reader, writers []io.Writer, stat *pb.InstructionStat) error { errChan := make(chan error, len(readers)) for i, reader := range readers { go func(i int, reader io.Reader) { errChan <- f(reader) }(i, reader) } for range readers { err := <-errChan if err != nil { fmt.Fprintf(os.Stderr, "Failed to process output: %v\n", err) return err } } return nil } return d }
go
func (d *Dataset) Output(f func(io.Reader) error) *Dataset { step := d.Flow.AddAllToOneStep(d, nil) step.IsOnDriverSide = true step.Name = "Output" step.Function = func(readers []io.Reader, writers []io.Writer, stat *pb.InstructionStat) error { errChan := make(chan error, len(readers)) for i, reader := range readers { go func(i int, reader io.Reader) { errChan <- f(reader) }(i, reader) } for range readers { err := <-errChan if err != nil { fmt.Fprintf(os.Stderr, "Failed to process output: %v\n", err) return err } } return nil } return d }
[ "func", "(", "d", "*", "Dataset", ")", "Output", "(", "f", "func", "(", "io", ".", "Reader", ")", "error", ")", "*", "Dataset", "{", "step", ":=", "d", ".", "Flow", ".", "AddAllToOneStep", "(", "d", ",", "nil", ")", "\n", "step", ".", "IsOnDriverSide", "=", "true", "\n", "step", ".", "Name", "=", "\"Output\"", "\n", "step", ".", "Function", "=", "func", "(", "readers", "[", "]", "io", ".", "Reader", ",", "writers", "[", "]", "io", ".", "Writer", ",", "stat", "*", "pb", ".", "InstructionStat", ")", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ",", "len", "(", "readers", ")", ")", "\n", "for", "i", ",", "reader", ":=", "range", "readers", "{", "go", "func", "(", "i", "int", ",", "reader", "io", ".", "Reader", ")", "{", "errChan", "<-", "f", "(", "reader", ")", "\n", "}", "(", "i", ",", "reader", ")", "\n", "}", "\n", "for", "range", "readers", "{", "err", ":=", "<-", "errChan", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"Failed to process output: %v\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Output concurrently collects outputs from previous step to the driver.
[ "Output", "concurrently", "collects", "outputs", "from", "previous", "step", "to", "the", "driver", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L17-L38
train
chrislusf/gleam
flow/dataset_output.go
Fprintf
func (d *Dataset) Fprintf(writer io.Writer, format string) *Dataset { fn := func(r io.Reader) error { w := bufio.NewWriter(writer) defer w.Flush() return util.Fprintf(w, r, format) } return d.Output(fn) }
go
func (d *Dataset) Fprintf(writer io.Writer, format string) *Dataset { fn := func(r io.Reader) error { w := bufio.NewWriter(writer) defer w.Flush() return util.Fprintf(w, r, format) } return d.Output(fn) }
[ "func", "(", "d", "*", "Dataset", ")", "Fprintf", "(", "writer", "io", ".", "Writer", ",", "format", "string", ")", "*", "Dataset", "{", "fn", ":=", "func", "(", "r", "io", ".", "Reader", ")", "error", "{", "w", ":=", "bufio", ".", "NewWriter", "(", "writer", ")", "\n", "defer", "w", ".", "Flush", "(", ")", "\n", "return", "util", ".", "Fprintf", "(", "w", ",", "r", ",", "format", ")", "\n", "}", "\n", "return", "d", ".", "Output", "(", "fn", ")", "\n", "}" ]
// Fprintf formats using the format for each row and writes to writer.
[ "Fprintf", "formats", "using", "the", "format", "for", "each", "row", "and", "writes", "to", "writer", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L41-L48
train
chrislusf/gleam
flow/dataset_output.go
Fprintlnf
func (d *Dataset) Fprintlnf(writer io.Writer, format string) *Dataset { return d.Fprintf(writer, format+"\n") }
go
func (d *Dataset) Fprintlnf(writer io.Writer, format string) *Dataset { return d.Fprintf(writer, format+"\n") }
[ "func", "(", "d", "*", "Dataset", ")", "Fprintlnf", "(", "writer", "io", ".", "Writer", ",", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "writer", ",", "format", "+", "\"\\n\"", ")", "\n", "}" ]
// Fprintlnf add "\n" at the end of each format
[ "Fprintlnf", "add", "\\", "n", "at", "the", "end", "of", "each", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L51-L53
train
chrislusf/gleam
flow/dataset_output.go
Printf
func (d *Dataset) Printf(format string) *Dataset { return d.Fprintf(os.Stdout, format) }
go
func (d *Dataset) Printf(format string) *Dataset { return d.Fprintf(os.Stdout, format) }
[ "func", "(", "d", "*", "Dataset", ")", "Printf", "(", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "format", ")", "\n", "}" ]
// Printf prints to os.Stdout in the specified format
[ "Printf", "prints", "to", "os", ".", "Stdout", "in", "the", "specified", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L56-L58
train
chrislusf/gleam
flow/dataset_output.go
Printlnf
func (d *Dataset) Printlnf(format string) *Dataset { return d.Fprintf(os.Stdout, format+"\n") }
go
func (d *Dataset) Printlnf(format string) *Dataset { return d.Fprintf(os.Stdout, format+"\n") }
[ "func", "(", "d", "*", "Dataset", ")", "Printlnf", "(", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "format", "+", "\"\\n\"", ")", "\n", "}" ]
// Printlnf prints to os.Stdout in the specified format, // adding an "\n" at the end of each format
[ "Printlnf", "prints", "to", "os", ".", "Stdout", "in", "the", "specified", "format", "adding", "an", "\\", "n", "at", "the", "end", "of", "each", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L62-L64
train
chrislusf/gleam
flow/dataset_output.go
SaveFirstRowTo
func (d *Dataset) SaveFirstRowTo(decodedObjects ...interface{}) *Dataset { fn := func(reader io.Reader) error { return util.TakeMessage(reader, 1, func(encodedBytes []byte) error { row, err := util.DecodeRow(encodedBytes) if err != nil { fmt.Fprintf(os.Stderr, "Failed to decode byte: %v\n", err) return err } var counter int for _, v := range row.K { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } for _, v := range row.V { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } return nil }) } return d.Output(fn) }
go
func (d *Dataset) SaveFirstRowTo(decodedObjects ...interface{}) *Dataset { fn := func(reader io.Reader) error { return util.TakeMessage(reader, 1, func(encodedBytes []byte) error { row, err := util.DecodeRow(encodedBytes) if err != nil { fmt.Fprintf(os.Stderr, "Failed to decode byte: %v\n", err) return err } var counter int for _, v := range row.K { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } for _, v := range row.V { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } return nil }) } return d.Output(fn) }
[ "func", "(", "d", "*", "Dataset", ")", "SaveFirstRowTo", "(", "decodedObjects", "...", "interface", "{", "}", ")", "*", "Dataset", "{", "fn", ":=", "func", "(", "reader", "io", ".", "Reader", ")", "error", "{", "return", "util", ".", "TakeMessage", "(", "reader", ",", "1", ",", "func", "(", "encodedBytes", "[", "]", "byte", ")", "error", "{", "row", ",", "err", ":=", "util", ".", "DecodeRow", "(", "encodedBytes", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"Failed to decode byte: %v\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "return", "err", "\n", "var", "counter", "int", "\n", "for", "_", ",", "v", ":=", "range", "row", ".", "K", "{", "if", "err", ":=", "setValueTo", "(", "v", ",", "decodedObjects", "[", "counter", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "counter", "++", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "row", ".", "V", "{", "if", "err", ":=", "setValueTo", "(", "v", ",", "decodedObjects", "[", "counter", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "counter", "++", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SaveFirstRowTo saves the first row's values into the operands.
[ "SaveFirstRowTo", "saves", "the", "first", "row", "s", "values", "into", "the", "operands", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L67-L93
train
chrislusf/gleam
sql/session.go
runStmt
func runStmt(ctx context.Context, s ast.Statement) (ast.RecordSet, error) { var err error var rs ast.RecordSet rs, err = s.Exec(ctx) return rs, errors.Trace(err) }
go
func runStmt(ctx context.Context, s ast.Statement) (ast.RecordSet, error) { var err error var rs ast.RecordSet rs, err = s.Exec(ctx) return rs, errors.Trace(err) }
[ "func", "runStmt", "(", "ctx", "context", ".", "Context", ",", "s", "ast", ".", "Statement", ")", "(", "ast", ".", "RecordSet", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "rs", "ast", ".", "RecordSet", "\n", "rs", ",", "err", "=", "s", ".", "Exec", "(", "ctx", ")", "\n", "return", "rs", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// runStmt executes the ast.Statement and commit or rollback the current transaction.
[ "runStmt", "executes", "the", "ast", ".", "Statement", "and", "commit", "or", "rollback", "the", "current", "transaction", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/session.go#L209-L214
train
chrislusf/gleam
flow/dataset_cogroup.go
CoGroupPartitionedSorted
func (this *Dataset) CoGroupPartitionedSorted(name string, that *Dataset, indexes []int) (ret *Dataset) { ret = this.Flow.NewNextDataset(len(this.Shards)) ret.IsPartitionedBy = indexes inputs := []*Dataset{this, that} step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewCoGroupPartitionedSorted(indexes)) return ret }
go
func (this *Dataset) CoGroupPartitionedSorted(name string, that *Dataset, indexes []int) (ret *Dataset) { ret = this.Flow.NewNextDataset(len(this.Shards)) ret.IsPartitionedBy = indexes inputs := []*Dataset{this, that} step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewCoGroupPartitionedSorted(indexes)) return ret }
[ "func", "(", "this", "*", "Dataset", ")", "CoGroupPartitionedSorted", "(", "name", "string", ",", "that", "*", "Dataset", ",", "indexes", "[", "]", "int", ")", "(", "ret", "*", "Dataset", ")", "{", "ret", "=", "this", ".", "Flow", ".", "NewNextDataset", "(", "len", "(", "this", ".", "Shards", ")", ")", "\n", "ret", ".", "IsPartitionedBy", "=", "indexes", "\n", "inputs", ":=", "[", "]", "*", "Dataset", "{", "this", ",", "that", "}", "\n", "step", ":=", "this", ".", "Flow", ".", "MergeDatasets1ShardTo1Step", "(", "inputs", ",", "ret", ")", "\n", "step", ".", "SetInstruction", "(", "name", ",", "instruction", ".", "NewCoGroupPartitionedSorted", "(", "indexes", ")", ")", "\n", "return", "ret", "\n", "}" ]
// CoGroupPartitionedSorted joins 2 datasets that are sharded // by the same key and already locally sorted within each shard.
[ "CoGroupPartitionedSorted", "joins", "2", "datasets", "that", "are", "sharded", "by", "the", "same", "key", "and", "already", "locally", "sorted", "within", "each", "shard", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_cogroup.go#L24-L32
train
chrislusf/gleam
sql/expression/aggregation.go
NewAggFunction
func NewAggFunction(funcType string, funcArgs []Expression, distinct bool) AggregationFunction { switch tp := strings.ToLower(funcType); tp { case ast.AggFuncSum: return &sumFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncCount: return &countFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncAvg: return &avgFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncGroupConcat: return &concatFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncMax: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: true} case ast.AggFuncMin: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: false} case ast.AggFuncFirstRow: return &firstRowFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} } return nil }
go
func NewAggFunction(funcType string, funcArgs []Expression, distinct bool) AggregationFunction { switch tp := strings.ToLower(funcType); tp { case ast.AggFuncSum: return &sumFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncCount: return &countFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncAvg: return &avgFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncGroupConcat: return &concatFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncMax: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: true} case ast.AggFuncMin: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: false} case ast.AggFuncFirstRow: return &firstRowFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} } return nil }
[ "func", "NewAggFunction", "(", "funcType", "string", ",", "funcArgs", "[", "]", "Expression", ",", "distinct", "bool", ")", "AggregationFunction", "{", "switch", "tp", ":=", "strings", ".", "ToLower", "(", "funcType", ")", ";", "tp", "{", "case", "ast", ".", "AggFuncSum", ":", "return", "&", "sumFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncCount", ":", "return", "&", "countFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncAvg", ":", "return", "&", "avgFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncGroupConcat", ":", "return", "&", "concatFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncMax", ":", "return", "&", "maxMinFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", ",", "isMax", ":", "true", "}", "\n", "case", "ast", ".", "AggFuncMin", ":", "return", "&", "maxMinFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", ",", "isMax", ":", "false", "}", "\n", "case", "ast", ".", "AggFuncFirstRow", ":", "return", "&", "firstRowFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// NewAggFunction creates a new AggregationFunction.
[ "NewAggFunction", "creates", "a", "new", "AggregationFunction", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L98-L116
train
chrislusf/gleam
sql/expression/aggregation.go
Equal
func (af *aggFunction) Equal(b AggregationFunction, ctx context.Context) bool { if af.GetName() != b.GetName() { return false } if af.Distinct != b.IsDistinct() { return false } if len(af.GetArgs()) == len(b.GetArgs()) { for i, argA := range af.GetArgs() { if !argA.Equal(b.GetArgs()[i], ctx) { return false } } } return true }
go
func (af *aggFunction) Equal(b AggregationFunction, ctx context.Context) bool { if af.GetName() != b.GetName() { return false } if af.Distinct != b.IsDistinct() { return false } if len(af.GetArgs()) == len(b.GetArgs()) { for i, argA := range af.GetArgs() { if !argA.Equal(b.GetArgs()[i], ctx) { return false } } } return true }
[ "func", "(", "af", "*", "aggFunction", ")", "Equal", "(", "b", "AggregationFunction", ",", "ctx", "context", ".", "Context", ")", "bool", "{", "if", "af", ".", "GetName", "(", ")", "!=", "b", ".", "GetName", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "af", ".", "Distinct", "!=", "b", ".", "IsDistinct", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "af", ".", "GetArgs", "(", ")", ")", "==", "len", "(", "b", ".", "GetArgs", "(", ")", ")", "{", "for", "i", ",", "argA", ":=", "range", "af", ".", "GetArgs", "(", ")", "{", "if", "!", "argA", ".", "Equal", "(", "b", ".", "GetArgs", "(", ")", "[", "i", "]", ",", "ctx", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal implements AggregationFunction interface.
[ "Equal", "implements", "AggregationFunction", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L140-L155
train
chrislusf/gleam
sql/expression/aggregation.go
Clear
func (af *aggFunction) Clear() { af.resultMapper = make(aggCtxMapper, 0) af.streamCtx = nil }
go
func (af *aggFunction) Clear() { af.resultMapper = make(aggCtxMapper, 0) af.streamCtx = nil }
[ "func", "(", "af", "*", "aggFunction", ")", "Clear", "(", ")", "{", "af", ".", "resultMapper", "=", "make", "(", "aggCtxMapper", ",", "0", ")", "\n", "af", ".", "streamCtx", "=", "nil", "\n", "}" ]
// Clear implements AggregationFunction interface.
[ "Clear", "implements", "AggregationFunction", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L196-L199
train
chrislusf/gleam
sql/mysql/error.go
Error
func (e *SQLError) Error() string { return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message) }
go
func (e *SQLError) Error() string { return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message) }
[ "func", "(", "e", "*", "SQLError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"ERROR %d (%s): %s\"", ",", "e", ".", "Code", ",", "e", ".", "State", ",", "e", ".", "Message", ")", "\n", "}" ]
// Error prints errors, with a formatted string.
[ "Error", "prints", "errors", "with", "a", "formatted", "string", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L35-L37
train
chrislusf/gleam
sql/mysql/error.go
NewErr
func NewErr(errCode uint16, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } if format, ok := MySQLErrName[errCode]; ok { e.Message = fmt.Sprintf(format, args...) } else { e.Message = fmt.Sprint(args...) } return e }
go
func NewErr(errCode uint16, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } if format, ok := MySQLErrName[errCode]; ok { e.Message = fmt.Sprintf(format, args...) } else { e.Message = fmt.Sprint(args...) } return e }
[ "func", "NewErr", "(", "errCode", "uint16", ",", "args", "...", "interface", "{", "}", ")", "*", "SQLError", "{", "e", ":=", "&", "SQLError", "{", "Code", ":", "errCode", "}", "\n", "if", "s", ",", "ok", ":=", "MySQLState", "[", "errCode", "]", ";", "ok", "{", "e", ".", "State", "=", "s", "\n", "}", "else", "{", "e", ".", "State", "=", "DefaultMySQLState", "\n", "}", "\n", "if", "format", ",", "ok", ":=", "MySQLErrName", "[", "errCode", "]", ";", "ok", "{", "e", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n", "}", "else", "{", "e", ".", "Message", "=", "fmt", ".", "Sprint", "(", "args", "...", ")", "\n", "}", "\n", "return", "e", "\n", "}" ]
// NewErr generates a SQL error, with an error code and default format specifier defined in MySQLErrName.
[ "NewErr", "generates", "a", "SQL", "error", "with", "an", "error", "code", "and", "default", "format", "specifier", "defined", "in", "MySQLErrName", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L40-L56
train
chrislusf/gleam
sql/mysql/error.go
NewErrf
func NewErrf(errCode uint16, format string, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } e.Message = fmt.Sprintf(format, args...) return e }
go
func NewErrf(errCode uint16, format string, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } e.Message = fmt.Sprintf(format, args...) return e }
[ "func", "NewErrf", "(", "errCode", "uint16", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "SQLError", "{", "e", ":=", "&", "SQLError", "{", "Code", ":", "errCode", "}", "\n", "if", "s", ",", "ok", ":=", "MySQLState", "[", "errCode", "]", ";", "ok", "{", "e", ".", "State", "=", "s", "\n", "}", "else", "{", "e", ".", "State", "=", "DefaultMySQLState", "\n", "}", "\n", "e", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n", "return", "e", "\n", "}" ]
// NewErrf creates a SQL error, with an error code and a format specifier.
[ "NewErrf", "creates", "a", "SQL", "error", "with", "an", "error", "code", "and", "a", "format", "specifier", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L59-L71
train
chrislusf/gleam
instruction/local_limit.go
DoLocalLimit
func DoLocalLimit(reader io.Reader, writer io.Writer, n int, offset int, stats *pb.InstructionStat) error { return util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if offset > 0 { offset-- } else { if n > 0 { row.WriteTo(writer) stats.OutputCounter++ } n-- } return nil }) }
go
func DoLocalLimit(reader io.Reader, writer io.Writer, n int, offset int, stats *pb.InstructionStat) error { return util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if offset > 0 { offset-- } else { if n > 0 { row.WriteTo(writer) stats.OutputCounter++ } n-- } return nil }) }
[ "func", "DoLocalLimit", "(", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ",", "n", "int", ",", "offset", "int", ",", "stats", "*", "pb", ".", "InstructionStat", ")", "error", "{", "return", "util", ".", "ProcessRow", "(", "reader", ",", "nil", ",", "func", "(", "row", "*", "util", ".", "Row", ")", "error", "{", "stats", ".", "InputCounter", "++", "\n", "if", "offset", ">", "0", "{", "offset", "--", "\n", "}", "else", "{", "if", "n", ">", "0", "{", "row", ".", "WriteTo", "(", "writer", ")", "\n", "stats", ".", "OutputCounter", "++", "\n", "}", "\n", "n", "--", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// DoLocalLimit streamingly get the n items starting from offset
[ "DoLocalLimit", "streamingly", "get", "the", "n", "items", "starting", "from", "offset" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/instruction/local_limit.go#L55-L73
train
chrislusf/gleam
sql/plan/column_pruning.go
exprHasSetVar
func exprHasSetVar(expr expression.Expression) bool { if fun, ok := expr.(*expression.ScalarFunction); ok { canPrune := true if fun.FuncName.L == ast.SetVar { return false } for _, arg := range fun.GetArgs() { canPrune = canPrune && exprHasSetVar(arg) if !canPrune { return false } } } return true }
go
func exprHasSetVar(expr expression.Expression) bool { if fun, ok := expr.(*expression.ScalarFunction); ok { canPrune := true if fun.FuncName.L == ast.SetVar { return false } for _, arg := range fun.GetArgs() { canPrune = canPrune && exprHasSetVar(arg) if !canPrune { return false } } } return true }
[ "func", "exprHasSetVar", "(", "expr", "expression", ".", "Expression", ")", "bool", "{", "if", "fun", ",", "ok", ":=", "expr", ".", "(", "*", "expression", ".", "ScalarFunction", ")", ";", "ok", "{", "canPrune", ":=", "true", "\n", "if", "fun", ".", "FuncName", ".", "L", "==", "ast", ".", "SetVar", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "fun", ".", "GetArgs", "(", ")", "{", "canPrune", "=", "canPrune", "&&", "exprHasSetVar", "(", "arg", ")", "\n", "if", "!", "canPrune", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// exprHasSetVar checks if the expression has set-var function. If do, we should not prune it.
[ "exprHasSetVar", "checks", "if", "the", "expression", "has", "set", "-", "var", "function", ".", "If", "do", "we", "should", "not", "prune", "it", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/column_pruning.go#L35-L49
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
NewSegmentMap
func NewSegmentMap(size int64) (*SegmentMap, error) { if size <= 0 { return nil, errors.Errorf("Invalid size: %d", size) } sm := &SegmentMap{ maps: make([]map[string]interface{}, size), size: size, } for i := int64(0); i < size; i++ { sm.maps[i] = make(map[string]interface{}) } sm.crcTable = crc32.MakeTable(crc32.Castagnoli) return sm, nil }
go
func NewSegmentMap(size int64) (*SegmentMap, error) { if size <= 0 { return nil, errors.Errorf("Invalid size: %d", size) } sm := &SegmentMap{ maps: make([]map[string]interface{}, size), size: size, } for i := int64(0); i < size; i++ { sm.maps[i] = make(map[string]interface{}) } sm.crcTable = crc32.MakeTable(crc32.Castagnoli) return sm, nil }
[ "func", "NewSegmentMap", "(", "size", "int64", ")", "(", "*", "SegmentMap", ",", "error", ")", "{", "if", "size", "<=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"Invalid size: %d\"", ",", "size", ")", "\n", "}", "\n", "sm", ":=", "&", "SegmentMap", "{", "maps", ":", "make", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "size", ")", ",", "size", ":", "size", ",", "}", "\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "size", ";", "i", "++", "{", "sm", ".", "maps", "[", "i", "]", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n", "sm", ".", "crcTable", "=", "crc32", ".", "MakeTable", "(", "crc32", ".", "Castagnoli", ")", "\n", "return", "sm", ",", "nil", "\n", "}" ]
// NewSegmentMap creates a new SegmentMap.
[ "NewSegmentMap", "creates", "a", "new", "SegmentMap", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L32-L47
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
GetSegment
func (sm *SegmentMap) GetSegment(index int64) (map[string]interface{}, error) { if index >= sm.size || index < 0 { return nil, errors.Errorf("index out of bound: %d", index) } return sm.maps[index], nil }
go
func (sm *SegmentMap) GetSegment(index int64) (map[string]interface{}, error) { if index >= sm.size || index < 0 { return nil, errors.Errorf("index out of bound: %d", index) } return sm.maps[index], nil }
[ "func", "(", "sm", "*", "SegmentMap", ")", "GetSegment", "(", "index", "int64", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "index", ">=", "sm", ".", "size", "||", "index", "<", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"index out of bound: %d\"", ",", "index", ")", "\n", "}", "\n", "return", "sm", ".", "maps", "[", "index", "]", ",", "nil", "\n", "}" ]
// GetSegment gets the map specific by index.
[ "GetSegment", "gets", "the", "map", "specific", "by", "index", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L57-L63
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
Set
func (sm *SegmentMap) Set(key []byte, value interface{}, force bool) bool { idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size k := string(key) _, exist := sm.maps[idx][k] if exist && !force { return exist } sm.maps[idx][k] = value return exist }
go
func (sm *SegmentMap) Set(key []byte, value interface{}, force bool) bool { idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size k := string(key) _, exist := sm.maps[idx][k] if exist && !force { return exist } sm.maps[idx][k] = value return exist }
[ "func", "(", "sm", "*", "SegmentMap", ")", "Set", "(", "key", "[", "]", "byte", ",", "value", "interface", "{", "}", ",", "force", "bool", ")", "bool", "{", "idx", ":=", "int64", "(", "crc32", ".", "Checksum", "(", "key", ",", "sm", ".", "crcTable", ")", ")", "%", "sm", ".", "size", "\n", "k", ":=", "string", "(", "key", ")", "\n", "_", ",", "exist", ":=", "sm", ".", "maps", "[", "idx", "]", "[", "k", "]", "\n", "if", "exist", "&&", "!", "force", "{", "return", "exist", "\n", "}", "\n", "sm", ".", "maps", "[", "idx", "]", "[", "k", "]", "=", "value", "\n", "return", "exist", "\n", "}" ]
// Set if key not exists, returns whether already exists.
[ "Set", "if", "key", "not", "exists", "returns", "whether", "already", "exists", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L66-L76
train
chrislusf/gleam
sql/sessionctx/variable/statusvar.go
GetStatusVars
func GetStatusVars() (map[string]*StatusVal, error) { statusVars := make(map[string]*StatusVal) for _, statistics := range statisticsList { vals, err := statistics.Stats() if err != nil { return nil, errors.Trace(err) } for name, val := range vals { scope := statistics.GetScope(name) statusVars[name] = &StatusVal{Value: val, Scope: scope} } } return statusVars, nil }
go
func GetStatusVars() (map[string]*StatusVal, error) { statusVars := make(map[string]*StatusVal) for _, statistics := range statisticsList { vals, err := statistics.Stats() if err != nil { return nil, errors.Trace(err) } for name, val := range vals { scope := statistics.GetScope(name) statusVars[name] = &StatusVal{Value: val, Scope: scope} } } return statusVars, nil }
[ "func", "GetStatusVars", "(", ")", "(", "map", "[", "string", "]", "*", "StatusVal", ",", "error", ")", "{", "statusVars", ":=", "make", "(", "map", "[", "string", "]", "*", "StatusVal", ")", "\n", "for", "_", ",", "statistics", ":=", "range", "statisticsList", "{", "vals", ",", "err", ":=", "statistics", ".", "Stats", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "name", ",", "val", ":=", "range", "vals", "{", "scope", ":=", "statistics", ".", "GetScope", "(", "name", ")", "\n", "statusVars", "[", "name", "]", "=", "&", "StatusVal", "{", "Value", ":", "val", ",", "Scope", ":", "scope", "}", "\n", "}", "\n", "}", "\n", "return", "statusVars", ",", "nil", "\n", "}" ]
// GetStatusVars gets registered statistics status variables.
[ "GetStatusVars", "gets", "registered", "statistics", "status", "variables", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/statusvar.go#L46-L62
train
chrislusf/gleam
sql/plan/join_reorder.go
tryToGetJoinGroup
func tryToGetJoinGroup(j *Join) ([]LogicalPlan, bool) { if j.reordered || !j.cartesianJoin { return nil, false } lChild := j.GetChildByIndex(0).(LogicalPlan) rChild := j.GetChildByIndex(1).(LogicalPlan) if nj, ok := lChild.(*Join); ok { plans, valid := tryToGetJoinGroup(nj) return append(plans, rChild), valid } return []LogicalPlan{lChild, rChild}, true }
go
func tryToGetJoinGroup(j *Join) ([]LogicalPlan, bool) { if j.reordered || !j.cartesianJoin { return nil, false } lChild := j.GetChildByIndex(0).(LogicalPlan) rChild := j.GetChildByIndex(1).(LogicalPlan) if nj, ok := lChild.(*Join); ok { plans, valid := tryToGetJoinGroup(nj) return append(plans, rChild), valid } return []LogicalPlan{lChild, rChild}, true }
[ "func", "tryToGetJoinGroup", "(", "j", "*", "Join", ")", "(", "[", "]", "LogicalPlan", ",", "bool", ")", "{", "if", "j", ".", "reordered", "||", "!", "j", ".", "cartesianJoin", "{", "return", "nil", ",", "false", "\n", "}", "\n", "lChild", ":=", "j", ".", "GetChildByIndex", "(", "0", ")", ".", "(", "LogicalPlan", ")", "\n", "rChild", ":=", "j", ".", "GetChildByIndex", "(", "1", ")", ".", "(", "LogicalPlan", ")", "\n", "if", "nj", ",", "ok", ":=", "lChild", ".", "(", "*", "Join", ")", ";", "ok", "{", "plans", ",", "valid", ":=", "tryToGetJoinGroup", "(", "nj", ")", "\n", "return", "append", "(", "plans", ",", "rChild", ")", ",", "valid", "\n", "}", "\n", "return", "[", "]", "LogicalPlan", "{", "lChild", ",", "rChild", "}", ",", "true", "\n", "}" ]
// tryToGetJoinGroup tries to fetch a whole join group, which all joins is cartesian join.
[ "tryToGetJoinGroup", "tries", "to", "fetch", "a", "whole", "join", "group", "which", "all", "joins", "is", "cartesian", "join", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/join_reorder.go#L25-L36
train
chrislusf/gleam
sql/plan/join_reorder.go
walkGraphAndComposeJoin
func (e *joinReOrderSolver) walkGraphAndComposeJoin(u int) { e.visited[u] = true for _, edge := range e.graph[u] { v := edge.nodeID if !e.visited[v] { e.resultJoin = e.newJoin(e.resultJoin, e.group[v]) e.walkGraphAndComposeJoin(v) } } }
go
func (e *joinReOrderSolver) walkGraphAndComposeJoin(u int) { e.visited[u] = true for _, edge := range e.graph[u] { v := edge.nodeID if !e.visited[v] { e.resultJoin = e.newJoin(e.resultJoin, e.group[v]) e.walkGraphAndComposeJoin(v) } } }
[ "func", "(", "e", "*", "joinReOrderSolver", ")", "walkGraphAndComposeJoin", "(", "u", "int", ")", "{", "e", ".", "visited", "[", "u", "]", "=", "true", "\n", "for", "_", ",", "edge", ":=", "range", "e", ".", "graph", "[", "u", "]", "{", "v", ":=", "edge", ".", "nodeID", "\n", "if", "!", "e", ".", "visited", "[", "v", "]", "{", "e", ".", "resultJoin", "=", "e", ".", "newJoin", "(", "e", ".", "resultJoin", ",", "e", ".", "group", "[", "v", "]", ")", "\n", "e", ".", "walkGraphAndComposeJoin", "(", "v", ")", "\n", "}", "\n", "}", "\n", "}" ]
// walkGraph implements a dfs algorithm. Each time it picks a edge with lowest rate, which has been sorted before.
[ "walkGraph", "implements", "a", "dfs", "algorithm", ".", "Each", "time", "it", "picks", "a", "edge", "with", "lowest", "rate", "which", "has", "been", "sorted", "before", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/join_reorder.go#L198-L207
train
chrislusf/gleam
sql/table/column.go
FindCols
func FindCols(cols []*Column, names []string) ([]*Column, error) { var rcols []*Column for _, name := range names { col := FindCol(cols, name) if col != nil { rcols = append(rcols, col) } else { return nil, errUnknownColumn.Gen("unknown column %s", name) } } return rcols, nil }
go
func FindCols(cols []*Column, names []string) ([]*Column, error) { var rcols []*Column for _, name := range names { col := FindCol(cols, name) if col != nil { rcols = append(rcols, col) } else { return nil, errUnknownColumn.Gen("unknown column %s", name) } } return rcols, nil }
[ "func", "FindCols", "(", "cols", "[", "]", "*", "Column", ",", "names", "[", "]", "string", ")", "(", "[", "]", "*", "Column", ",", "error", ")", "{", "var", "rcols", "[", "]", "*", "Column", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "col", ":=", "FindCol", "(", "cols", ",", "name", ")", "\n", "if", "col", "!=", "nil", "{", "rcols", "=", "append", "(", "rcols", ",", "col", ")", "\n", "}", "else", "{", "return", "nil", ",", "errUnknownColumn", ".", "Gen", "(", "\"unknown column %s\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "return", "rcols", ",", "nil", "\n", "}" ]
// FindCols finds columns in cols by names.
[ "FindCols", "finds", "columns", "in", "cols", "by", "names", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/table/column.go#L68-L80
train
chrislusf/gleam
sql/table/column.go
CheckOnce
func CheckOnce(cols []*Column) error { m := map[string]struct{}{} for _, col := range cols { name := col.Name _, ok := m[name.L] if ok { return errDuplicateColumn.Gen("column specified twice - %s", name) } m[name.L] = struct{}{} } return nil }
go
func CheckOnce(cols []*Column) error { m := map[string]struct{}{} for _, col := range cols { name := col.Name _, ok := m[name.L] if ok { return errDuplicateColumn.Gen("column specified twice - %s", name) } m[name.L] = struct{}{} } return nil }
[ "func", "CheckOnce", "(", "cols", "[", "]", "*", "Column", ")", "error", "{", "m", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "col", ":=", "range", "cols", "{", "name", ":=", "col", ".", "Name", "\n", "_", ",", "ok", ":=", "m", "[", "name", ".", "L", "]", "\n", "if", "ok", "{", "return", "errDuplicateColumn", ".", "Gen", "(", "\"column specified twice - %s\"", ",", "name", ")", "\n", "}", "\n", "m", "[", "name", ".", "L", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckOnce checks if there are duplicated column names in cols.
[ "CheckOnce", "checks", "if", "there", "are", "duplicated", "column", "names", "in", "cols", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/table/column.go#L201-L214
train