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
ipfs/go-ipfs-api
options/dag.go
Kind
func (dagOpts) Kind(kind string) DagPutOption { return func(opts *DagPutSettings) error { opts.Kind = kind return nil } }
go
func (dagOpts) Kind(kind string) DagPutOption { return func(opts *DagPutSettings) error { opts.Kind = kind return nil } }
[ "func", "(", "dagOpts", ")", "Kind", "(", "kind", "string", ")", "DagPutOption", "{", "return", "func", "(", "opts", "*", "DagPutSettings", ")", "error", "{", "opts", ".", "Kind", "=", "kind", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Kind is an option for Dag.Put which specifies the format that the dag // will be added as. Default is "cbor".
[ "Kind", "is", "an", "option", "for", "Dag", ".", "Put", "which", "specifies", "the", "format", "that", "the", "dag", "will", "be", "added", "as", ".", "Default", "is", "cbor", "." ]
a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L56-L61
test
ipfs/go-ipfs-api
options/dag.go
Hash
func (dagOpts) Hash(hash string) DagPutOption { return func(opts *DagPutSettings) error { opts.Hash = hash return nil } }
go
func (dagOpts) Hash(hash string) DagPutOption { return func(opts *DagPutSettings) error { opts.Hash = hash return nil } }
[ "func", "(", "dagOpts", ")", "Hash", "(", "hash", "string", ")", "DagPutOption", "{", "return", "func", "(", "opts", "*", "DagPutSettings", ")", "error", "{", "opts", ".", "Hash", "=", "hash", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Hash is an option for Dag.Put which specifies the hash function to use
[ "Hash", "is", "an", "option", "for", "Dag", ".", "Put", "which", "specifies", "the", "hash", "function", "to", "use" ]
a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L64-L69
test
ipfs/go-ipfs-api
add.go
AddDir
func (s *Shell) AddDir(dir string) (string, error) { stat, err := os.Lstat(dir) if err != nil { return "", err } sf, err := files.NewSerialFile(dir, false, stat) if err != nil { return "", err } slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry(filepath.Base(dir), sf)}) reader := files.NewMultiFileReader(slf, true) resp, err := s.Request("add"). Option("recursive", true). Body(reader). Send(context.Background()) if err != nil { return "", nil } defer resp.Close() if resp.Error != nil { return "", resp.Error } dec := json.NewDecoder(resp.Output) var final string for { var out object err = dec.Decode(&out) if err != nil { if err == io.EOF { break } return "", err } final = out.Hash } if final == "" { return "", errors.New("no results received") } return final, nil }
go
func (s *Shell) AddDir(dir string) (string, error) { stat, err := os.Lstat(dir) if err != nil { return "", err } sf, err := files.NewSerialFile(dir, false, stat) if err != nil { return "", err } slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry(filepath.Base(dir), sf)}) reader := files.NewMultiFileReader(slf, true) resp, err := s.Request("add"). Option("recursive", true). Body(reader). Send(context.Background()) if err != nil { return "", nil } defer resp.Close() if resp.Error != nil { return "", resp.Error } dec := json.NewDecoder(resp.Output) var final string for { var out object err = dec.Decode(&out) if err != nil { if err == io.EOF { break } return "", err } final = out.Hash } if final == "" { return "", errors.New("no results received") } return final, nil }
[ "func", "(", "s", "*", "Shell", ")", "AddDir", "(", "dir", "string", ")", "(", "string", ",", "error", ")", "{", "stat", ",", "err", ":=", "os", ".", "Lstat", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "sf", ",", "err", ":=", "files", ".", "NewSerialFile", "(", "dir", ",", "false", ",", "stat", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "slf", ":=", "files", ".", "NewSliceDirectory", "(", "[", "]", "files", ".", "DirEntry", "{", "files", ".", "FileEntry", "(", "filepath", ".", "Base", "(", "dir", ")", ",", "sf", ")", "}", ")", "\n", "reader", ":=", "files", ".", "NewMultiFileReader", "(", "slf", ",", "true", ")", "\n", "resp", ",", "err", ":=", "s", ".", "Request", "(", "\"add\"", ")", ".", "Option", "(", "\"recursive\"", ",", "true", ")", ".", "Body", "(", "reader", ")", ".", "Send", "(", "context", ".", "Background", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "defer", "resp", ".", "Close", "(", ")", "\n", "if", "resp", ".", "Error", "!=", "nil", "{", "return", "\"\"", ",", "resp", ".", "Error", "\n", "}", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Output", ")", "\n", "var", "final", "string", "\n", "for", "{", "var", "out", "object", "\n", "err", "=", "dec", ".", "Decode", "(", "&", "out", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "return", "\"\"", ",", "err", "\n", "}", "\n", "final", "=", "out", ".", "Hash", "\n", "}", "\n", "if", "final", "==", "\"\"", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"no results received\"", ")", "\n", "}", "\n", "return", "final", ",", "nil", "\n", "}" ]
// AddDir adds a directory recursively with all of the files under it
[ "AddDir", "adds", "a", "directory", "recursively", "with", "all", "of", "the", "files", "under", "it" ]
a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/add.go#L83-L129
test
ipfs/go-ipfs-api
ipns.go
Publish
func (s *Shell) Publish(node string, value string) error { var pubResp PublishResponse req := s.Request("name/publish") if node != "" { req.Arguments(node) } req.Arguments(value) return req.Exec(context.Background(), &pubResp) }
go
func (s *Shell) Publish(node string, value string) error { var pubResp PublishResponse req := s.Request("name/publish") if node != "" { req.Arguments(node) } req.Arguments(value) return req.Exec(context.Background(), &pubResp) }
[ "func", "(", "s", "*", "Shell", ")", "Publish", "(", "node", "string", ",", "value", "string", ")", "error", "{", "var", "pubResp", "PublishResponse", "\n", "req", ":=", "s", ".", "Request", "(", "\"name/publish\"", ")", "\n", "if", "node", "!=", "\"\"", "{", "req", ".", "Arguments", "(", "node", ")", "\n", "}", "\n", "req", ".", "Arguments", "(", "value", ")", "\n", "return", "req", ".", "Exec", "(", "context", ".", "Background", "(", ")", ",", "&", "pubResp", ")", "\n", "}" ]
// Publish updates a mutable name to point to a given value
[ "Publish", "updates", "a", "mutable", "name", "to", "point", "to", "a", "given", "value" ]
a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/ipns.go#L14-L23
test
ipfs/go-ipfs-api
ipns.go
PublishWithDetails
func (s *Shell) PublishWithDetails(contentHash, key string, lifetime, ttl time.Duration, resolve bool) (*PublishResponse, error) { var pubResp PublishResponse req := s.Request("name/publish", contentHash).Option("resolve", resolve) if key != "" { req.Option("key", key) } if lifetime != 0 { req.Option("lifetime", lifetime) } if ttl.Seconds() > 0 { req.Option("ttl", ttl) } err := req.Exec(context.Background(), &pubResp) if err != nil { return nil, err } return &pubResp, nil }
go
func (s *Shell) PublishWithDetails(contentHash, key string, lifetime, ttl time.Duration, resolve bool) (*PublishResponse, error) { var pubResp PublishResponse req := s.Request("name/publish", contentHash).Option("resolve", resolve) if key != "" { req.Option("key", key) } if lifetime != 0 { req.Option("lifetime", lifetime) } if ttl.Seconds() > 0 { req.Option("ttl", ttl) } err := req.Exec(context.Background(), &pubResp) if err != nil { return nil, err } return &pubResp, nil }
[ "func", "(", "s", "*", "Shell", ")", "PublishWithDetails", "(", "contentHash", ",", "key", "string", ",", "lifetime", ",", "ttl", "time", ".", "Duration", ",", "resolve", "bool", ")", "(", "*", "PublishResponse", ",", "error", ")", "{", "var", "pubResp", "PublishResponse", "\n", "req", ":=", "s", ".", "Request", "(", "\"name/publish\"", ",", "contentHash", ")", ".", "Option", "(", "\"resolve\"", ",", "resolve", ")", "\n", "if", "key", "!=", "\"\"", "{", "req", ".", "Option", "(", "\"key\"", ",", "key", ")", "\n", "}", "\n", "if", "lifetime", "!=", "0", "{", "req", ".", "Option", "(", "\"lifetime\"", ",", "lifetime", ")", "\n", "}", "\n", "if", "ttl", ".", "Seconds", "(", ")", ">", "0", "{", "req", ".", "Option", "(", "\"ttl\"", ",", "ttl", ")", "\n", "}", "\n", "err", ":=", "req", ".", "Exec", "(", "context", ".", "Background", "(", ")", ",", "&", "pubResp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "pubResp", ",", "nil", "\n", "}" ]
// PublishWithDetails is used for fine grained control over record publishing
[ "PublishWithDetails", "is", "used", "for", "fine", "grained", "control", "over", "record", "publishing" ]
a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/ipns.go#L26-L43
test
xwb1989/sqlparser
dependency/sqltypes/plan_value.go
ResolveValue
func (pv PlanValue) ResolveValue(bindVars map[string]*querypb.BindVariable) (Value, error) { switch { case pv.Key != "": bv, err := pv.lookupValue(bindVars) if err != nil { return NULL, err } return MakeTrusted(bv.Type, bv.Value), nil case !pv.Value.IsNull(): return pv.Value, nil case pv.ListKey != "" || pv.Values != nil: // This code is unreachable because the parser does not allow // multi-value constructs where a single value is expected. return NULL, errors.New("a list was supplied where a single value was expected") } return NULL, nil }
go
func (pv PlanValue) ResolveValue(bindVars map[string]*querypb.BindVariable) (Value, error) { switch { case pv.Key != "": bv, err := pv.lookupValue(bindVars) if err != nil { return NULL, err } return MakeTrusted(bv.Type, bv.Value), nil case !pv.Value.IsNull(): return pv.Value, nil case pv.ListKey != "" || pv.Values != nil: // This code is unreachable because the parser does not allow // multi-value constructs where a single value is expected. return NULL, errors.New("a list was supplied where a single value was expected") } return NULL, nil }
[ "func", "(", "pv", "PlanValue", ")", "ResolveValue", "(", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "Value", ",", "error", ")", "{", "switch", "{", "case", "pv", ".", "Key", "!=", "\"\"", ":", "bv", ",", "err", ":=", "pv", ".", "lookupValue", "(", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NULL", ",", "err", "\n", "}", "\n", "return", "MakeTrusted", "(", "bv", ".", "Type", ",", "bv", ".", "Value", ")", ",", "nil", "\n", "case", "!", "pv", ".", "Value", ".", "IsNull", "(", ")", ":", "return", "pv", ".", "Value", ",", "nil", "\n", "case", "pv", ".", "ListKey", "!=", "\"\"", "||", "pv", ".", "Values", "!=", "nil", ":", "return", "NULL", ",", "errors", ".", "New", "(", "\"a list was supplied where a single value was expected\"", ")", "\n", "}", "\n", "return", "NULL", ",", "nil", "\n", "}" ]
// ResolveValue resolves a PlanValue as a single value based on the supplied bindvars.
[ "ResolveValue", "resolves", "a", "PlanValue", "as", "a", "single", "value", "based", "on", "the", "supplied", "bindvars", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/plan_value.go#L77-L93
test
xwb1989/sqlparser
parsed_query.go
GenerateQuery
func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) ([]byte, error) { if len(pq.bindLocations) == 0 { return []byte(pq.Query), nil } buf := bytes.NewBuffer(make([]byte, 0, len(pq.Query))) current := 0 for _, loc := range pq.bindLocations { buf.WriteString(pq.Query[current:loc.offset]) name := pq.Query[loc.offset : loc.offset+loc.length] if encodable, ok := extras[name[1:]]; ok { encodable.EncodeSQL(buf) } else { supplied, _, err := FetchBindVar(name, bindVariables) if err != nil { return nil, err } EncodeValue(buf, supplied) } current = loc.offset + loc.length } buf.WriteString(pq.Query[current:]) return buf.Bytes(), nil }
go
func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) ([]byte, error) { if len(pq.bindLocations) == 0 { return []byte(pq.Query), nil } buf := bytes.NewBuffer(make([]byte, 0, len(pq.Query))) current := 0 for _, loc := range pq.bindLocations { buf.WriteString(pq.Query[current:loc.offset]) name := pq.Query[loc.offset : loc.offset+loc.length] if encodable, ok := extras[name[1:]]; ok { encodable.EncodeSQL(buf) } else { supplied, _, err := FetchBindVar(name, bindVariables) if err != nil { return nil, err } EncodeValue(buf, supplied) } current = loc.offset + loc.length } buf.WriteString(pq.Query[current:]) return buf.Bytes(), nil }
[ "func", "(", "pq", "*", "ParsedQuery", ")", "GenerateQuery", "(", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "extras", "map", "[", "string", "]", "Encodable", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "pq", ".", "bindLocations", ")", "==", "0", "{", "return", "[", "]", "byte", "(", "pq", ".", "Query", ")", ",", "nil", "\n", "}", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "pq", ".", "Query", ")", ")", ")", "\n", "current", ":=", "0", "\n", "for", "_", ",", "loc", ":=", "range", "pq", ".", "bindLocations", "{", "buf", ".", "WriteString", "(", "pq", ".", "Query", "[", "current", ":", "loc", ".", "offset", "]", ")", "\n", "name", ":=", "pq", ".", "Query", "[", "loc", ".", "offset", ":", "loc", ".", "offset", "+", "loc", ".", "length", "]", "\n", "if", "encodable", ",", "ok", ":=", "extras", "[", "name", "[", "1", ":", "]", "]", ";", "ok", "{", "encodable", ".", "EncodeSQL", "(", "buf", ")", "\n", "}", "else", "{", "supplied", ",", "_", ",", "err", ":=", "FetchBindVar", "(", "name", ",", "bindVariables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "EncodeValue", "(", "buf", ",", "supplied", ")", "\n", "}", "\n", "current", "=", "loc", ".", "offset", "+", "loc", ".", "length", "\n", "}", "\n", "buf", ".", "WriteString", "(", "pq", ".", "Query", "[", "current", ":", "]", ")", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// GenerateQuery generates a query by substituting the specified // bindVariables. The extras parameter specifies special parameters // that can perform custom encoding.
[ "GenerateQuery", "generates", "a", "query", "by", "substituting", "the", "specified", "bindVariables", ".", "The", "extras", "parameter", "specifies", "special", "parameters", "that", "can", "perform", "custom", "encoding", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/parsed_query.go#L48-L70
test
xwb1989/sqlparser
parsed_query.go
EncodeValue
func EncodeValue(buf *bytes.Buffer, value *querypb.BindVariable) { if value.Type != querypb.Type_TUPLE { // Since we already check for TUPLE, we don't expect an error. v, _ := sqltypes.BindVariableToValue(value) v.EncodeSQL(buf) return } // It's a TUPLE. buf.WriteByte('(') for i, bv := range value.Values { if i != 0 { buf.WriteString(", ") } sqltypes.ProtoToValue(bv).EncodeSQL(buf) } buf.WriteByte(')') }
go
func EncodeValue(buf *bytes.Buffer, value *querypb.BindVariable) { if value.Type != querypb.Type_TUPLE { // Since we already check for TUPLE, we don't expect an error. v, _ := sqltypes.BindVariableToValue(value) v.EncodeSQL(buf) return } // It's a TUPLE. buf.WriteByte('(') for i, bv := range value.Values { if i != 0 { buf.WriteString(", ") } sqltypes.ProtoToValue(bv).EncodeSQL(buf) } buf.WriteByte(')') }
[ "func", "EncodeValue", "(", "buf", "*", "bytes", ".", "Buffer", ",", "value", "*", "querypb", ".", "BindVariable", ")", "{", "if", "value", ".", "Type", "!=", "querypb", ".", "Type_TUPLE", "{", "v", ",", "_", ":=", "sqltypes", ".", "BindVariableToValue", "(", "value", ")", "\n", "v", ".", "EncodeSQL", "(", "buf", ")", "\n", "return", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "'('", ")", "\n", "for", "i", ",", "bv", ":=", "range", "value", ".", "Values", "{", "if", "i", "!=", "0", "{", "buf", ".", "WriteString", "(", "\", \"", ")", "\n", "}", "\n", "sqltypes", ".", "ProtoToValue", "(", "bv", ")", ".", "EncodeSQL", "(", "buf", ")", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "')'", ")", "\n", "}" ]
// EncodeValue encodes one bind variable value into the query.
[ "EncodeValue", "encodes", "one", "bind", "variable", "value", "into", "the", "query", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/parsed_query.go#L73-L90
test
xwb1989/sqlparser
token.go
Lex
func (tkn *Tokenizer) Lex(lval *yySymType) int { typ, val := tkn.Scan() for typ == COMMENT { if tkn.AllowComments { break } typ, val = tkn.Scan() } lval.bytes = val tkn.lastToken = val return typ }
go
func (tkn *Tokenizer) Lex(lval *yySymType) int { typ, val := tkn.Scan() for typ == COMMENT { if tkn.AllowComments { break } typ, val = tkn.Scan() } lval.bytes = val tkn.lastToken = val return typ }
[ "func", "(", "tkn", "*", "Tokenizer", ")", "Lex", "(", "lval", "*", "yySymType", ")", "int", "{", "typ", ",", "val", ":=", "tkn", ".", "Scan", "(", ")", "\n", "for", "typ", "==", "COMMENT", "{", "if", "tkn", ".", "AllowComments", "{", "break", "\n", "}", "\n", "typ", ",", "val", "=", "tkn", ".", "Scan", "(", ")", "\n", "}", "\n", "lval", ".", "bytes", "=", "val", "\n", "tkn", ".", "lastToken", "=", "val", "\n", "return", "typ", "\n", "}" ]
// Lex returns the next token form the Tokenizer. // This function is used by go yacc.
[ "Lex", "returns", "the", "next", "token", "form", "the", "Tokenizer", ".", "This", "function", "is", "used", "by", "go", "yacc", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/token.go#L420-L431
test
xwb1989/sqlparser
token.go
skipStatement
func (tkn *Tokenizer) skipStatement() { ch := tkn.lastChar for ch != ';' && ch != eofChar { tkn.next() ch = tkn.lastChar } }
go
func (tkn *Tokenizer) skipStatement() { ch := tkn.lastChar for ch != ';' && ch != eofChar { tkn.next() ch = tkn.lastChar } }
[ "func", "(", "tkn", "*", "Tokenizer", ")", "skipStatement", "(", ")", "{", "ch", ":=", "tkn", ".", "lastChar", "\n", "for", "ch", "!=", "';'", "&&", "ch", "!=", "eofChar", "{", "tkn", ".", "next", "(", ")", "\n", "ch", "=", "tkn", ".", "lastChar", "\n", "}", "\n", "}" ]
// skipStatement scans until the EOF, or end of statement is encountered.
[ "skipStatement", "scans", "until", "the", "EOF", "or", "end", "of", "statement", "is", "encountered", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/token.go#L609-L615
test
xwb1989/sqlparser
token.go
reset
func (tkn *Tokenizer) reset() { tkn.ParseTree = nil tkn.partialDDL = nil tkn.specialComment = nil tkn.posVarIndex = 0 tkn.nesting = 0 tkn.ForceEOF = false }
go
func (tkn *Tokenizer) reset() { tkn.ParseTree = nil tkn.partialDDL = nil tkn.specialComment = nil tkn.posVarIndex = 0 tkn.nesting = 0 tkn.ForceEOF = false }
[ "func", "(", "tkn", "*", "Tokenizer", ")", "reset", "(", ")", "{", "tkn", ".", "ParseTree", "=", "nil", "\n", "tkn", ".", "partialDDL", "=", "nil", "\n", "tkn", ".", "specialComment", "=", "nil", "\n", "tkn", ".", "posVarIndex", "=", "0", "\n", "tkn", ".", "nesting", "=", "0", "\n", "tkn", ".", "ForceEOF", "=", "false", "\n", "}" ]
// reset clears any internal state.
[ "reset", "clears", "any", "internal", "state", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/token.go#L919-L926
test
xwb1989/sqlparser
analyzer.go
Preview
func Preview(sql string) int { trimmed := StripLeadingComments(sql) firstWord := trimmed if end := strings.IndexFunc(trimmed, unicode.IsSpace); end != -1 { firstWord = trimmed[:end] } firstWord = strings.TrimLeftFunc(firstWord, func(r rune) bool { return !unicode.IsLetter(r) }) // Comparison is done in order of priority. loweredFirstWord := strings.ToLower(firstWord) switch loweredFirstWord { case "select": return StmtSelect case "stream": return StmtStream case "insert": return StmtInsert case "replace": return StmtReplace case "update": return StmtUpdate case "delete": return StmtDelete } // For the following statements it is not sufficient to rely // on loweredFirstWord. This is because they are not statements // in the grammar and we are relying on Preview to parse them. // For instance, we don't want: "BEGIN JUNK" to be parsed // as StmtBegin. trimmedNoComments, _ := SplitMarginComments(trimmed) switch strings.ToLower(trimmedNoComments) { case "begin", "start transaction": return StmtBegin case "commit": return StmtCommit case "rollback": return StmtRollback } switch loweredFirstWord { case "create", "alter", "rename", "drop", "truncate": return StmtDDL case "set": return StmtSet case "show": return StmtShow case "use": return StmtUse case "analyze", "describe", "desc", "explain", "repair", "optimize": return StmtOther } if strings.Index(trimmed, "/*!") == 0 { return StmtComment } return StmtUnknown }
go
func Preview(sql string) int { trimmed := StripLeadingComments(sql) firstWord := trimmed if end := strings.IndexFunc(trimmed, unicode.IsSpace); end != -1 { firstWord = trimmed[:end] } firstWord = strings.TrimLeftFunc(firstWord, func(r rune) bool { return !unicode.IsLetter(r) }) // Comparison is done in order of priority. loweredFirstWord := strings.ToLower(firstWord) switch loweredFirstWord { case "select": return StmtSelect case "stream": return StmtStream case "insert": return StmtInsert case "replace": return StmtReplace case "update": return StmtUpdate case "delete": return StmtDelete } // For the following statements it is not sufficient to rely // on loweredFirstWord. This is because they are not statements // in the grammar and we are relying on Preview to parse them. // For instance, we don't want: "BEGIN JUNK" to be parsed // as StmtBegin. trimmedNoComments, _ := SplitMarginComments(trimmed) switch strings.ToLower(trimmedNoComments) { case "begin", "start transaction": return StmtBegin case "commit": return StmtCommit case "rollback": return StmtRollback } switch loweredFirstWord { case "create", "alter", "rename", "drop", "truncate": return StmtDDL case "set": return StmtSet case "show": return StmtShow case "use": return StmtUse case "analyze", "describe", "desc", "explain", "repair", "optimize": return StmtOther } if strings.Index(trimmed, "/*!") == 0 { return StmtComment } return StmtUnknown }
[ "func", "Preview", "(", "sql", "string", ")", "int", "{", "trimmed", ":=", "StripLeadingComments", "(", "sql", ")", "\n", "firstWord", ":=", "trimmed", "\n", "if", "end", ":=", "strings", ".", "IndexFunc", "(", "trimmed", ",", "unicode", ".", "IsSpace", ")", ";", "end", "!=", "-", "1", "{", "firstWord", "=", "trimmed", "[", ":", "end", "]", "\n", "}", "\n", "firstWord", "=", "strings", ".", "TrimLeftFunc", "(", "firstWord", ",", "func", "(", "r", "rune", ")", "bool", "{", "return", "!", "unicode", ".", "IsLetter", "(", "r", ")", "}", ")", "\n", "loweredFirstWord", ":=", "strings", ".", "ToLower", "(", "firstWord", ")", "\n", "switch", "loweredFirstWord", "{", "case", "\"select\"", ":", "return", "StmtSelect", "\n", "case", "\"stream\"", ":", "return", "StmtStream", "\n", "case", "\"insert\"", ":", "return", "StmtInsert", "\n", "case", "\"replace\"", ":", "return", "StmtReplace", "\n", "case", "\"update\"", ":", "return", "StmtUpdate", "\n", "case", "\"delete\"", ":", "return", "StmtDelete", "\n", "}", "\n", "trimmedNoComments", ",", "_", ":=", "SplitMarginComments", "(", "trimmed", ")", "\n", "switch", "strings", ".", "ToLower", "(", "trimmedNoComments", ")", "{", "case", "\"begin\"", ",", "\"start transaction\"", ":", "return", "StmtBegin", "\n", "case", "\"commit\"", ":", "return", "StmtCommit", "\n", "case", "\"rollback\"", ":", "return", "StmtRollback", "\n", "}", "\n", "switch", "loweredFirstWord", "{", "case", "\"create\"", ",", "\"alter\"", ",", "\"rename\"", ",", "\"drop\"", ",", "\"truncate\"", ":", "return", "StmtDDL", "\n", "case", "\"set\"", ":", "return", "StmtSet", "\n", "case", "\"show\"", ":", "return", "StmtShow", "\n", "case", "\"use\"", ":", "return", "StmtUse", "\n", "case", "\"analyze\"", ",", "\"describe\"", ",", "\"desc\"", ",", "\"explain\"", ",", "\"repair\"", ",", "\"optimize\"", ":", "return", "StmtOther", "\n", "}", "\n", "if", "strings", ".", "Index", "(", "trimmed", ",", "\"/*!\"", ")", "==", "0", "{", "return", "StmtComment", "\n", "}", "\n", "return", "StmtUnknown", "\n", "}" ]
// Preview analyzes the beginning of the query using a simpler and faster // textual comparison to identify the statement type.
[ "Preview", "analyzes", "the", "beginning", "of", "the", "query", "using", "a", "simpler", "and", "faster", "textual", "comparison", "to", "identify", "the", "statement", "type", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/analyzer.go#L53-L107
test
xwb1989/sqlparser
analyzer.go
NewPlanValue
func NewPlanValue(node Expr) (sqltypes.PlanValue, error) { switch node := node.(type) { case *SQLVal: switch node.Type { case ValArg: return sqltypes.PlanValue{Key: string(node.Val[1:])}, nil case IntVal: n, err := sqltypes.NewIntegral(string(node.Val)) if err != nil { return sqltypes.PlanValue{}, fmt.Errorf("%v", err) } return sqltypes.PlanValue{Value: n}, nil case StrVal: return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, node.Val)}, nil case HexVal: v, err := node.HexDecode() if err != nil { return sqltypes.PlanValue{}, fmt.Errorf("%v", err) } return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, v)}, nil } case ListArg: return sqltypes.PlanValue{ListKey: string(node[2:])}, nil case ValTuple: pv := sqltypes.PlanValue{ Values: make([]sqltypes.PlanValue, 0, len(node)), } for _, val := range node { innerpv, err := NewPlanValue(val) if err != nil { return sqltypes.PlanValue{}, err } if innerpv.ListKey != "" || innerpv.Values != nil { return sqltypes.PlanValue{}, errors.New("unsupported: nested lists") } pv.Values = append(pv.Values, innerpv) } return pv, nil case *NullVal: return sqltypes.PlanValue{}, nil } return sqltypes.PlanValue{}, fmt.Errorf("expression is too complex '%v'", String(node)) }
go
func NewPlanValue(node Expr) (sqltypes.PlanValue, error) { switch node := node.(type) { case *SQLVal: switch node.Type { case ValArg: return sqltypes.PlanValue{Key: string(node.Val[1:])}, nil case IntVal: n, err := sqltypes.NewIntegral(string(node.Val)) if err != nil { return sqltypes.PlanValue{}, fmt.Errorf("%v", err) } return sqltypes.PlanValue{Value: n}, nil case StrVal: return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, node.Val)}, nil case HexVal: v, err := node.HexDecode() if err != nil { return sqltypes.PlanValue{}, fmt.Errorf("%v", err) } return sqltypes.PlanValue{Value: sqltypes.MakeTrusted(sqltypes.VarBinary, v)}, nil } case ListArg: return sqltypes.PlanValue{ListKey: string(node[2:])}, nil case ValTuple: pv := sqltypes.PlanValue{ Values: make([]sqltypes.PlanValue, 0, len(node)), } for _, val := range node { innerpv, err := NewPlanValue(val) if err != nil { return sqltypes.PlanValue{}, err } if innerpv.ListKey != "" || innerpv.Values != nil { return sqltypes.PlanValue{}, errors.New("unsupported: nested lists") } pv.Values = append(pv.Values, innerpv) } return pv, nil case *NullVal: return sqltypes.PlanValue{}, nil } return sqltypes.PlanValue{}, fmt.Errorf("expression is too complex '%v'", String(node)) }
[ "func", "NewPlanValue", "(", "node", "Expr", ")", "(", "sqltypes", ".", "PlanValue", ",", "error", ")", "{", "switch", "node", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "SQLVal", ":", "switch", "node", ".", "Type", "{", "case", "ValArg", ":", "return", "sqltypes", ".", "PlanValue", "{", "Key", ":", "string", "(", "node", ".", "Val", "[", "1", ":", "]", ")", "}", ",", "nil", "\n", "case", "IntVal", ":", "n", ",", "err", ":=", "sqltypes", ".", "NewIntegral", "(", "string", "(", "node", ".", "Val", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"%v\"", ",", "err", ")", "\n", "}", "\n", "return", "sqltypes", ".", "PlanValue", "{", "Value", ":", "n", "}", ",", "nil", "\n", "case", "StrVal", ":", "return", "sqltypes", ".", "PlanValue", "{", "Value", ":", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarBinary", ",", "node", ".", "Val", ")", "}", ",", "nil", "\n", "case", "HexVal", ":", "v", ",", "err", ":=", "node", ".", "HexDecode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"%v\"", ",", "err", ")", "\n", "}", "\n", "return", "sqltypes", ".", "PlanValue", "{", "Value", ":", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarBinary", ",", "v", ")", "}", ",", "nil", "\n", "}", "\n", "case", "ListArg", ":", "return", "sqltypes", ".", "PlanValue", "{", "ListKey", ":", "string", "(", "node", "[", "2", ":", "]", ")", "}", ",", "nil", "\n", "case", "ValTuple", ":", "pv", ":=", "sqltypes", ".", "PlanValue", "{", "Values", ":", "make", "(", "[", "]", "sqltypes", ".", "PlanValue", ",", "0", ",", "len", "(", "node", ")", ")", ",", "}", "\n", "for", "_", ",", "val", ":=", "range", "node", "{", "innerpv", ",", "err", ":=", "NewPlanValue", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "err", "\n", "}", "\n", "if", "innerpv", ".", "ListKey", "!=", "\"\"", "||", "innerpv", ".", "Values", "!=", "nil", "{", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "errors", ".", "New", "(", "\"unsupported: nested lists\"", ")", "\n", "}", "\n", "pv", ".", "Values", "=", "append", "(", "pv", ".", "Values", ",", "innerpv", ")", "\n", "}", "\n", "return", "pv", ",", "nil", "\n", "case", "*", "NullVal", ":", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "nil", "\n", "}", "\n", "return", "sqltypes", ".", "PlanValue", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"expression is too complex '%v'\"", ",", "String", "(", "node", ")", ")", "\n", "}" ]
// NewPlanValue builds a sqltypes.PlanValue from an Expr.
[ "NewPlanValue", "builds", "a", "sqltypes", ".", "PlanValue", "from", "an", "Expr", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/analyzer.go#L211-L253
test
xwb1989/sqlparser
analyzer.go
StringIn
func StringIn(str string, values ...string) bool { for _, val := range values { if str == val { return true } } return false }
go
func StringIn(str string, values ...string) bool { for _, val := range values { if str == val { return true } } return false }
[ "func", "StringIn", "(", "str", "string", ",", "values", "...", "string", ")", "bool", "{", "for", "_", ",", "val", ":=", "range", "values", "{", "if", "str", "==", "val", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// StringIn is a convenience function that returns // true if str matches any of the values.
[ "StringIn", "is", "a", "convenience", "function", "that", "returns", "true", "if", "str", "matches", "any", "of", "the", "values", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/analyzer.go#L257-L264
test
xwb1989/sqlparser
tracked_buffer.go
NewTrackedBuffer
func NewTrackedBuffer(nodeFormatter NodeFormatter) *TrackedBuffer { return &TrackedBuffer{ Buffer: new(bytes.Buffer), nodeFormatter: nodeFormatter, } }
go
func NewTrackedBuffer(nodeFormatter NodeFormatter) *TrackedBuffer { return &TrackedBuffer{ Buffer: new(bytes.Buffer), nodeFormatter: nodeFormatter, } }
[ "func", "NewTrackedBuffer", "(", "nodeFormatter", "NodeFormatter", ")", "*", "TrackedBuffer", "{", "return", "&", "TrackedBuffer", "{", "Buffer", ":", "new", "(", "bytes", ".", "Buffer", ")", ",", "nodeFormatter", ":", "nodeFormatter", ",", "}", "\n", "}" ]
// NewTrackedBuffer creates a new TrackedBuffer.
[ "NewTrackedBuffer", "creates", "a", "new", "TrackedBuffer", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/tracked_buffer.go#L42-L47
test
xwb1989/sqlparser
dependency/hack/hack.go
NewStringArena
func NewStringArena(size int) *StringArena { sa := &StringArena{buf: make([]byte, 0, size)} pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&sa.buf)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&sa.str)) pstring.Data = pbytes.Data pstring.Len = pbytes.Cap return sa }
go
func NewStringArena(size int) *StringArena { sa := &StringArena{buf: make([]byte, 0, size)} pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&sa.buf)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&sa.str)) pstring.Data = pbytes.Data pstring.Len = pbytes.Cap return sa }
[ "func", "NewStringArena", "(", "size", "int", ")", "*", "StringArena", "{", "sa", ":=", "&", "StringArena", "{", "buf", ":", "make", "(", "[", "]", "byte", ",", "0", ",", "size", ")", "}", "\n", "pbytes", ":=", "(", "*", "reflect", ".", "SliceHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "sa", ".", "buf", ")", ")", "\n", "pstring", ":=", "(", "*", "reflect", ".", "StringHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "sa", ".", "str", ")", ")", "\n", "pstring", ".", "Data", "=", "pbytes", ".", "Data", "\n", "pstring", ".", "Len", "=", "pbytes", ".", "Cap", "\n", "return", "sa", "\n", "}" ]
// NewStringArena creates an arena of the specified size.
[ "NewStringArena", "creates", "an", "arena", "of", "the", "specified", "size", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/hack/hack.go#L34-L41
test
xwb1989/sqlparser
dependency/hack/hack.go
NewString
func (sa *StringArena) NewString(b []byte) string { if len(b) == 0 { return "" } if len(sa.buf)+len(b) > cap(sa.buf) { return string(b) } start := len(sa.buf) sa.buf = append(sa.buf, b...) return sa.str[start : start+len(b)] }
go
func (sa *StringArena) NewString(b []byte) string { if len(b) == 0 { return "" } if len(sa.buf)+len(b) > cap(sa.buf) { return string(b) } start := len(sa.buf) sa.buf = append(sa.buf, b...) return sa.str[start : start+len(b)] }
[ "func", "(", "sa", "*", "StringArena", ")", "NewString", "(", "b", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "\"\"", "\n", "}", "\n", "if", "len", "(", "sa", ".", "buf", ")", "+", "len", "(", "b", ")", ">", "cap", "(", "sa", ".", "buf", ")", "{", "return", "string", "(", "b", ")", "\n", "}", "\n", "start", ":=", "len", "(", "sa", ".", "buf", ")", "\n", "sa", ".", "buf", "=", "append", "(", "sa", ".", "buf", ",", "b", "...", ")", "\n", "return", "sa", ".", "str", "[", "start", ":", "start", "+", "len", "(", "b", ")", "]", "\n", "}" ]
// NewString copies a byte slice into the arena and returns it as a string. // If the arena is full, it returns a traditional go string.
[ "NewString", "copies", "a", "byte", "slice", "into", "the", "arena", "and", "returns", "it", "as", "a", "string", ".", "If", "the", "arena", "is", "full", "it", "returns", "a", "traditional", "go", "string", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/hack/hack.go#L45-L55
test
xwb1989/sqlparser
dependency/hack/hack.go
SpaceLeft
func (sa *StringArena) SpaceLeft() int { return cap(sa.buf) - len(sa.buf) }
go
func (sa *StringArena) SpaceLeft() int { return cap(sa.buf) - len(sa.buf) }
[ "func", "(", "sa", "*", "StringArena", ")", "SpaceLeft", "(", ")", "int", "{", "return", "cap", "(", "sa", ".", "buf", ")", "-", "len", "(", "sa", ".", "buf", ")", "\n", "}" ]
// SpaceLeft returns the amount of space left in the arena.
[ "SpaceLeft", "returns", "the", "amount", "of", "space", "left", "in", "the", "arena", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/hack/hack.go#L58-L60
test
xwb1989/sqlparser
ast.go
ParseStrictDDL
func ParseStrictDDL(sql string) (Statement, error) { tokenizer := NewStringTokenizer(sql) if yyParse(tokenizer) != 0 { return nil, tokenizer.LastError } return tokenizer.ParseTree, nil }
go
func ParseStrictDDL(sql string) (Statement, error) { tokenizer := NewStringTokenizer(sql) if yyParse(tokenizer) != 0 { return nil, tokenizer.LastError } return tokenizer.ParseTree, nil }
[ "func", "ParseStrictDDL", "(", "sql", "string", ")", "(", "Statement", ",", "error", ")", "{", "tokenizer", ":=", "NewStringTokenizer", "(", "sql", ")", "\n", "if", "yyParse", "(", "tokenizer", ")", "!=", "0", "{", "return", "nil", ",", "tokenizer", ".", "LastError", "\n", "}", "\n", "return", "tokenizer", ".", "ParseTree", ",", "nil", "\n", "}" ]
// ParseStrictDDL is the same as Parse except it errors on // partially parsed DDL statements.
[ "ParseStrictDDL", "is", "the", "same", "as", "Parse", "except", "it", "errors", "on", "partially", "parsed", "DDL", "statements", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L63-L69
test
xwb1989/sqlparser
ast.go
ParseNext
func ParseNext(tokenizer *Tokenizer) (Statement, error) { if tokenizer.lastChar == ';' { tokenizer.next() tokenizer.skipBlank() } if tokenizer.lastChar == eofChar { return nil, io.EOF } tokenizer.reset() tokenizer.multi = true if yyParse(tokenizer) != 0 { if tokenizer.partialDDL != nil { tokenizer.ParseTree = tokenizer.partialDDL return tokenizer.ParseTree, nil } return nil, tokenizer.LastError } return tokenizer.ParseTree, nil }
go
func ParseNext(tokenizer *Tokenizer) (Statement, error) { if tokenizer.lastChar == ';' { tokenizer.next() tokenizer.skipBlank() } if tokenizer.lastChar == eofChar { return nil, io.EOF } tokenizer.reset() tokenizer.multi = true if yyParse(tokenizer) != 0 { if tokenizer.partialDDL != nil { tokenizer.ParseTree = tokenizer.partialDDL return tokenizer.ParseTree, nil } return nil, tokenizer.LastError } return tokenizer.ParseTree, nil }
[ "func", "ParseNext", "(", "tokenizer", "*", "Tokenizer", ")", "(", "Statement", ",", "error", ")", "{", "if", "tokenizer", ".", "lastChar", "==", "';'", "{", "tokenizer", ".", "next", "(", ")", "\n", "tokenizer", ".", "skipBlank", "(", ")", "\n", "}", "\n", "if", "tokenizer", ".", "lastChar", "==", "eofChar", "{", "return", "nil", ",", "io", ".", "EOF", "\n", "}", "\n", "tokenizer", ".", "reset", "(", ")", "\n", "tokenizer", ".", "multi", "=", "true", "\n", "if", "yyParse", "(", "tokenizer", ")", "!=", "0", "{", "if", "tokenizer", ".", "partialDDL", "!=", "nil", "{", "tokenizer", ".", "ParseTree", "=", "tokenizer", ".", "partialDDL", "\n", "return", "tokenizer", ".", "ParseTree", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "tokenizer", ".", "LastError", "\n", "}", "\n", "return", "tokenizer", ".", "ParseTree", ",", "nil", "\n", "}" ]
// ParseNext parses a single SQL statement from the tokenizer // returning a Statement which is the AST representation of the query. // The tokenizer will always read up to the end of the statement, allowing for // the next call to ParseNext to parse any subsequent SQL statements. When // there are no more statements to parse, a error of io.EOF is returned.
[ "ParseNext", "parses", "a", "single", "SQL", "statement", "from", "the", "tokenizer", "returning", "a", "Statement", "which", "is", "the", "AST", "representation", "of", "the", "query", ".", "The", "tokenizer", "will", "always", "read", "up", "to", "the", "end", "of", "the", "statement", "allowing", "for", "the", "next", "call", "to", "ParseNext", "to", "parse", "any", "subsequent", "SQL", "statements", ".", "When", "there", "are", "no", "more", "statements", "to", "parse", "a", "error", "of", "io", ".", "EOF", "is", "returned", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L76-L95
test
xwb1989/sqlparser
ast.go
Append
func Append(buf *bytes.Buffer, node SQLNode) { tbuf := &TrackedBuffer{ Buffer: buf, } node.Format(tbuf) }
go
func Append(buf *bytes.Buffer, node SQLNode) { tbuf := &TrackedBuffer{ Buffer: buf, } node.Format(tbuf) }
[ "func", "Append", "(", "buf", "*", "bytes", ".", "Buffer", ",", "node", "SQLNode", ")", "{", "tbuf", ":=", "&", "TrackedBuffer", "{", "Buffer", ":", "buf", ",", "}", "\n", "node", ".", "Format", "(", "tbuf", ")", "\n", "}" ]
// Append appends the SQLNode to the buffer.
[ "Append", "appends", "the", "SQLNode", "to", "the", "buffer", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L197-L202
test
xwb1989/sqlparser
ast.go
ExprFromValue
func ExprFromValue(value sqltypes.Value) (Expr, error) { // The type checks here follow the rules defined in sqltypes/types.go. switch { case value.Type() == sqltypes.Null: return &NullVal{}, nil case value.IsIntegral(): return NewIntVal(value.ToBytes()), nil case value.IsFloat() || value.Type() == sqltypes.Decimal: return NewFloatVal(value.ToBytes()), nil case value.IsQuoted(): return NewStrVal(value.ToBytes()), nil default: // We cannot support sqltypes.Expression, or any other invalid type. return nil, fmt.Errorf("cannot convert value %v to AST", value) } }
go
func ExprFromValue(value sqltypes.Value) (Expr, error) { // The type checks here follow the rules defined in sqltypes/types.go. switch { case value.Type() == sqltypes.Null: return &NullVal{}, nil case value.IsIntegral(): return NewIntVal(value.ToBytes()), nil case value.IsFloat() || value.Type() == sqltypes.Decimal: return NewFloatVal(value.ToBytes()), nil case value.IsQuoted(): return NewStrVal(value.ToBytes()), nil default: // We cannot support sqltypes.Expression, or any other invalid type. return nil, fmt.Errorf("cannot convert value %v to AST", value) } }
[ "func", "ExprFromValue", "(", "value", "sqltypes", ".", "Value", ")", "(", "Expr", ",", "error", ")", "{", "switch", "{", "case", "value", ".", "Type", "(", ")", "==", "sqltypes", ".", "Null", ":", "return", "&", "NullVal", "{", "}", ",", "nil", "\n", "case", "value", ".", "IsIntegral", "(", ")", ":", "return", "NewIntVal", "(", "value", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "case", "value", ".", "IsFloat", "(", ")", "||", "value", ".", "Type", "(", ")", "==", "sqltypes", ".", "Decimal", ":", "return", "NewFloatVal", "(", "value", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "case", "value", ".", "IsQuoted", "(", ")", ":", "return", "NewStrVal", "(", "value", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"cannot convert value %v to AST\"", ",", "value", ")", "\n", "}", "\n", "}" ]
// ExprFromValue converts the given Value into an Expr or returns an error.
[ "ExprFromValue", "converts", "the", "given", "Value", "into", "an", "Expr", "or", "returns", "an", "error", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L2236-L2251
test
xwb1989/sqlparser
ast.go
Backtick
func Backtick(in string) string { var buf bytes.Buffer buf.WriteByte('`') for _, c := range in { buf.WriteRune(c) if c == '`' { buf.WriteByte('`') } } buf.WriteByte('`') return buf.String() }
go
func Backtick(in string) string { var buf bytes.Buffer buf.WriteByte('`') for _, c := range in { buf.WriteRune(c) if c == '`' { buf.WriteByte('`') } } buf.WriteByte('`') return buf.String() }
[ "func", "Backtick", "(", "in", "string", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "for", "_", ",", "c", ":=", "range", "in", "{", "buf", ".", "WriteRune", "(", "c", ")", "\n", "if", "c", "==", "'`'", "{", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "}", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Backtick produces a backticked literal given an input string.
[ "Backtick", "produces", "a", "backticked", "literal", "given", "an", "input", "string", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L3395-L3406
test
xwb1989/sqlparser
dependency/sqltypes/value.go
NewValue
func NewValue(typ querypb.Type, val []byte) (v Value, err error) { switch { case IsSigned(typ): if _, err := strconv.ParseInt(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsUnsigned(typ): if _, err := strconv.ParseUint(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsFloat(typ) || typ == Decimal: if _, err := strconv.ParseFloat(string(val), 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsQuoted(typ) || typ == Null: return MakeTrusted(typ, val), nil } // All other types are unsafe or invalid. return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ) }
go
func NewValue(typ querypb.Type, val []byte) (v Value, err error) { switch { case IsSigned(typ): if _, err := strconv.ParseInt(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsUnsigned(typ): if _, err := strconv.ParseUint(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsFloat(typ) || typ == Decimal: if _, err := strconv.ParseFloat(string(val), 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsQuoted(typ) || typ == Null: return MakeTrusted(typ, val), nil } // All other types are unsafe or invalid. return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ) }
[ "func", "NewValue", "(", "typ", "querypb", ".", "Type", ",", "val", "[", "]", "byte", ")", "(", "v", "Value", ",", "err", "error", ")", "{", "switch", "{", "case", "IsSigned", "(", "typ", ")", ":", "if", "_", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "string", "(", "val", ")", ",", "0", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "NULL", ",", "err", "\n", "}", "\n", "return", "MakeTrusted", "(", "typ", ",", "val", ")", ",", "nil", "\n", "case", "IsUnsigned", "(", "typ", ")", ":", "if", "_", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "string", "(", "val", ")", ",", "0", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "NULL", ",", "err", "\n", "}", "\n", "return", "MakeTrusted", "(", "typ", ",", "val", ")", ",", "nil", "\n", "case", "IsFloat", "(", "typ", ")", "||", "typ", "==", "Decimal", ":", "if", "_", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "string", "(", "val", ")", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "NULL", ",", "err", "\n", "}", "\n", "return", "MakeTrusted", "(", "typ", ",", "val", ")", ",", "nil", "\n", "case", "IsQuoted", "(", "typ", ")", "||", "typ", "==", "Null", ":", "return", "MakeTrusted", "(", "typ", ",", "val", ")", ",", "nil", "\n", "}", "\n", "return", "NULL", ",", "fmt", ".", "Errorf", "(", "\"invalid type specified for MakeValue: %v\"", ",", "typ", ")", "\n", "}" ]
// NewValue builds a Value using typ and val. If the value and typ // don't match, it returns an error.
[ "NewValue", "builds", "a", "Value", "using", "typ", "and", "val", ".", "If", "the", "value", "and", "typ", "don", "t", "match", "it", "returns", "an", "error", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/value.go#L60-L82
test
xwb1989/sqlparser
dependency/sqltypes/value.go
String
func (v Value) String() string { if v.typ == Null { return "NULL" } if v.IsQuoted() { return fmt.Sprintf("%v(%q)", v.typ, v.val) } return fmt.Sprintf("%v(%s)", v.typ, v.val) }
go
func (v Value) String() string { if v.typ == Null { return "NULL" } if v.IsQuoted() { return fmt.Sprintf("%v(%q)", v.typ, v.val) } return fmt.Sprintf("%v(%s)", v.typ, v.val) }
[ "func", "(", "v", "Value", ")", "String", "(", ")", "string", "{", "if", "v", ".", "typ", "==", "Null", "{", "return", "\"NULL\"", "\n", "}", "\n", "if", "v", ".", "IsQuoted", "(", ")", "{", "return", "fmt", ".", "Sprintf", "(", "\"%v(%q)\"", ",", "v", ".", "typ", ",", "v", ".", "val", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v(%s)\"", ",", "v", ".", "typ", ",", "v", ".", "val", ")", "\n", "}" ]
// String returns a printable version of the value.
[ "String", "returns", "a", "printable", "version", "of", "the", "value", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/value.go#L204-L212
test
xwb1989/sqlparser
dependency/sqltypes/value.go
EncodeSQL
func (v Value) EncodeSQL(b BinWriter) { switch { case v.typ == Null: b.Write(nullstr) case v.IsQuoted(): encodeBytesSQL(v.val, b) default: b.Write(v.val) } }
go
func (v Value) EncodeSQL(b BinWriter) { switch { case v.typ == Null: b.Write(nullstr) case v.IsQuoted(): encodeBytesSQL(v.val, b) default: b.Write(v.val) } }
[ "func", "(", "v", "Value", ")", "EncodeSQL", "(", "b", "BinWriter", ")", "{", "switch", "{", "case", "v", ".", "typ", "==", "Null", ":", "b", ".", "Write", "(", "nullstr", ")", "\n", "case", "v", ".", "IsQuoted", "(", ")", ":", "encodeBytesSQL", "(", "v", ".", "val", ",", "b", ")", "\n", "default", ":", "b", ".", "Write", "(", "v", ".", "val", ")", "\n", "}", "\n", "}" ]
// EncodeSQL encodes the value into an SQL statement. Can be binary.
[ "EncodeSQL", "encodes", "the", "value", "into", "an", "SQL", "statement", ".", "Can", "be", "binary", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/value.go#L215-L224
test
xwb1989/sqlparser
encodable.go
EncodeSQL
func (iv InsertValues) EncodeSQL(buf *bytes.Buffer) { for i, rows := range iv { if i != 0 { buf.WriteString(", ") } buf.WriteByte('(') for j, bv := range rows { if j != 0 { buf.WriteString(", ") } bv.EncodeSQL(buf) } buf.WriteByte(')') } }
go
func (iv InsertValues) EncodeSQL(buf *bytes.Buffer) { for i, rows := range iv { if i != 0 { buf.WriteString(", ") } buf.WriteByte('(') for j, bv := range rows { if j != 0 { buf.WriteString(", ") } bv.EncodeSQL(buf) } buf.WriteByte(')') } }
[ "func", "(", "iv", "InsertValues", ")", "EncodeSQL", "(", "buf", "*", "bytes", ".", "Buffer", ")", "{", "for", "i", ",", "rows", ":=", "range", "iv", "{", "if", "i", "!=", "0", "{", "buf", ".", "WriteString", "(", "\", \"", ")", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "'('", ")", "\n", "for", "j", ",", "bv", ":=", "range", "rows", "{", "if", "j", "!=", "0", "{", "buf", ".", "WriteString", "(", "\", \"", ")", "\n", "}", "\n", "bv", ".", "EncodeSQL", "(", "buf", ")", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "')'", ")", "\n", "}", "\n", "}" ]
// EncodeSQL performs the SQL encoding for InsertValues.
[ "EncodeSQL", "performs", "the", "SQL", "encoding", "for", "InsertValues", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/encodable.go#L38-L52
test
xwb1989/sqlparser
encodable.go
EncodeSQL
func (tpl *TupleEqualityList) EncodeSQL(buf *bytes.Buffer) { if len(tpl.Columns) == 1 { tpl.encodeAsIn(buf) return } tpl.encodeAsEquality(buf) }
go
func (tpl *TupleEqualityList) EncodeSQL(buf *bytes.Buffer) { if len(tpl.Columns) == 1 { tpl.encodeAsIn(buf) return } tpl.encodeAsEquality(buf) }
[ "func", "(", "tpl", "*", "TupleEqualityList", ")", "EncodeSQL", "(", "buf", "*", "bytes", ".", "Buffer", ")", "{", "if", "len", "(", "tpl", ".", "Columns", ")", "==", "1", "{", "tpl", ".", "encodeAsIn", "(", "buf", ")", "\n", "return", "\n", "}", "\n", "tpl", ".", "encodeAsEquality", "(", "buf", ")", "\n", "}" ]
// EncodeSQL generates the where clause constraints for the tuple // equality.
[ "EncodeSQL", "generates", "the", "where", "clause", "constraints", "for", "the", "tuple", "equality", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/encodable.go#L63-L69
test
xwb1989/sqlparser
normalizer.go
WalkStatement
func (nz *normalizer) WalkStatement(node SQLNode) (bool, error) { switch node := node.(type) { case *Select: _ = Walk(nz.WalkSelect, node) // Don't continue return false, nil case *SQLVal: nz.convertSQLVal(node) case *ComparisonExpr: nz.convertComparison(node) } return true, nil }
go
func (nz *normalizer) WalkStatement(node SQLNode) (bool, error) { switch node := node.(type) { case *Select: _ = Walk(nz.WalkSelect, node) // Don't continue return false, nil case *SQLVal: nz.convertSQLVal(node) case *ComparisonExpr: nz.convertComparison(node) } return true, nil }
[ "func", "(", "nz", "*", "normalizer", ")", "WalkStatement", "(", "node", "SQLNode", ")", "(", "bool", ",", "error", ")", "{", "switch", "node", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "Select", ":", "_", "=", "Walk", "(", "nz", ".", "WalkSelect", ",", "node", ")", "\n", "return", "false", ",", "nil", "\n", "case", "*", "SQLVal", ":", "nz", ".", "convertSQLVal", "(", "node", ")", "\n", "case", "*", "ComparisonExpr", ":", "nz", ".", "convertComparison", "(", "node", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// WalkStatement is the top level walk function. // If it encounters a Select, it switches to a mode // where variables are deduped.
[ "WalkStatement", "is", "the", "top", "level", "walk", "function", ".", "If", "it", "encounters", "a", "Select", "it", "switches", "to", "a", "mode", "where", "variables", "are", "deduped", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/normalizer.go#L62-L74
test
xwb1989/sqlparser
normalizer.go
WalkSelect
func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) { switch node := node.(type) { case *SQLVal: nz.convertSQLValDedup(node) case *ComparisonExpr: nz.convertComparison(node) } return true, nil }
go
func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) { switch node := node.(type) { case *SQLVal: nz.convertSQLValDedup(node) case *ComparisonExpr: nz.convertComparison(node) } return true, nil }
[ "func", "(", "nz", "*", "normalizer", ")", "WalkSelect", "(", "node", "SQLNode", ")", "(", "bool", ",", "error", ")", "{", "switch", "node", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "SQLVal", ":", "nz", ".", "convertSQLValDedup", "(", "node", ")", "\n", "case", "*", "ComparisonExpr", ":", "nz", ".", "convertComparison", "(", "node", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// WalkSelect normalizes the AST in Select mode.
[ "WalkSelect", "normalizes", "the", "AST", "in", "Select", "mode", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/normalizer.go#L77-L85
test
xwb1989/sqlparser
dependency/sqltypes/bind_variables.go
BindVariablesEqual
func BindVariablesEqual(x, y map[string]*querypb.BindVariable) bool { return reflect.DeepEqual(&querypb.BoundQuery{BindVariables: x}, &querypb.BoundQuery{BindVariables: y}) }
go
func BindVariablesEqual(x, y map[string]*querypb.BindVariable) bool { return reflect.DeepEqual(&querypb.BoundQuery{BindVariables: x}, &querypb.BoundQuery{BindVariables: y}) }
[ "func", "BindVariablesEqual", "(", "x", ",", "y", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "&", "querypb", ".", "BoundQuery", "{", "BindVariables", ":", "x", "}", ",", "&", "querypb", ".", "BoundQuery", "{", "BindVariables", ":", "y", "}", ")", "\n", "}" ]
// BindVariablesEqual compares two maps of bind variables.
[ "BindVariablesEqual", "compares", "two", "maps", "of", "bind", "variables", "." ]
120387863bf27d04bc07db8015110a6e96d0146c
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/bind_variables.go#L255-L257
test
auth0/go-jwt-middleware
jwtmiddleware.go
New
func New(options ...Options) *JWTMiddleware { var opts Options if len(options) == 0 { opts = Options{} } else { opts = options[0] } if opts.UserProperty == "" { opts.UserProperty = "user" } if opts.ErrorHandler == nil { opts.ErrorHandler = OnError } if opts.Extractor == nil { opts.Extractor = FromAuthHeader } return &JWTMiddleware{ Options: opts, } }
go
func New(options ...Options) *JWTMiddleware { var opts Options if len(options) == 0 { opts = Options{} } else { opts = options[0] } if opts.UserProperty == "" { opts.UserProperty = "user" } if opts.ErrorHandler == nil { opts.ErrorHandler = OnError } if opts.Extractor == nil { opts.Extractor = FromAuthHeader } return &JWTMiddleware{ Options: opts, } }
[ "func", "New", "(", "options", "...", "Options", ")", "*", "JWTMiddleware", "{", "var", "opts", "Options", "\n", "if", "len", "(", "options", ")", "==", "0", "{", "opts", "=", "Options", "{", "}", "\n", "}", "else", "{", "opts", "=", "options", "[", "0", "]", "\n", "}", "\n", "if", "opts", ".", "UserProperty", "==", "\"\"", "{", "opts", ".", "UserProperty", "=", "\"user\"", "\n", "}", "\n", "if", "opts", ".", "ErrorHandler", "==", "nil", "{", "opts", ".", "ErrorHandler", "=", "OnError", "\n", "}", "\n", "if", "opts", ".", "Extractor", "==", "nil", "{", "opts", ".", "Extractor", "=", "FromAuthHeader", "\n", "}", "\n", "return", "&", "JWTMiddleware", "{", "Options", ":", "opts", ",", "}", "\n", "}" ]
// New constructs a new Secure instance with supplied options.
[ "New", "constructs", "a", "new", "Secure", "instance", "with", "supplied", "options", "." ]
5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L64-L88
test
auth0/go-jwt-middleware
jwtmiddleware.go
HandlerWithNext
func (m *JWTMiddleware) HandlerWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { err := m.CheckJWT(w, r) // If there was an error, do not call next. if err == nil && next != nil { next(w, r) } }
go
func (m *JWTMiddleware) HandlerWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { err := m.CheckJWT(w, r) // If there was an error, do not call next. if err == nil && next != nil { next(w, r) } }
[ "func", "(", "m", "*", "JWTMiddleware", ")", "HandlerWithNext", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "next", "http", ".", "HandlerFunc", ")", "{", "err", ":=", "m", ".", "CheckJWT", "(", "w", ",", "r", ")", "\n", "if", "err", "==", "nil", "&&", "next", "!=", "nil", "{", "next", "(", "w", ",", "r", ")", "\n", "}", "\n", "}" ]
// Special implementation for Negroni, but could be used elsewhere.
[ "Special", "implementation", "for", "Negroni", "but", "could", "be", "used", "elsewhere", "." ]
5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L97-L104
test
auth0/go-jwt-middleware
jwtmiddleware.go
FromAuthHeader
func FromAuthHeader(r *http.Request) (string, error) { authHeader := r.Header.Get("Authorization") if authHeader == "" { return "", nil // No error, just no token } // TODO: Make this a bit more robust, parsing-wise authHeaderParts := strings.Split(authHeader, " ") if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" { return "", errors.New("Authorization header format must be Bearer {token}") } return authHeaderParts[1], nil }
go
func FromAuthHeader(r *http.Request) (string, error) { authHeader := r.Header.Get("Authorization") if authHeader == "" { return "", nil // No error, just no token } // TODO: Make this a bit more robust, parsing-wise authHeaderParts := strings.Split(authHeader, " ") if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" { return "", errors.New("Authorization header format must be Bearer {token}") } return authHeaderParts[1], nil }
[ "func", "FromAuthHeader", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "authHeader", ":=", "r", ".", "Header", ".", "Get", "(", "\"Authorization\"", ")", "\n", "if", "authHeader", "==", "\"\"", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "authHeaderParts", ":=", "strings", ".", "Split", "(", "authHeader", ",", "\" \"", ")", "\n", "if", "len", "(", "authHeaderParts", ")", "!=", "2", "||", "strings", ".", "ToLower", "(", "authHeaderParts", "[", "0", "]", ")", "!=", "\"bearer\"", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"Authorization header format must be Bearer {token}\"", ")", "\n", "}", "\n", "return", "authHeaderParts", "[", "1", "]", ",", "nil", "\n", "}" ]
// FromAuthHeader is a "TokenExtractor" that takes a give request and extracts // the JWT token from the Authorization header.
[ "FromAuthHeader", "is", "a", "TokenExtractor", "that", "takes", "a", "give", "request", "and", "extracts", "the", "JWT", "token", "from", "the", "Authorization", "header", "." ]
5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L123-L136
test
auth0/go-jwt-middleware
jwtmiddleware.go
FromParameter
func FromParameter(param string) TokenExtractor { return func(r *http.Request) (string, error) { return r.URL.Query().Get(param), nil } }
go
func FromParameter(param string) TokenExtractor { return func(r *http.Request) (string, error) { return r.URL.Query().Get(param), nil } }
[ "func", "FromParameter", "(", "param", "string", ")", "TokenExtractor", "{", "return", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "return", "r", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "param", ")", ",", "nil", "\n", "}", "\n", "}" ]
// FromParameter returns a function that extracts the token from the specified // query string parameter
[ "FromParameter", "returns", "a", "function", "that", "extracts", "the", "token", "from", "the", "specified", "query", "string", "parameter" ]
5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L140-L144
test
auth0/go-jwt-middleware
jwtmiddleware.go
FromFirst
func FromFirst(extractors ...TokenExtractor) TokenExtractor { return func(r *http.Request) (string, error) { for _, ex := range extractors { token, err := ex(r) if err != nil { return "", err } if token != "" { return token, nil } } return "", nil } }
go
func FromFirst(extractors ...TokenExtractor) TokenExtractor { return func(r *http.Request) (string, error) { for _, ex := range extractors { token, err := ex(r) if err != nil { return "", err } if token != "" { return token, nil } } return "", nil } }
[ "func", "FromFirst", "(", "extractors", "...", "TokenExtractor", ")", "TokenExtractor", "{", "return", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "for", "_", ",", "ex", ":=", "range", "extractors", "{", "token", ",", "err", ":=", "ex", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "if", "token", "!=", "\"\"", "{", "return", "token", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "nil", "\n", "}", "\n", "}" ]
// FromFirst returns a function that runs multiple token extractors and takes the // first token it finds
[ "FromFirst", "returns", "a", "function", "that", "runs", "multiple", "token", "extractors", "and", "takes", "the", "first", "token", "it", "finds" ]
5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L148-L161
test
libp2p/go-libp2p-pubsub
comm.go
getHelloPacket
func (p *PubSub) getHelloPacket() *RPC { var rpc RPC for t := range p.myTopics { as := &pb.RPC_SubOpts{ Topicid: proto.String(t), Subscribe: proto.Bool(true), } rpc.Subscriptions = append(rpc.Subscriptions, as) } return &rpc }
go
func (p *PubSub) getHelloPacket() *RPC { var rpc RPC for t := range p.myTopics { as := &pb.RPC_SubOpts{ Topicid: proto.String(t), Subscribe: proto.Bool(true), } rpc.Subscriptions = append(rpc.Subscriptions, as) } return &rpc }
[ "func", "(", "p", "*", "PubSub", ")", "getHelloPacket", "(", ")", "*", "RPC", "{", "var", "rpc", "RPC", "\n", "for", "t", ":=", "range", "p", ".", "myTopics", "{", "as", ":=", "&", "pb", ".", "RPC_SubOpts", "{", "Topicid", ":", "proto", ".", "String", "(", "t", ")", ",", "Subscribe", ":", "proto", ".", "Bool", "(", "true", ")", ",", "}", "\n", "rpc", ".", "Subscriptions", "=", "append", "(", "rpc", ".", "Subscriptions", ",", "as", ")", "\n", "}", "\n", "return", "&", "rpc", "\n", "}" ]
// get the initial RPC containing all of our subscriptions to send to new peers
[ "get", "the", "initial", "RPC", "containing", "all", "of", "our", "subscriptions", "to", "send", "to", "new", "peers" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/comm.go#L18-L28
test
libp2p/go-libp2p-pubsub
floodsub.go
NewFloodsubWithProtocols
func NewFloodsubWithProtocols(ctx context.Context, h host.Host, ps []protocol.ID, opts ...Option) (*PubSub, error) { rt := &FloodSubRouter{ protocols: ps, } return NewPubSub(ctx, h, rt, opts...) }
go
func NewFloodsubWithProtocols(ctx context.Context, h host.Host, ps []protocol.ID, opts ...Option) (*PubSub, error) { rt := &FloodSubRouter{ protocols: ps, } return NewPubSub(ctx, h, rt, opts...) }
[ "func", "NewFloodsubWithProtocols", "(", "ctx", "context", ".", "Context", ",", "h", "host", ".", "Host", ",", "ps", "[", "]", "protocol", ".", "ID", ",", "opts", "...", "Option", ")", "(", "*", "PubSub", ",", "error", ")", "{", "rt", ":=", "&", "FloodSubRouter", "{", "protocols", ":", "ps", ",", "}", "\n", "return", "NewPubSub", "(", "ctx", ",", "h", ",", "rt", ",", "opts", "...", ")", "\n", "}" ]
// NewFloodsubWithProtocols returns a new floodsub-enabled PubSub objecting using the protocols specified in ps.
[ "NewFloodsubWithProtocols", "returns", "a", "new", "floodsub", "-", "enabled", "PubSub", "objecting", "using", "the", "protocols", "specified", "in", "ps", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/floodsub.go#L18-L23
test
libp2p/go-libp2p-pubsub
floodsub.go
NewFloodSub
func NewFloodSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { return NewFloodsubWithProtocols(ctx, h, []protocol.ID{FloodSubID}, opts...) }
go
func NewFloodSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { return NewFloodsubWithProtocols(ctx, h, []protocol.ID{FloodSubID}, opts...) }
[ "func", "NewFloodSub", "(", "ctx", "context", ".", "Context", ",", "h", "host", ".", "Host", ",", "opts", "...", "Option", ")", "(", "*", "PubSub", ",", "error", ")", "{", "return", "NewFloodsubWithProtocols", "(", "ctx", ",", "h", ",", "[", "]", "protocol", ".", "ID", "{", "FloodSubID", "}", ",", "opts", "...", ")", "\n", "}" ]
// NewFloodSub returns a new PubSub object using the FloodSubRouter.
[ "NewFloodSub", "returns", "a", "new", "PubSub", "object", "using", "the", "FloodSubRouter", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/floodsub.go#L26-L28
test
libp2p/go-libp2p-pubsub
blacklist.go
NewLRUBlacklist
func NewLRUBlacklist(cap int) (Blacklist, error) { c, err := lru.New(cap) if err != nil { return nil, err } b := &LRUBlacklist{lru: c} return b, nil }
go
func NewLRUBlacklist(cap int) (Blacklist, error) { c, err := lru.New(cap) if err != nil { return nil, err } b := &LRUBlacklist{lru: c} return b, nil }
[ "func", "NewLRUBlacklist", "(", "cap", "int", ")", "(", "Blacklist", ",", "error", ")", "{", "c", ",", "err", ":=", "lru", ".", "New", "(", "cap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ":=", "&", "LRUBlacklist", "{", "lru", ":", "c", "}", "\n", "return", "b", ",", "nil", "\n", "}" ]
// NewLRUBlacklist creates a new LRUBlacklist with capacity cap
[ "NewLRUBlacklist", "creates", "a", "new", "LRUBlacklist", "with", "capacity", "cap" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/blacklist.go#L37-L45
test
libp2p/go-libp2p-pubsub
randomsub.go
NewRandomSub
func NewRandomSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { rt := &RandomSubRouter{ peers: make(map[peer.ID]protocol.ID), } return NewPubSub(ctx, h, rt, opts...) }
go
func NewRandomSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { rt := &RandomSubRouter{ peers: make(map[peer.ID]protocol.ID), } return NewPubSub(ctx, h, rt, opts...) }
[ "func", "NewRandomSub", "(", "ctx", "context", ".", "Context", ",", "h", "host", ".", "Host", ",", "opts", "...", "Option", ")", "(", "*", "PubSub", ",", "error", ")", "{", "rt", ":=", "&", "RandomSubRouter", "{", "peers", ":", "make", "(", "map", "[", "peer", ".", "ID", "]", "protocol", ".", "ID", ")", ",", "}", "\n", "return", "NewPubSub", "(", "ctx", ",", "h", ",", "rt", ",", "opts", "...", ")", "\n", "}" ]
// NewRandomSub returns a new PubSub object using RandomSubRouter as the router.
[ "NewRandomSub", "returns", "a", "new", "PubSub", "object", "using", "RandomSubRouter", "as", "the", "router", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/randomsub.go#L22-L27
test
libp2p/go-libp2p-pubsub
gossipsub.go
NewGossipSub
func NewGossipSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { rt := &GossipSubRouter{ peers: make(map[peer.ID]protocol.ID), mesh: make(map[string]map[peer.ID]struct{}), fanout: make(map[string]map[peer.ID]struct{}), lastpub: make(map[string]int64), gossip: make(map[peer.ID][]*pb.ControlIHave), control: make(map[peer.ID]*pb.ControlMessage), mcache: NewMessageCache(GossipSubHistoryGossip, GossipSubHistoryLength), } return NewPubSub(ctx, h, rt, opts...) }
go
func NewGossipSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) { rt := &GossipSubRouter{ peers: make(map[peer.ID]protocol.ID), mesh: make(map[string]map[peer.ID]struct{}), fanout: make(map[string]map[peer.ID]struct{}), lastpub: make(map[string]int64), gossip: make(map[peer.ID][]*pb.ControlIHave), control: make(map[peer.ID]*pb.ControlMessage), mcache: NewMessageCache(GossipSubHistoryGossip, GossipSubHistoryLength), } return NewPubSub(ctx, h, rt, opts...) }
[ "func", "NewGossipSub", "(", "ctx", "context", ".", "Context", ",", "h", "host", ".", "Host", ",", "opts", "...", "Option", ")", "(", "*", "PubSub", ",", "error", ")", "{", "rt", ":=", "&", "GossipSubRouter", "{", "peers", ":", "make", "(", "map", "[", "peer", ".", "ID", "]", "protocol", ".", "ID", ")", ",", "mesh", ":", "make", "(", "map", "[", "string", "]", "map", "[", "peer", ".", "ID", "]", "struct", "{", "}", ")", ",", "fanout", ":", "make", "(", "map", "[", "string", "]", "map", "[", "peer", ".", "ID", "]", "struct", "{", "}", ")", ",", "lastpub", ":", "make", "(", "map", "[", "string", "]", "int64", ")", ",", "gossip", ":", "make", "(", "map", "[", "peer", ".", "ID", "]", "[", "]", "*", "pb", ".", "ControlIHave", ")", ",", "control", ":", "make", "(", "map", "[", "peer", ".", "ID", "]", "*", "pb", ".", "ControlMessage", ")", ",", "mcache", ":", "NewMessageCache", "(", "GossipSubHistoryGossip", ",", "GossipSubHistoryLength", ")", ",", "}", "\n", "return", "NewPubSub", "(", "ctx", ",", "h", ",", "rt", ",", "opts", "...", ")", "\n", "}" ]
// NewGossipSub returns a new PubSub object using GossipSubRouter as the router.
[ "NewGossipSub", "returns", "a", "new", "PubSub", "object", "using", "GossipSubRouter", "as", "the", "router", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/gossipsub.go#L39-L50
test
libp2p/go-libp2p-pubsub
pubsub.go
NewPubSub
func NewPubSub(ctx context.Context, h host.Host, rt PubSubRouter, opts ...Option) (*PubSub, error) { ps := &PubSub{ host: h, ctx: ctx, rt: rt, signID: h.ID(), signKey: h.Peerstore().PrivKey(h.ID()), signStrict: true, incoming: make(chan *RPC, 32), publish: make(chan *Message), newPeers: make(chan peer.ID), newPeerStream: make(chan inet.Stream), newPeerError: make(chan peer.ID), peerDead: make(chan peer.ID), cancelCh: make(chan *Subscription), getPeers: make(chan *listPeerReq), addSub: make(chan *addSubReq), getTopics: make(chan *topicReq), sendMsg: make(chan *sendReq, 32), addVal: make(chan *addValReq), rmVal: make(chan *rmValReq), validateThrottle: make(chan struct{}, defaultValidateThrottle), eval: make(chan func()), myTopics: make(map[string]map[*Subscription]struct{}), topics: make(map[string]map[peer.ID]struct{}), peers: make(map[peer.ID]chan *RPC), topicVals: make(map[string]*topicVal), blacklist: NewMapBlacklist(), blacklistPeer: make(chan peer.ID), seenMessages: timecache.NewTimeCache(TimeCacheDuration), counter: uint64(time.Now().UnixNano()), } for _, opt := range opts { err := opt(ps) if err != nil { return nil, err } } if ps.signStrict && ps.signKey == nil { return nil, fmt.Errorf("strict signature verification enabled but message signing is disabled") } rt.Attach(ps) for _, id := range rt.Protocols() { h.SetStreamHandler(id, ps.handleNewStream) } h.Network().Notify((*PubSubNotif)(ps)) go ps.processLoop(ctx) return ps, nil }
go
func NewPubSub(ctx context.Context, h host.Host, rt PubSubRouter, opts ...Option) (*PubSub, error) { ps := &PubSub{ host: h, ctx: ctx, rt: rt, signID: h.ID(), signKey: h.Peerstore().PrivKey(h.ID()), signStrict: true, incoming: make(chan *RPC, 32), publish: make(chan *Message), newPeers: make(chan peer.ID), newPeerStream: make(chan inet.Stream), newPeerError: make(chan peer.ID), peerDead: make(chan peer.ID), cancelCh: make(chan *Subscription), getPeers: make(chan *listPeerReq), addSub: make(chan *addSubReq), getTopics: make(chan *topicReq), sendMsg: make(chan *sendReq, 32), addVal: make(chan *addValReq), rmVal: make(chan *rmValReq), validateThrottle: make(chan struct{}, defaultValidateThrottle), eval: make(chan func()), myTopics: make(map[string]map[*Subscription]struct{}), topics: make(map[string]map[peer.ID]struct{}), peers: make(map[peer.ID]chan *RPC), topicVals: make(map[string]*topicVal), blacklist: NewMapBlacklist(), blacklistPeer: make(chan peer.ID), seenMessages: timecache.NewTimeCache(TimeCacheDuration), counter: uint64(time.Now().UnixNano()), } for _, opt := range opts { err := opt(ps) if err != nil { return nil, err } } if ps.signStrict && ps.signKey == nil { return nil, fmt.Errorf("strict signature verification enabled but message signing is disabled") } rt.Attach(ps) for _, id := range rt.Protocols() { h.SetStreamHandler(id, ps.handleNewStream) } h.Network().Notify((*PubSubNotif)(ps)) go ps.processLoop(ctx) return ps, nil }
[ "func", "NewPubSub", "(", "ctx", "context", ".", "Context", ",", "h", "host", ".", "Host", ",", "rt", "PubSubRouter", ",", "opts", "...", "Option", ")", "(", "*", "PubSub", ",", "error", ")", "{", "ps", ":=", "&", "PubSub", "{", "host", ":", "h", ",", "ctx", ":", "ctx", ",", "rt", ":", "rt", ",", "signID", ":", "h", ".", "ID", "(", ")", ",", "signKey", ":", "h", ".", "Peerstore", "(", ")", ".", "PrivKey", "(", "h", ".", "ID", "(", ")", ")", ",", "signStrict", ":", "true", ",", "incoming", ":", "make", "(", "chan", "*", "RPC", ",", "32", ")", ",", "publish", ":", "make", "(", "chan", "*", "Message", ")", ",", "newPeers", ":", "make", "(", "chan", "peer", ".", "ID", ")", ",", "newPeerStream", ":", "make", "(", "chan", "inet", ".", "Stream", ")", ",", "newPeerError", ":", "make", "(", "chan", "peer", ".", "ID", ")", ",", "peerDead", ":", "make", "(", "chan", "peer", ".", "ID", ")", ",", "cancelCh", ":", "make", "(", "chan", "*", "Subscription", ")", ",", "getPeers", ":", "make", "(", "chan", "*", "listPeerReq", ")", ",", "addSub", ":", "make", "(", "chan", "*", "addSubReq", ")", ",", "getTopics", ":", "make", "(", "chan", "*", "topicReq", ")", ",", "sendMsg", ":", "make", "(", "chan", "*", "sendReq", ",", "32", ")", ",", "addVal", ":", "make", "(", "chan", "*", "addValReq", ")", ",", "rmVal", ":", "make", "(", "chan", "*", "rmValReq", ")", ",", "validateThrottle", ":", "make", "(", "chan", "struct", "{", "}", ",", "defaultValidateThrottle", ")", ",", "eval", ":", "make", "(", "chan", "func", "(", ")", ")", ",", "myTopics", ":", "make", "(", "map", "[", "string", "]", "map", "[", "*", "Subscription", "]", "struct", "{", "}", ")", ",", "topics", ":", "make", "(", "map", "[", "string", "]", "map", "[", "peer", ".", "ID", "]", "struct", "{", "}", ")", ",", "peers", ":", "make", "(", "map", "[", "peer", ".", "ID", "]", "chan", "*", "RPC", ")", ",", "topicVals", ":", "make", "(", "map", "[", "string", "]", "*", "topicVal", ")", ",", "blacklist", ":", "NewMapBlacklist", "(", ")", ",", "blacklistPeer", ":", "make", "(", "chan", "peer", ".", "ID", ")", ",", "seenMessages", ":", "timecache", ".", "NewTimeCache", "(", "TimeCacheDuration", ")", ",", "counter", ":", "uint64", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "err", ":=", "opt", "(", "ps", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "ps", ".", "signStrict", "&&", "ps", ".", "signKey", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"strict signature verification enabled but message signing is disabled\"", ")", "\n", "}", "\n", "rt", ".", "Attach", "(", "ps", ")", "\n", "for", "_", ",", "id", ":=", "range", "rt", ".", "Protocols", "(", ")", "{", "h", ".", "SetStreamHandler", "(", "id", ",", "ps", ".", "handleNewStream", ")", "\n", "}", "\n", "h", ".", "Network", "(", ")", ".", "Notify", "(", "(", "*", "PubSubNotif", ")", "(", "ps", ")", ")", "\n", "go", "ps", ".", "processLoop", "(", "ctx", ")", "\n", "return", "ps", ",", "nil", "\n", "}" ]
// NewPubSub returns a new PubSub management object.
[ "NewPubSub", "returns", "a", "new", "PubSub", "management", "object", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L160-L214
test
libp2p/go-libp2p-pubsub
pubsub.go
WithValidateThrottle
func WithValidateThrottle(n int) Option { return func(ps *PubSub) error { ps.validateThrottle = make(chan struct{}, n) return nil } }
go
func WithValidateThrottle(n int) Option { return func(ps *PubSub) error { ps.validateThrottle = make(chan struct{}, n) return nil } }
[ "func", "WithValidateThrottle", "(", "n", "int", ")", "Option", "{", "return", "func", "(", "ps", "*", "PubSub", ")", "error", "{", "ps", ".", "validateThrottle", "=", "make", "(", "chan", "struct", "{", "}", ",", "n", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithValidateThrottle sets the upper bound on the number of active validation // goroutines.
[ "WithValidateThrottle", "sets", "the", "upper", "bound", "on", "the", "number", "of", "active", "validation", "goroutines", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L218-L223
test
libp2p/go-libp2p-pubsub
pubsub.go
WithBlacklist
func WithBlacklist(b Blacklist) Option { return func(p *PubSub) error { p.blacklist = b return nil } }
go
func WithBlacklist(b Blacklist) Option { return func(p *PubSub) error { p.blacklist = b return nil } }
[ "func", "WithBlacklist", "(", "b", "Blacklist", ")", "Option", "{", "return", "func", "(", "p", "*", "PubSub", ")", "error", "{", "p", ".", "blacklist", "=", "b", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithBlacklist provides an implementation of the blacklist; the default is a // MapBlacklist
[ "WithBlacklist", "provides", "an", "implementation", "of", "the", "blacklist", ";", "the", "default", "is", "a", "MapBlacklist" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L272-L277
test
libp2p/go-libp2p-pubsub
pubsub.go
handleRemoveSubscription
func (p *PubSub) handleRemoveSubscription(sub *Subscription) { subs := p.myTopics[sub.topic] if subs == nil { return } sub.err = fmt.Errorf("subscription cancelled by calling sub.Cancel()") close(sub.ch) delete(subs, sub) if len(subs) == 0 { delete(p.myTopics, sub.topic) p.announce(sub.topic, false) p.rt.Leave(sub.topic) } }
go
func (p *PubSub) handleRemoveSubscription(sub *Subscription) { subs := p.myTopics[sub.topic] if subs == nil { return } sub.err = fmt.Errorf("subscription cancelled by calling sub.Cancel()") close(sub.ch) delete(subs, sub) if len(subs) == 0 { delete(p.myTopics, sub.topic) p.announce(sub.topic, false) p.rt.Leave(sub.topic) } }
[ "func", "(", "p", "*", "PubSub", ")", "handleRemoveSubscription", "(", "sub", "*", "Subscription", ")", "{", "subs", ":=", "p", ".", "myTopics", "[", "sub", ".", "topic", "]", "\n", "if", "subs", "==", "nil", "{", "return", "\n", "}", "\n", "sub", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"subscription cancelled by calling sub.Cancel()\"", ")", "\n", "close", "(", "sub", ".", "ch", ")", "\n", "delete", "(", "subs", ",", "sub", ")", "\n", "if", "len", "(", "subs", ")", "==", "0", "{", "delete", "(", "p", ".", "myTopics", ",", "sub", ".", "topic", ")", "\n", "p", ".", "announce", "(", "sub", ".", "topic", ",", "false", ")", "\n", "p", ".", "rt", ".", "Leave", "(", "sub", ".", "topic", ")", "\n", "}", "\n", "}" ]
// handleRemoveSubscription removes Subscription sub from bookeeping. // If this was the last Subscription for a given topic, it will also announce // that this node is not subscribing to this topic anymore. // Only called from processLoop.
[ "handleRemoveSubscription", "removes", "Subscription", "sub", "from", "bookeeping", ".", "If", "this", "was", "the", "last", "Subscription", "for", "a", "given", "topic", "it", "will", "also", "announce", "that", "this", "node", "is", "not", "subscribing", "to", "this", "topic", "anymore", ".", "Only", "called", "from", "processLoop", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L427-L443
test
libp2p/go-libp2p-pubsub
pubsub.go
handleAddSubscription
func (p *PubSub) handleAddSubscription(req *addSubReq) { sub := req.sub subs := p.myTopics[sub.topic] // announce we want this topic if len(subs) == 0 { p.announce(sub.topic, true) p.rt.Join(sub.topic) } // make new if not there if subs == nil { p.myTopics[sub.topic] = make(map[*Subscription]struct{}) subs = p.myTopics[sub.topic] } sub.ch = make(chan *Message, 32) sub.cancelCh = p.cancelCh p.myTopics[sub.topic][sub] = struct{}{} req.resp <- sub }
go
func (p *PubSub) handleAddSubscription(req *addSubReq) { sub := req.sub subs := p.myTopics[sub.topic] // announce we want this topic if len(subs) == 0 { p.announce(sub.topic, true) p.rt.Join(sub.topic) } // make new if not there if subs == nil { p.myTopics[sub.topic] = make(map[*Subscription]struct{}) subs = p.myTopics[sub.topic] } sub.ch = make(chan *Message, 32) sub.cancelCh = p.cancelCh p.myTopics[sub.topic][sub] = struct{}{} req.resp <- sub }
[ "func", "(", "p", "*", "PubSub", ")", "handleAddSubscription", "(", "req", "*", "addSubReq", ")", "{", "sub", ":=", "req", ".", "sub", "\n", "subs", ":=", "p", ".", "myTopics", "[", "sub", ".", "topic", "]", "\n", "if", "len", "(", "subs", ")", "==", "0", "{", "p", ".", "announce", "(", "sub", ".", "topic", ",", "true", ")", "\n", "p", ".", "rt", ".", "Join", "(", "sub", ".", "topic", ")", "\n", "}", "\n", "if", "subs", "==", "nil", "{", "p", ".", "myTopics", "[", "sub", ".", "topic", "]", "=", "make", "(", "map", "[", "*", "Subscription", "]", "struct", "{", "}", ")", "\n", "subs", "=", "p", ".", "myTopics", "[", "sub", ".", "topic", "]", "\n", "}", "\n", "sub", ".", "ch", "=", "make", "(", "chan", "*", "Message", ",", "32", ")", "\n", "sub", ".", "cancelCh", "=", "p", ".", "cancelCh", "\n", "p", ".", "myTopics", "[", "sub", ".", "topic", "]", "[", "sub", "]", "=", "struct", "{", "}", "{", "}", "\n", "req", ".", "resp", "<-", "sub", "\n", "}" ]
// handleAddSubscription adds a Subscription for a particular topic. If it is // the first Subscription for the topic, it will announce that this node // subscribes to the topic. // Only called from processLoop.
[ "handleAddSubscription", "adds", "a", "Subscription", "for", "a", "particular", "topic", ".", "If", "it", "is", "the", "first", "Subscription", "for", "the", "topic", "it", "will", "announce", "that", "this", "node", "subscribes", "to", "the", "topic", ".", "Only", "called", "from", "processLoop", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L449-L471
test
libp2p/go-libp2p-pubsub
pubsub.go
announce
func (p *PubSub) announce(topic string, sub bool) { subopt := &pb.RPC_SubOpts{ Topicid: &topic, Subscribe: &sub, } out := rpcWithSubs(subopt) for pid, peer := range p.peers { select { case peer <- out: default: log.Infof("Can't send announce message to peer %s: queue full; scheduling retry", pid) go p.announceRetry(pid, topic, sub) } } }
go
func (p *PubSub) announce(topic string, sub bool) { subopt := &pb.RPC_SubOpts{ Topicid: &topic, Subscribe: &sub, } out := rpcWithSubs(subopt) for pid, peer := range p.peers { select { case peer <- out: default: log.Infof("Can't send announce message to peer %s: queue full; scheduling retry", pid) go p.announceRetry(pid, topic, sub) } } }
[ "func", "(", "p", "*", "PubSub", ")", "announce", "(", "topic", "string", ",", "sub", "bool", ")", "{", "subopt", ":=", "&", "pb", ".", "RPC_SubOpts", "{", "Topicid", ":", "&", "topic", ",", "Subscribe", ":", "&", "sub", ",", "}", "\n", "out", ":=", "rpcWithSubs", "(", "subopt", ")", "\n", "for", "pid", ",", "peer", ":=", "range", "p", ".", "peers", "{", "select", "{", "case", "peer", "<-", "out", ":", "default", ":", "log", ".", "Infof", "(", "\"Can't send announce message to peer %s: queue full; scheduling retry\"", ",", "pid", ")", "\n", "go", "p", ".", "announceRetry", "(", "pid", ",", "topic", ",", "sub", ")", "\n", "}", "\n", "}", "\n", "}" ]
// announce announces whether or not this node is interested in a given topic // Only called from processLoop.
[ "announce", "announces", "whether", "or", "not", "this", "node", "is", "interested", "in", "a", "given", "topic", "Only", "called", "from", "processLoop", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L475-L490
test
libp2p/go-libp2p-pubsub
pubsub.go
notifySubs
func (p *PubSub) notifySubs(msg *pb.Message) { for _, topic := range msg.GetTopicIDs() { subs := p.myTopics[topic] for f := range subs { select { case f.ch <- &Message{msg}: default: log.Infof("Can't deliver message to subscription for topic %s; subscriber too slow", topic) } } } }
go
func (p *PubSub) notifySubs(msg *pb.Message) { for _, topic := range msg.GetTopicIDs() { subs := p.myTopics[topic] for f := range subs { select { case f.ch <- &Message{msg}: default: log.Infof("Can't deliver message to subscription for topic %s; subscriber too slow", topic) } } } }
[ "func", "(", "p", "*", "PubSub", ")", "notifySubs", "(", "msg", "*", "pb", ".", "Message", ")", "{", "for", "_", ",", "topic", ":=", "range", "msg", ".", "GetTopicIDs", "(", ")", "{", "subs", ":=", "p", ".", "myTopics", "[", "topic", "]", "\n", "for", "f", ":=", "range", "subs", "{", "select", "{", "case", "f", ".", "ch", "<-", "&", "Message", "{", "msg", "}", ":", "default", ":", "log", ".", "Infof", "(", "\"Can't deliver message to subscription for topic %s; subscriber too slow\"", ",", "topic", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// notifySubs sends a given message to all corresponding subscribers. // Only called from processLoop.
[ "notifySubs", "sends", "a", "given", "message", "to", "all", "corresponding", "subscribers", ".", "Only", "called", "from", "processLoop", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L530-L541
test
libp2p/go-libp2p-pubsub
pubsub.go
seenMessage
func (p *PubSub) seenMessage(id string) bool { return p.seenMessages.Has(id) }
go
func (p *PubSub) seenMessage(id string) bool { return p.seenMessages.Has(id) }
[ "func", "(", "p", "*", "PubSub", ")", "seenMessage", "(", "id", "string", ")", "bool", "{", "return", "p", ".", "seenMessages", ".", "Has", "(", "id", ")", "\n", "}" ]
// seenMessage returns whether we already saw this message before
[ "seenMessage", "returns", "whether", "we", "already", "saw", "this", "message", "before" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L544-L546
test
libp2p/go-libp2p-pubsub
pubsub.go
subscribedToMsg
func (p *PubSub) subscribedToMsg(msg *pb.Message) bool { if len(p.myTopics) == 0 { return false } for _, t := range msg.GetTopicIDs() { if _, ok := p.myTopics[t]; ok { return true } } return false }
go
func (p *PubSub) subscribedToMsg(msg *pb.Message) bool { if len(p.myTopics) == 0 { return false } for _, t := range msg.GetTopicIDs() { if _, ok := p.myTopics[t]; ok { return true } } return false }
[ "func", "(", "p", "*", "PubSub", ")", "subscribedToMsg", "(", "msg", "*", "pb", ".", "Message", ")", "bool", "{", "if", "len", "(", "p", ".", "myTopics", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "msg", ".", "GetTopicIDs", "(", ")", "{", "if", "_", ",", "ok", ":=", "p", ".", "myTopics", "[", "t", "]", ";", "ok", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// subscribedToMessage returns whether we are subscribed to one of the topics // of a given message
[ "subscribedToMessage", "returns", "whether", "we", "are", "subscribed", "to", "one", "of", "the", "topics", "of", "a", "given", "message" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L555-L566
test
libp2p/go-libp2p-pubsub
pubsub.go
msgID
func msgID(pmsg *pb.Message) string { return string(pmsg.GetFrom()) + string(pmsg.GetSeqno()) }
go
func msgID(pmsg *pb.Message) string { return string(pmsg.GetFrom()) + string(pmsg.GetSeqno()) }
[ "func", "msgID", "(", "pmsg", "*", "pb", ".", "Message", ")", "string", "{", "return", "string", "(", "pmsg", ".", "GetFrom", "(", ")", ")", "+", "string", "(", "pmsg", ".", "GetSeqno", "(", ")", ")", "\n", "}" ]
// msgID returns a unique ID of the passed Message
[ "msgID", "returns", "a", "unique", "ID", "of", "the", "passed", "Message" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L603-L605
test
libp2p/go-libp2p-pubsub
pubsub.go
pushMsg
func (p *PubSub) pushMsg(vals []*topicVal, src peer.ID, msg *Message) { // reject messages from blacklisted peers if p.blacklist.Contains(src) { log.Warningf("dropping message from blacklisted peer %s", src) return } // even if they are forwarded by good peers if p.blacklist.Contains(msg.GetFrom()) { log.Warningf("dropping message from blacklisted source %s", src) return } // reject unsigned messages when strict before we even process the id if p.signStrict && msg.Signature == nil { log.Debugf("dropping unsigned message from %s", src) return } // have we already seen and validated this message? id := msgID(msg.Message) if p.seenMessage(id) { return } if len(vals) > 0 || msg.Signature != nil { // validation is asynchronous and globally throttled with the throttleValidate semaphore. // the purpose of the global throttle is to bound the goncurrency possible from incoming // network traffic; each validator also has an individual throttle to preclude // slow (or faulty) validators from starving other topics; see validate below. select { case p.validateThrottle <- struct{}{}: go func() { p.validate(vals, src, msg) <-p.validateThrottle }() default: log.Warningf("message validation throttled; dropping message from %s", src) } return } p.publishMessage(src, msg.Message) }
go
func (p *PubSub) pushMsg(vals []*topicVal, src peer.ID, msg *Message) { // reject messages from blacklisted peers if p.blacklist.Contains(src) { log.Warningf("dropping message from blacklisted peer %s", src) return } // even if they are forwarded by good peers if p.blacklist.Contains(msg.GetFrom()) { log.Warningf("dropping message from blacklisted source %s", src) return } // reject unsigned messages when strict before we even process the id if p.signStrict && msg.Signature == nil { log.Debugf("dropping unsigned message from %s", src) return } // have we already seen and validated this message? id := msgID(msg.Message) if p.seenMessage(id) { return } if len(vals) > 0 || msg.Signature != nil { // validation is asynchronous and globally throttled with the throttleValidate semaphore. // the purpose of the global throttle is to bound the goncurrency possible from incoming // network traffic; each validator also has an individual throttle to preclude // slow (or faulty) validators from starving other topics; see validate below. select { case p.validateThrottle <- struct{}{}: go func() { p.validate(vals, src, msg) <-p.validateThrottle }() default: log.Warningf("message validation throttled; dropping message from %s", src) } return } p.publishMessage(src, msg.Message) }
[ "func", "(", "p", "*", "PubSub", ")", "pushMsg", "(", "vals", "[", "]", "*", "topicVal", ",", "src", "peer", ".", "ID", ",", "msg", "*", "Message", ")", "{", "if", "p", ".", "blacklist", ".", "Contains", "(", "src", ")", "{", "log", ".", "Warningf", "(", "\"dropping message from blacklisted peer %s\"", ",", "src", ")", "\n", "return", "\n", "}", "\n", "if", "p", ".", "blacklist", ".", "Contains", "(", "msg", ".", "GetFrom", "(", ")", ")", "{", "log", ".", "Warningf", "(", "\"dropping message from blacklisted source %s\"", ",", "src", ")", "\n", "return", "\n", "}", "\n", "if", "p", ".", "signStrict", "&&", "msg", ".", "Signature", "==", "nil", "{", "log", ".", "Debugf", "(", "\"dropping unsigned message from %s\"", ",", "src", ")", "\n", "return", "\n", "}", "\n", "id", ":=", "msgID", "(", "msg", ".", "Message", ")", "\n", "if", "p", ".", "seenMessage", "(", "id", ")", "{", "return", "\n", "}", "\n", "if", "len", "(", "vals", ")", ">", "0", "||", "msg", ".", "Signature", "!=", "nil", "{", "select", "{", "case", "p", ".", "validateThrottle", "<-", "struct", "{", "}", "{", "}", ":", "go", "func", "(", ")", "{", "p", ".", "validate", "(", "vals", ",", "src", ",", "msg", ")", "\n", "<-", "p", ".", "validateThrottle", "\n", "}", "(", ")", "\n", "default", ":", "log", ".", "Warningf", "(", "\"message validation throttled; dropping message from %s\"", ",", "src", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "p", ".", "publishMessage", "(", "src", ",", "msg", ".", "Message", ")", "\n", "}" ]
// pushMsg pushes a message performing validation as necessary
[ "pushMsg", "pushes", "a", "message", "performing", "validation", "as", "necessary" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L608-L651
test
libp2p/go-libp2p-pubsub
pubsub.go
validate
func (p *PubSub) validate(vals []*topicVal, src peer.ID, msg *Message) { if msg.Signature != nil { if !p.validateSignature(msg) { log.Warningf("message signature validation failed; dropping message from %s", src) return } } if len(vals) > 0 { if !p.validateTopic(vals, src, msg) { log.Warningf("message validation failed; dropping message from %s", src) return } } // all validators were successful, send the message p.sendMsg <- &sendReq{ from: src, msg: msg, } }
go
func (p *PubSub) validate(vals []*topicVal, src peer.ID, msg *Message) { if msg.Signature != nil { if !p.validateSignature(msg) { log.Warningf("message signature validation failed; dropping message from %s", src) return } } if len(vals) > 0 { if !p.validateTopic(vals, src, msg) { log.Warningf("message validation failed; dropping message from %s", src) return } } // all validators were successful, send the message p.sendMsg <- &sendReq{ from: src, msg: msg, } }
[ "func", "(", "p", "*", "PubSub", ")", "validate", "(", "vals", "[", "]", "*", "topicVal", ",", "src", "peer", ".", "ID", ",", "msg", "*", "Message", ")", "{", "if", "msg", ".", "Signature", "!=", "nil", "{", "if", "!", "p", ".", "validateSignature", "(", "msg", ")", "{", "log", ".", "Warningf", "(", "\"message signature validation failed; dropping message from %s\"", ",", "src", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "len", "(", "vals", ")", ">", "0", "{", "if", "!", "p", ".", "validateTopic", "(", "vals", ",", "src", ",", "msg", ")", "{", "log", ".", "Warningf", "(", "\"message validation failed; dropping message from %s\"", ",", "src", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "p", ".", "sendMsg", "<-", "&", "sendReq", "{", "from", ":", "src", ",", "msg", ":", "msg", ",", "}", "\n", "}" ]
// validate performs validation and only sends the message if all validators succeed
[ "validate", "performs", "validation", "and", "only", "sends", "the", "message", "if", "all", "validators", "succeed" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L654-L674
test
libp2p/go-libp2p-pubsub
pubsub.go
validateSingleTopic
func (p *PubSub) validateSingleTopic(val *topicVal, src peer.ID, msg *Message) bool { select { case val.validateThrottle <- struct{}{}: ctx, cancel := context.WithCancel(p.ctx) defer cancel() res := val.validateMsg(ctx, src, msg) <-val.validateThrottle return res default: log.Debugf("validation throttled for topic %s", val.topic) return false } }
go
func (p *PubSub) validateSingleTopic(val *topicVal, src peer.ID, msg *Message) bool { select { case val.validateThrottle <- struct{}{}: ctx, cancel := context.WithCancel(p.ctx) defer cancel() res := val.validateMsg(ctx, src, msg) <-val.validateThrottle return res default: log.Debugf("validation throttled for topic %s", val.topic) return false } }
[ "func", "(", "p", "*", "PubSub", ")", "validateSingleTopic", "(", "val", "*", "topicVal", ",", "src", "peer", ".", "ID", ",", "msg", "*", "Message", ")", "bool", "{", "select", "{", "case", "val", ".", "validateThrottle", "<-", "struct", "{", "}", "{", "}", ":", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "p", ".", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "res", ":=", "val", ".", "validateMsg", "(", "ctx", ",", "src", ",", "msg", ")", "\n", "<-", "val", ".", "validateThrottle", "\n", "return", "res", "\n", "default", ":", "log", ".", "Debugf", "(", "\"validation throttled for topic %s\"", ",", "val", ".", "topic", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// fast path for single topic validation that avoids the extra goroutine
[ "fast", "path", "for", "single", "topic", "validation", "that", "avoids", "the", "extra", "goroutine" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L731-L746
test
libp2p/go-libp2p-pubsub
pubsub.go
getValidators
func (p *PubSub) getValidators(msg *Message) []*topicVal { var vals []*topicVal for _, topic := range msg.GetTopicIDs() { val, ok := p.topicVals[topic] if !ok { continue } vals = append(vals, val) } return vals }
go
func (p *PubSub) getValidators(msg *Message) []*topicVal { var vals []*topicVal for _, topic := range msg.GetTopicIDs() { val, ok := p.topicVals[topic] if !ok { continue } vals = append(vals, val) } return vals }
[ "func", "(", "p", "*", "PubSub", ")", "getValidators", "(", "msg", "*", "Message", ")", "[", "]", "*", "topicVal", "{", "var", "vals", "[", "]", "*", "topicVal", "\n", "for", "_", ",", "topic", ":=", "range", "msg", ".", "GetTopicIDs", "(", ")", "{", "val", ",", "ok", ":=", "p", ".", "topicVals", "[", "topic", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "vals", "=", "append", "(", "vals", ",", "val", ")", "\n", "}", "\n", "return", "vals", "\n", "}" ]
// getValidators returns all validators that apply to a given message
[ "getValidators", "returns", "all", "validators", "that", "apply", "to", "a", "given", "message" ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L760-L773
test
libp2p/go-libp2p-pubsub
pubsub.go
Subscribe
func (p *PubSub) Subscribe(topic string, opts ...SubOpt) (*Subscription, error) { td := pb.TopicDescriptor{Name: &topic} return p.SubscribeByTopicDescriptor(&td, opts...) }
go
func (p *PubSub) Subscribe(topic string, opts ...SubOpt) (*Subscription, error) { td := pb.TopicDescriptor{Name: &topic} return p.SubscribeByTopicDescriptor(&td, opts...) }
[ "func", "(", "p", "*", "PubSub", ")", "Subscribe", "(", "topic", "string", ",", "opts", "...", "SubOpt", ")", "(", "*", "Subscription", ",", "error", ")", "{", "td", ":=", "pb", ".", "TopicDescriptor", "{", "Name", ":", "&", "topic", "}", "\n", "return", "p", ".", "SubscribeByTopicDescriptor", "(", "&", "td", ",", "opts", "...", ")", "\n", "}" ]
// Subscribe returns a new Subscription for the given topic. // Note that subscription is not an instanteneous operation. It may take some time // before the subscription is processed by the pubsub main loop and propagated to our peers.
[ "Subscribe", "returns", "a", "new", "Subscription", "for", "the", "given", "topic", ".", "Note", "that", "subscription", "is", "not", "an", "instanteneous", "operation", ".", "It", "may", "take", "some", "time", "before", "the", "subscription", "is", "processed", "by", "the", "pubsub", "main", "loop", "and", "propagated", "to", "our", "peers", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L785-L789
test
libp2p/go-libp2p-pubsub
pubsub.go
SubscribeByTopicDescriptor
func (p *PubSub) SubscribeByTopicDescriptor(td *pb.TopicDescriptor, opts ...SubOpt) (*Subscription, error) { if td.GetAuth().GetMode() != pb.TopicDescriptor_AuthOpts_NONE { return nil, fmt.Errorf("auth mode not yet supported") } if td.GetEnc().GetMode() != pb.TopicDescriptor_EncOpts_NONE { return nil, fmt.Errorf("encryption mode not yet supported") } sub := &Subscription{ topic: td.GetName(), } for _, opt := range opts { err := opt(sub) if err != nil { return nil, err } } out := make(chan *Subscription, 1) p.addSub <- &addSubReq{ sub: sub, resp: out, } return <-out, nil }
go
func (p *PubSub) SubscribeByTopicDescriptor(td *pb.TopicDescriptor, opts ...SubOpt) (*Subscription, error) { if td.GetAuth().GetMode() != pb.TopicDescriptor_AuthOpts_NONE { return nil, fmt.Errorf("auth mode not yet supported") } if td.GetEnc().GetMode() != pb.TopicDescriptor_EncOpts_NONE { return nil, fmt.Errorf("encryption mode not yet supported") } sub := &Subscription{ topic: td.GetName(), } for _, opt := range opts { err := opt(sub) if err != nil { return nil, err } } out := make(chan *Subscription, 1) p.addSub <- &addSubReq{ sub: sub, resp: out, } return <-out, nil }
[ "func", "(", "p", "*", "PubSub", ")", "SubscribeByTopicDescriptor", "(", "td", "*", "pb", ".", "TopicDescriptor", ",", "opts", "...", "SubOpt", ")", "(", "*", "Subscription", ",", "error", ")", "{", "if", "td", ".", "GetAuth", "(", ")", ".", "GetMode", "(", ")", "!=", "pb", ".", "TopicDescriptor_AuthOpts_NONE", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"auth mode not yet supported\"", ")", "\n", "}", "\n", "if", "td", ".", "GetEnc", "(", ")", ".", "GetMode", "(", ")", "!=", "pb", ".", "TopicDescriptor_EncOpts_NONE", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"encryption mode not yet supported\"", ")", "\n", "}", "\n", "sub", ":=", "&", "Subscription", "{", "topic", ":", "td", ".", "GetName", "(", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "err", ":=", "opt", "(", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "out", ":=", "make", "(", "chan", "*", "Subscription", ",", "1", ")", "\n", "p", ".", "addSub", "<-", "&", "addSubReq", "{", "sub", ":", "sub", ",", "resp", ":", "out", ",", "}", "\n", "return", "<-", "out", ",", "nil", "\n", "}" ]
// SubscribeByTopicDescriptor lets you subscribe a topic using a pb.TopicDescriptor.
[ "SubscribeByTopicDescriptor", "lets", "you", "subscribe", "a", "topic", "using", "a", "pb", ".", "TopicDescriptor", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L792-L819
test
libp2p/go-libp2p-pubsub
pubsub.go
GetTopics
func (p *PubSub) GetTopics() []string { out := make(chan []string, 1) p.getTopics <- &topicReq{resp: out} return <-out }
go
func (p *PubSub) GetTopics() []string { out := make(chan []string, 1) p.getTopics <- &topicReq{resp: out} return <-out }
[ "func", "(", "p", "*", "PubSub", ")", "GetTopics", "(", ")", "[", "]", "string", "{", "out", ":=", "make", "(", "chan", "[", "]", "string", ",", "1", ")", "\n", "p", ".", "getTopics", "<-", "&", "topicReq", "{", "resp", ":", "out", "}", "\n", "return", "<-", "out", "\n", "}" ]
// GetTopics returns the topics this node is subscribed to.
[ "GetTopics", "returns", "the", "topics", "this", "node", "is", "subscribed", "to", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L826-L830
test
libp2p/go-libp2p-pubsub
pubsub.go
Publish
func (p *PubSub) Publish(topic string, data []byte) error { seqno := p.nextSeqno() m := &pb.Message{ Data: data, TopicIDs: []string{topic}, From: []byte(p.host.ID()), Seqno: seqno, } if p.signKey != nil { m.From = []byte(p.signID) err := signMessage(p.signID, p.signKey, m) if err != nil { return err } } p.publish <- &Message{m} return nil }
go
func (p *PubSub) Publish(topic string, data []byte) error { seqno := p.nextSeqno() m := &pb.Message{ Data: data, TopicIDs: []string{topic}, From: []byte(p.host.ID()), Seqno: seqno, } if p.signKey != nil { m.From = []byte(p.signID) err := signMessage(p.signID, p.signKey, m) if err != nil { return err } } p.publish <- &Message{m} return nil }
[ "func", "(", "p", "*", "PubSub", ")", "Publish", "(", "topic", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "seqno", ":=", "p", ".", "nextSeqno", "(", ")", "\n", "m", ":=", "&", "pb", ".", "Message", "{", "Data", ":", "data", ",", "TopicIDs", ":", "[", "]", "string", "{", "topic", "}", ",", "From", ":", "[", "]", "byte", "(", "p", ".", "host", ".", "ID", "(", ")", ")", ",", "Seqno", ":", "seqno", ",", "}", "\n", "if", "p", ".", "signKey", "!=", "nil", "{", "m", ".", "From", "=", "[", "]", "byte", "(", "p", ".", "signID", ")", "\n", "err", ":=", "signMessage", "(", "p", ".", "signID", ",", "p", ".", "signKey", ",", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "p", ".", "publish", "<-", "&", "Message", "{", "m", "}", "\n", "return", "nil", "\n", "}" ]
// Publish publishes data to the given topic.
[ "Publish", "publishes", "data", "to", "the", "given", "topic", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L833-L850
test
libp2p/go-libp2p-pubsub
pubsub.go
ListPeers
func (p *PubSub) ListPeers(topic string) []peer.ID { out := make(chan []peer.ID) p.getPeers <- &listPeerReq{ resp: out, topic: topic, } return <-out }
go
func (p *PubSub) ListPeers(topic string) []peer.ID { out := make(chan []peer.ID) p.getPeers <- &listPeerReq{ resp: out, topic: topic, } return <-out }
[ "func", "(", "p", "*", "PubSub", ")", "ListPeers", "(", "topic", "string", ")", "[", "]", "peer", ".", "ID", "{", "out", ":=", "make", "(", "chan", "[", "]", "peer", ".", "ID", ")", "\n", "p", ".", "getPeers", "<-", "&", "listPeerReq", "{", "resp", ":", "out", ",", "topic", ":", "topic", ",", "}", "\n", "return", "<-", "out", "\n", "}" ]
// ListPeers returns a list of peers we are connected to in the given topic.
[ "ListPeers", "returns", "a", "list", "of", "peers", "we", "are", "connected", "to", "in", "the", "given", "topic", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L872-L879
test
libp2p/go-libp2p-pubsub
pubsub.go
WithValidatorTimeout
func WithValidatorTimeout(timeout time.Duration) ValidatorOpt { return func(addVal *addValReq) error { addVal.timeout = timeout return nil } }
go
func WithValidatorTimeout(timeout time.Duration) ValidatorOpt { return func(addVal *addValReq) error { addVal.timeout = timeout return nil } }
[ "func", "WithValidatorTimeout", "(", "timeout", "time", ".", "Duration", ")", "ValidatorOpt", "{", "return", "func", "(", "addVal", "*", "addValReq", ")", "error", "{", "addVal", ".", "timeout", "=", "timeout", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithValidatorTimeout is an option that sets the topic validator timeout.
[ "WithValidatorTimeout", "is", "an", "option", "that", "sets", "the", "topic", "validator", "timeout", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L914-L919
test
libp2p/go-libp2p-pubsub
pubsub.go
WithValidatorConcurrency
func WithValidatorConcurrency(n int) ValidatorOpt { return func(addVal *addValReq) error { addVal.throttle = n return nil } }
go
func WithValidatorConcurrency(n int) ValidatorOpt { return func(addVal *addValReq) error { addVal.throttle = n return nil } }
[ "func", "WithValidatorConcurrency", "(", "n", "int", ")", "ValidatorOpt", "{", "return", "func", "(", "addVal", "*", "addValReq", ")", "error", "{", "addVal", ".", "throttle", "=", "n", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithValidatorConcurrency is an option that sets topic validator throttle.
[ "WithValidatorConcurrency", "is", "an", "option", "that", "sets", "topic", "validator", "throttle", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L922-L927
test
libp2p/go-libp2p-pubsub
pubsub.go
RegisterTopicValidator
func (p *PubSub) RegisterTopicValidator(topic string, val Validator, opts ...ValidatorOpt) error { addVal := &addValReq{ topic: topic, validate: val, resp: make(chan error, 1), } for _, opt := range opts { err := opt(addVal) if err != nil { return err } } p.addVal <- addVal return <-addVal.resp }
go
func (p *PubSub) RegisterTopicValidator(topic string, val Validator, opts ...ValidatorOpt) error { addVal := &addValReq{ topic: topic, validate: val, resp: make(chan error, 1), } for _, opt := range opts { err := opt(addVal) if err != nil { return err } } p.addVal <- addVal return <-addVal.resp }
[ "func", "(", "p", "*", "PubSub", ")", "RegisterTopicValidator", "(", "topic", "string", ",", "val", "Validator", ",", "opts", "...", "ValidatorOpt", ")", "error", "{", "addVal", ":=", "&", "addValReq", "{", "topic", ":", "topic", ",", "validate", ":", "val", ",", "resp", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "err", ":=", "opt", "(", "addVal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "p", ".", "addVal", "<-", "addVal", "\n", "return", "<-", "addVal", ".", "resp", "\n", "}" ]
// RegisterTopicValidator registers a validator for topic.
[ "RegisterTopicValidator", "registers", "a", "validator", "for", "topic", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L930-L946
test
libp2p/go-libp2p-pubsub
pubsub.go
UnregisterTopicValidator
func (p *PubSub) UnregisterTopicValidator(topic string) error { rmVal := &rmValReq{ topic: topic, resp: make(chan error, 1), } p.rmVal <- rmVal return <-rmVal.resp }
go
func (p *PubSub) UnregisterTopicValidator(topic string) error { rmVal := &rmValReq{ topic: topic, resp: make(chan error, 1), } p.rmVal <- rmVal return <-rmVal.resp }
[ "func", "(", "p", "*", "PubSub", ")", "UnregisterTopicValidator", "(", "topic", "string", ")", "error", "{", "rmVal", ":=", "&", "rmValReq", "{", "topic", ":", "topic", ",", "resp", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "}", "\n", "p", ".", "rmVal", "<-", "rmVal", "\n", "return", "<-", "rmVal", ".", "resp", "\n", "}" ]
// UnregisterTopicValidator removes a validator from a topic. // Returns an error if there was no validator registered with the topic.
[ "UnregisterTopicValidator", "removes", "a", "validator", "from", "a", "topic", ".", "Returns", "an", "error", "if", "there", "was", "no", "validator", "registered", "with", "the", "topic", "." ]
9db3dbdde90f44d1c420192c5cefd60682fbdbb9
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L978-L986
test
uber/tchannel-go
stats/metrickey.go
DefaultMetricPrefix
func DefaultMetricPrefix(name string, tags map[string]string) string { return MetricWithPrefix("tchannel.", name, tags) }
go
func DefaultMetricPrefix(name string, tags map[string]string) string { return MetricWithPrefix("tchannel.", name, tags) }
[ "func", "DefaultMetricPrefix", "(", "name", "string", ",", "tags", "map", "[", "string", "]", "string", ")", "string", "{", "return", "MetricWithPrefix", "(", "\"tchannel.\"", ",", "name", ",", "tags", ")", "\n", "}" ]
// DefaultMetricPrefix is the default mapping for metrics to statsd keys. // It uses a "tchannel" prefix for all stats.
[ "DefaultMetricPrefix", "is", "the", "default", "mapping", "for", "metrics", "to", "statsd", "keys", ".", "It", "uses", "a", "tchannel", "prefix", "for", "all", "stats", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/stats/metrickey.go#L31-L33
test
uber/tchannel-go
stats/metrickey.go
MetricWithPrefix
func MetricWithPrefix(prefix, name string, tags map[string]string) string { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() if prefix != "" { buf.WriteString(prefix) } buf.WriteString(name) addKeys := make([]string, 0, 5) switch { case strings.HasPrefix(name, "outbound"): addKeys = append(addKeys, "service", "target-service", "target-endpoint") if strings.HasPrefix(name, "outbound.calls.retries") { addKeys = append(addKeys, "retry-count") } case strings.HasPrefix(name, "inbound"): addKeys = append(addKeys, "calling-service", "service", "endpoint") } for _, k := range addKeys { buf.WriteByte('.') v, ok := tags[k] if ok { writeClean(buf, v) } else { buf.WriteString("no-") buf.WriteString(k) } } m := buf.String() bufPool.Put(buf) return m }
go
func MetricWithPrefix(prefix, name string, tags map[string]string) string { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() if prefix != "" { buf.WriteString(prefix) } buf.WriteString(name) addKeys := make([]string, 0, 5) switch { case strings.HasPrefix(name, "outbound"): addKeys = append(addKeys, "service", "target-service", "target-endpoint") if strings.HasPrefix(name, "outbound.calls.retries") { addKeys = append(addKeys, "retry-count") } case strings.HasPrefix(name, "inbound"): addKeys = append(addKeys, "calling-service", "service", "endpoint") } for _, k := range addKeys { buf.WriteByte('.') v, ok := tags[k] if ok { writeClean(buf, v) } else { buf.WriteString("no-") buf.WriteString(k) } } m := buf.String() bufPool.Put(buf) return m }
[ "func", "MetricWithPrefix", "(", "prefix", ",", "name", "string", ",", "tags", "map", "[", "string", "]", "string", ")", "string", "{", "buf", ":=", "bufPool", ".", "Get", "(", ")", ".", "(", "*", "bytes", ".", "Buffer", ")", "\n", "buf", ".", "Reset", "(", ")", "\n", "if", "prefix", "!=", "\"\"", "{", "buf", ".", "WriteString", "(", "prefix", ")", "\n", "}", "\n", "buf", ".", "WriteString", "(", "name", ")", "\n", "addKeys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "5", ")", "\n", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "name", ",", "\"outbound\"", ")", ":", "addKeys", "=", "append", "(", "addKeys", ",", "\"service\"", ",", "\"target-service\"", ",", "\"target-endpoint\"", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"outbound.calls.retries\"", ")", "{", "addKeys", "=", "append", "(", "addKeys", ",", "\"retry-count\"", ")", "\n", "}", "\n", "case", "strings", ".", "HasPrefix", "(", "name", ",", "\"inbound\"", ")", ":", "addKeys", "=", "append", "(", "addKeys", ",", "\"calling-service\"", ",", "\"service\"", ",", "\"endpoint\"", ")", "\n", "}", "\n", "for", "_", ",", "k", ":=", "range", "addKeys", "{", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "v", ",", "ok", ":=", "tags", "[", "k", "]", "\n", "if", "ok", "{", "writeClean", "(", "buf", ",", "v", ")", "\n", "}", "else", "{", "buf", ".", "WriteString", "(", "\"no-\"", ")", "\n", "buf", ".", "WriteString", "(", "k", ")", "\n", "}", "\n", "}", "\n", "m", ":=", "buf", ".", "String", "(", ")", "\n", "bufPool", ".", "Put", "(", "buf", ")", "\n", "return", "m", "\n", "}" ]
// MetricWithPrefix is the default mapping for metrics to statsd keys.
[ "MetricWithPrefix", "is", "the", "default", "mapping", "for", "metrics", "to", "statsd", "keys", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/stats/metrickey.go#L40-L74
test
uber/tchannel-go
json/call.go
NewClient
func NewClient(ch *tchannel.Channel, targetService string, opts *ClientOptions) *Client { client := &Client{ ch: ch, targetService: targetService, } if opts != nil && opts.HostPort != "" { client.hostPort = opts.HostPort } return client }
go
func NewClient(ch *tchannel.Channel, targetService string, opts *ClientOptions) *Client { client := &Client{ ch: ch, targetService: targetService, } if opts != nil && opts.HostPort != "" { client.hostPort = opts.HostPort } return client }
[ "func", "NewClient", "(", "ch", "*", "tchannel", ".", "Channel", ",", "targetService", "string", ",", "opts", "*", "ClientOptions", ")", "*", "Client", "{", "client", ":=", "&", "Client", "{", "ch", ":", "ch", ",", "targetService", ":", "targetService", ",", "}", "\n", "if", "opts", "!=", "nil", "&&", "opts", ".", "HostPort", "!=", "\"\"", "{", "client", ".", "hostPort", "=", "opts", ".", "HostPort", "\n", "}", "\n", "return", "client", "\n", "}" ]
// NewClient returns a json.Client used to make outbound JSON calls.
[ "NewClient", "returns", "a", "json", ".", "Client", "used", "to", "make", "outbound", "JSON", "calls", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/call.go#L51-L60
test
uber/tchannel-go
json/call.go
Call
func (c *Client) Call(ctx Context, method string, arg, resp interface{}) error { var ( headers = ctx.Headers() respHeaders map[string]string respErr ErrApplication errAt string isOK bool ) err := c.ch.RunWithRetry(ctx, func(ctx context.Context, rs *tchannel.RequestState) error { respHeaders, respErr, isOK = nil, nil, false errAt = "connect" call, err := c.startCall(ctx, method, &tchannel.CallOptions{ Format: tchannel.JSON, RequestState: rs, }) if err != nil { return err } isOK, errAt, err = makeCall(call, headers, arg, &respHeaders, resp, &respErr) return err }) if err != nil { // TODO: Don't lose the error type here. return fmt.Errorf("%s: %v", errAt, err) } if !isOK { return respErr } return nil }
go
func (c *Client) Call(ctx Context, method string, arg, resp interface{}) error { var ( headers = ctx.Headers() respHeaders map[string]string respErr ErrApplication errAt string isOK bool ) err := c.ch.RunWithRetry(ctx, func(ctx context.Context, rs *tchannel.RequestState) error { respHeaders, respErr, isOK = nil, nil, false errAt = "connect" call, err := c.startCall(ctx, method, &tchannel.CallOptions{ Format: tchannel.JSON, RequestState: rs, }) if err != nil { return err } isOK, errAt, err = makeCall(call, headers, arg, &respHeaders, resp, &respErr) return err }) if err != nil { // TODO: Don't lose the error type here. return fmt.Errorf("%s: %v", errAt, err) } if !isOK { return respErr } return nil }
[ "func", "(", "c", "*", "Client", ")", "Call", "(", "ctx", "Context", ",", "method", "string", ",", "arg", ",", "resp", "interface", "{", "}", ")", "error", "{", "var", "(", "headers", "=", "ctx", ".", "Headers", "(", ")", "\n", "respHeaders", "map", "[", "string", "]", "string", "\n", "respErr", "ErrApplication", "\n", "errAt", "string", "\n", "isOK", "bool", "\n", ")", "\n", "err", ":=", "c", ".", "ch", ".", "RunWithRetry", "(", "ctx", ",", "func", "(", "ctx", "context", ".", "Context", ",", "rs", "*", "tchannel", ".", "RequestState", ")", "error", "{", "respHeaders", ",", "respErr", ",", "isOK", "=", "nil", ",", "nil", ",", "false", "\n", "errAt", "=", "\"connect\"", "\n", "call", ",", "err", ":=", "c", ".", "startCall", "(", "ctx", ",", "method", ",", "&", "tchannel", ".", "CallOptions", "{", "Format", ":", "tchannel", ".", "JSON", ",", "RequestState", ":", "rs", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "isOK", ",", "errAt", ",", "err", "=", "makeCall", "(", "call", ",", "headers", ",", "arg", ",", "&", "respHeaders", ",", "resp", ",", "&", "respErr", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"%s: %v\"", ",", "errAt", ",", "err", ")", "\n", "}", "\n", "if", "!", "isOK", "{", "return", "respErr", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Call makes a JSON call, with retries.
[ "Call", "makes", "a", "JSON", "call", "with", "retries", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/call.go#L102-L136
test
uber/tchannel-go
json/call.go
CallPeer
func CallPeer(ctx Context, peer *tchannel.Peer, serviceName, method string, arg, resp interface{}) error { call, err := peer.BeginCall(ctx, serviceName, method, &tchannel.CallOptions{Format: tchannel.JSON}) if err != nil { return err } return wrapCall(ctx, call, method, arg, resp) }
go
func CallPeer(ctx Context, peer *tchannel.Peer, serviceName, method string, arg, resp interface{}) error { call, err := peer.BeginCall(ctx, serviceName, method, &tchannel.CallOptions{Format: tchannel.JSON}) if err != nil { return err } return wrapCall(ctx, call, method, arg, resp) }
[ "func", "CallPeer", "(", "ctx", "Context", ",", "peer", "*", "tchannel", ".", "Peer", ",", "serviceName", ",", "method", "string", ",", "arg", ",", "resp", "interface", "{", "}", ")", "error", "{", "call", ",", "err", ":=", "peer", ".", "BeginCall", "(", "ctx", ",", "serviceName", ",", "method", ",", "&", "tchannel", ".", "CallOptions", "{", "Format", ":", "tchannel", ".", "JSON", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "wrapCall", "(", "ctx", ",", "call", ",", "method", ",", "arg", ",", "resp", ")", "\n", "}" ]
// CallPeer makes a JSON call using the given peer.
[ "CallPeer", "makes", "a", "JSON", "call", "using", "the", "given", "peer", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/call.go#L155-L162
test
uber/tchannel-go
json/call.go
CallSC
func CallSC(ctx Context, sc *tchannel.SubChannel, method string, arg, resp interface{}) error { call, err := sc.BeginCall(ctx, method, &tchannel.CallOptions{Format: tchannel.JSON}) if err != nil { return err } return wrapCall(ctx, call, method, arg, resp) }
go
func CallSC(ctx Context, sc *tchannel.SubChannel, method string, arg, resp interface{}) error { call, err := sc.BeginCall(ctx, method, &tchannel.CallOptions{Format: tchannel.JSON}) if err != nil { return err } return wrapCall(ctx, call, method, arg, resp) }
[ "func", "CallSC", "(", "ctx", "Context", ",", "sc", "*", "tchannel", ".", "SubChannel", ",", "method", "string", ",", "arg", ",", "resp", "interface", "{", "}", ")", "error", "{", "call", ",", "err", ":=", "sc", ".", "BeginCall", "(", "ctx", ",", "method", ",", "&", "tchannel", ".", "CallOptions", "{", "Format", ":", "tchannel", ".", "JSON", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "wrapCall", "(", "ctx", ",", "call", ",", "method", ",", "arg", ",", "resp", ")", "\n", "}" ]
// CallSC makes a JSON call using the given subchannel.
[ "CallSC", "makes", "a", "JSON", "call", "using", "the", "given", "subchannel", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/call.go#L165-L172
test
uber/tchannel-go
http/response.go
ReadResponse
func ReadResponse(call tchannel.ArgReadable) (*http.Response, error) { var arg2 []byte if err := tchannel.NewArgReader(call.Arg2Reader()).Read(&arg2); err != nil { return nil, err } rb := typed.NewReadBuffer(arg2) statusCode := rb.ReadUint16() message := readVarintString(rb) response := &http.Response{ StatusCode: int(statusCode), Status: fmt.Sprintf("%v %v", statusCode, message), Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), } readHeaders(rb, response.Header) if err := rb.Err(); err != nil { return nil, err } arg3Reader, err := call.Arg3Reader() if err != nil { return nil, err } response.Body = arg3Reader return response, nil }
go
func ReadResponse(call tchannel.ArgReadable) (*http.Response, error) { var arg2 []byte if err := tchannel.NewArgReader(call.Arg2Reader()).Read(&arg2); err != nil { return nil, err } rb := typed.NewReadBuffer(arg2) statusCode := rb.ReadUint16() message := readVarintString(rb) response := &http.Response{ StatusCode: int(statusCode), Status: fmt.Sprintf("%v %v", statusCode, message), Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), } readHeaders(rb, response.Header) if err := rb.Err(); err != nil { return nil, err } arg3Reader, err := call.Arg3Reader() if err != nil { return nil, err } response.Body = arg3Reader return response, nil }
[ "func", "ReadResponse", "(", "call", "tchannel", ".", "ArgReadable", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "var", "arg2", "[", "]", "byte", "\n", "if", "err", ":=", "tchannel", ".", "NewArgReader", "(", "call", ".", "Arg2Reader", "(", ")", ")", ".", "Read", "(", "&", "arg2", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rb", ":=", "typed", ".", "NewReadBuffer", "(", "arg2", ")", "\n", "statusCode", ":=", "rb", ".", "ReadUint16", "(", ")", "\n", "message", ":=", "readVarintString", "(", "rb", ")", "\n", "response", ":=", "&", "http", ".", "Response", "{", "StatusCode", ":", "int", "(", "statusCode", ")", ",", "Status", ":", "fmt", ".", "Sprintf", "(", "\"%v %v\"", ",", "statusCode", ",", "message", ")", ",", "Proto", ":", "\"HTTP/1.1\"", ",", "ProtoMajor", ":", "1", ",", "ProtoMinor", ":", "1", ",", "Header", ":", "make", "(", "http", ".", "Header", ")", ",", "}", "\n", "readHeaders", "(", "rb", ",", "response", ".", "Header", ")", "\n", "if", "err", ":=", "rb", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "arg3Reader", ",", "err", ":=", "call", ".", "Arg3Reader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "response", ".", "Body", "=", "arg3Reader", "\n", "return", "response", ",", "nil", "\n", "}" ]
// ReadResponse reads a http.Response from the given readers.
[ "ReadResponse", "reads", "a", "http", ".", "Response", "from", "the", "given", "readers", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/http/response.go#L33-L63
test
uber/tchannel-go
http/response.go
writeHeaders
func (w *tchanResponseWriter) writeHeaders() { // TODO(prashant): Allow creating write buffers that let you grow the buffer underneath. wb := typed.NewWriteBufferWithSize(10000) wb.WriteUint16(uint16(w.statusCode)) writeVarintString(wb, http.StatusText(w.statusCode)) writeHeaders(wb, w.headers) arg2Writer, err := w.response.Arg2Writer() if err != nil { w.err = err return } if _, w.err = wb.FlushTo(arg2Writer); w.err != nil { return } if w.err = arg2Writer.Close(); w.err != nil { return } w.arg3Writer, w.err = w.response.Arg3Writer() }
go
func (w *tchanResponseWriter) writeHeaders() { // TODO(prashant): Allow creating write buffers that let you grow the buffer underneath. wb := typed.NewWriteBufferWithSize(10000) wb.WriteUint16(uint16(w.statusCode)) writeVarintString(wb, http.StatusText(w.statusCode)) writeHeaders(wb, w.headers) arg2Writer, err := w.response.Arg2Writer() if err != nil { w.err = err return } if _, w.err = wb.FlushTo(arg2Writer); w.err != nil { return } if w.err = arg2Writer.Close(); w.err != nil { return } w.arg3Writer, w.err = w.response.Arg3Writer() }
[ "func", "(", "w", "*", "tchanResponseWriter", ")", "writeHeaders", "(", ")", "{", "wb", ":=", "typed", ".", "NewWriteBufferWithSize", "(", "10000", ")", "\n", "wb", ".", "WriteUint16", "(", "uint16", "(", "w", ".", "statusCode", ")", ")", "\n", "writeVarintString", "(", "wb", ",", "http", ".", "StatusText", "(", "w", ".", "statusCode", ")", ")", "\n", "writeHeaders", "(", "wb", ",", "w", ".", "headers", ")", "\n", "arg2Writer", ",", "err", ":=", "w", ".", "response", ".", "Arg2Writer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "w", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "if", "_", ",", "w", ".", "err", "=", "wb", ".", "FlushTo", "(", "arg2Writer", ")", ";", "w", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "w", ".", "err", "=", "arg2Writer", ".", "Close", "(", ")", ";", "w", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "w", ".", "arg3Writer", ",", "w", ".", "err", "=", "w", ".", "response", ".", "Arg3Writer", "(", ")", "\n", "}" ]
// writeHeaders writes out the HTTP headers as arg2, and creates the arg3 writer.
[ "writeHeaders", "writes", "out", "the", "HTTP", "headers", "as", "arg2", "and", "creates", "the", "arg3", "writer", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/http/response.go#L90-L110
test
uber/tchannel-go
http/response.go
ResponseWriter
func ResponseWriter(response tchannel.ArgWritable) (http.ResponseWriter, func() error) { responseWriter := newTChanResponseWriter(response) return responseWriter, responseWriter.finish }
go
func ResponseWriter(response tchannel.ArgWritable) (http.ResponseWriter, func() error) { responseWriter := newTChanResponseWriter(response) return responseWriter, responseWriter.finish }
[ "func", "ResponseWriter", "(", "response", "tchannel", ".", "ArgWritable", ")", "(", "http", ".", "ResponseWriter", ",", "func", "(", ")", "error", ")", "{", "responseWriter", ":=", "newTChanResponseWriter", "(", "response", ")", "\n", "return", "responseWriter", ",", "responseWriter", ".", "finish", "\n", "}" ]
// ResponseWriter returns a http.ResponseWriter that will write to an underlying writer. // It also returns a function that should be called once the handler has completed.
[ "ResponseWriter", "returns", "a", "http", ".", "ResponseWriter", "that", "will", "write", "to", "an", "underlying", "writer", ".", "It", "also", "returns", "a", "function", "that", "should", "be", "called", "once", "the", "handler", "has", "completed", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/http/response.go#L136-L139
test
uber/tchannel-go
thrift/headers.go
ReadHeaders
func ReadHeaders(r io.Reader) (map[string]string, error) { reader := typed.NewReader(r) m, err := readHeaders(reader) reader.Release() return m, err }
go
func ReadHeaders(r io.Reader) (map[string]string, error) { reader := typed.NewReader(r) m, err := readHeaders(reader) reader.Release() return m, err }
[ "func", "ReadHeaders", "(", "r", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "reader", ":=", "typed", ".", "NewReader", "(", "r", ")", "\n", "m", ",", "err", ":=", "readHeaders", "(", "reader", ")", "\n", "reader", ".", "Release", "(", ")", "\n", "return", "m", ",", "err", "\n", "}" ]
// ReadHeaders reads key-value pairs encoded using WriteHeaders.
[ "ReadHeaders", "reads", "key", "-", "value", "pairs", "encoded", "using", "WriteHeaders", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/headers.go#L84-L90
test
uber/tchannel-go
benchmark/tcp_raw_relay.go
NewTCPRawRelay
func NewTCPRawRelay(dests []string) (Relay, error) { return newTCPRelay(dests, func(_ bool, src, dst net.Conn) { io.Copy(src, dst) }) }
go
func NewTCPRawRelay(dests []string) (Relay, error) { return newTCPRelay(dests, func(_ bool, src, dst net.Conn) { io.Copy(src, dst) }) }
[ "func", "NewTCPRawRelay", "(", "dests", "[", "]", "string", ")", "(", "Relay", ",", "error", ")", "{", "return", "newTCPRelay", "(", "dests", ",", "func", "(", "_", "bool", ",", "src", ",", "dst", "net", ".", "Conn", ")", "{", "io", ".", "Copy", "(", "src", ",", "dst", ")", "\n", "}", ")", "\n", "}" ]
// NewTCPRawRelay creates a relay that just pipes data from one connection // to another directly.
[ "NewTCPRawRelay", "creates", "a", "relay", "that", "just", "pipes", "data", "from", "one", "connection", "to", "another", "directly", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/benchmark/tcp_raw_relay.go#L55-L59
test
uber/tchannel-go
hyperbahn/client.go
NewClient
func NewClient(ch *tchannel.Channel, config Configuration, opts *ClientOptions) (*Client, error) { client := &Client{tchan: ch, quit: make(chan struct{})} if opts != nil { client.opts = *opts } if client.opts.Timeout == 0 { client.opts.Timeout = 3 * time.Second } if client.opts.TimeoutPerAttempt == 0 { client.opts.TimeoutPerAttempt = time.Second } if client.opts.Handler == nil { client.opts.Handler = nullHandler{} } if client.opts.TimeSleep == nil { client.opts.TimeSleep = time.Sleep } if err := parseConfig(&config); err != nil { return nil, err } // Add the given initial nodes as peers. for _, node := range config.InitialNodes { addPeer(ch, node) } client.jsonClient = tjson.NewClient(ch, hyperbahnServiceName, nil) thriftClient := tthrift.NewClient(ch, hyperbahnServiceName, nil) client.hyperbahnClient = htypes.NewTChanHyperbahnClient(thriftClient) return client, nil }
go
func NewClient(ch *tchannel.Channel, config Configuration, opts *ClientOptions) (*Client, error) { client := &Client{tchan: ch, quit: make(chan struct{})} if opts != nil { client.opts = *opts } if client.opts.Timeout == 0 { client.opts.Timeout = 3 * time.Second } if client.opts.TimeoutPerAttempt == 0 { client.opts.TimeoutPerAttempt = time.Second } if client.opts.Handler == nil { client.opts.Handler = nullHandler{} } if client.opts.TimeSleep == nil { client.opts.TimeSleep = time.Sleep } if err := parseConfig(&config); err != nil { return nil, err } // Add the given initial nodes as peers. for _, node := range config.InitialNodes { addPeer(ch, node) } client.jsonClient = tjson.NewClient(ch, hyperbahnServiceName, nil) thriftClient := tthrift.NewClient(ch, hyperbahnServiceName, nil) client.hyperbahnClient = htypes.NewTChanHyperbahnClient(thriftClient) return client, nil }
[ "func", "NewClient", "(", "ch", "*", "tchannel", ".", "Channel", ",", "config", "Configuration", ",", "opts", "*", "ClientOptions", ")", "(", "*", "Client", ",", "error", ")", "{", "client", ":=", "&", "Client", "{", "tchan", ":", "ch", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", "}", "\n", "if", "opts", "!=", "nil", "{", "client", ".", "opts", "=", "*", "opts", "\n", "}", "\n", "if", "client", ".", "opts", ".", "Timeout", "==", "0", "{", "client", ".", "opts", ".", "Timeout", "=", "3", "*", "time", ".", "Second", "\n", "}", "\n", "if", "client", ".", "opts", ".", "TimeoutPerAttempt", "==", "0", "{", "client", ".", "opts", ".", "TimeoutPerAttempt", "=", "time", ".", "Second", "\n", "}", "\n", "if", "client", ".", "opts", ".", "Handler", "==", "nil", "{", "client", ".", "opts", ".", "Handler", "=", "nullHandler", "{", "}", "\n", "}", "\n", "if", "client", ".", "opts", ".", "TimeSleep", "==", "nil", "{", "client", ".", "opts", ".", "TimeSleep", "=", "time", ".", "Sleep", "\n", "}", "\n", "if", "err", ":=", "parseConfig", "(", "&", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "node", ":=", "range", "config", ".", "InitialNodes", "{", "addPeer", "(", "ch", ",", "node", ")", "\n", "}", "\n", "client", ".", "jsonClient", "=", "tjson", ".", "NewClient", "(", "ch", ",", "hyperbahnServiceName", ",", "nil", ")", "\n", "thriftClient", ":=", "tthrift", ".", "NewClient", "(", "ch", ",", "hyperbahnServiceName", ",", "nil", ")", "\n", "client", ".", "hyperbahnClient", "=", "htypes", ".", "NewTChanHyperbahnClient", "(", "thriftClient", ")", "\n", "return", "client", ",", "nil", "\n", "}" ]
// NewClient creates a new Hyperbahn client using the given channel. // config is the environment-specific configuration for Hyperbahn such as the list of initial nodes. // opts are optional, and are used to customize the client.
[ "NewClient", "creates", "a", "new", "Hyperbahn", "client", "using", "the", "given", "channel", ".", "config", "is", "the", "environment", "-", "specific", "configuration", "for", "Hyperbahn", "such", "as", "the", "list", "of", "initial", "nodes", ".", "opts", "are", "optional", "and", "are", "used", "to", "customize", "the", "client", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L94-L126
test
uber/tchannel-go
hyperbahn/client.go
Advertise
func (c *Client) Advertise(otherServices ...tchannel.Registrar) error { c.getServiceNames(otherServices) if err := c.initialAdvertise(); err != nil { return err } c.opts.Handler.On(Advertised) go c.advertiseLoop() return nil }
go
func (c *Client) Advertise(otherServices ...tchannel.Registrar) error { c.getServiceNames(otherServices) if err := c.initialAdvertise(); err != nil { return err } c.opts.Handler.On(Advertised) go c.advertiseLoop() return nil }
[ "func", "(", "c", "*", "Client", ")", "Advertise", "(", "otherServices", "...", "tchannel", ".", "Registrar", ")", "error", "{", "c", ".", "getServiceNames", "(", "otherServices", ")", "\n", "if", "err", ":=", "c", ".", "initialAdvertise", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "opts", ".", "Handler", ".", "On", "(", "Advertised", ")", "\n", "go", "c", ".", "advertiseLoop", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Advertise advertises the service with Hyperbahn, and returns any errors on initial advertisement. // Advertise can register multiple services hosted on the same endpoint. // If the advertisement succeeds, a goroutine is started to re-advertise periodically.
[ "Advertise", "advertises", "the", "service", "with", "Hyperbahn", "and", "returns", "any", "errors", "on", "initial", "advertisement", ".", "Advertise", "can", "register", "multiple", "services", "hosted", "on", "the", "same", "endpoint", ".", "If", "the", "advertisement", "succeeds", "a", "goroutine", "is", "started", "to", "re", "-", "advertise", "periodically", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L175-L185
test
uber/tchannel-go
json/handler.go
Handle
func (h *handler) Handle(tctx context.Context, call *tchannel.InboundCall) error { var headers map[string]string if err := tchannel.NewArgReader(call.Arg2Reader()).ReadJSON(&headers); err != nil { return fmt.Errorf("arg2 read failed: %v", err) } tctx = tchannel.ExtractInboundSpan(tctx, call, headers, h.tracer()) ctx := WithHeaders(tctx, headers) var arg3 reflect.Value var callArg reflect.Value if h.isArgMap { arg3 = reflect.New(h.argType) // New returns a pointer, but the method accepts the map directly. callArg = arg3.Elem() } else { arg3 = reflect.New(h.argType.Elem()) callArg = arg3 } if err := tchannel.NewArgReader(call.Arg3Reader()).ReadJSON(arg3.Interface()); err != nil { return fmt.Errorf("arg3 read failed: %v", err) } args := []reflect.Value{reflect.ValueOf(ctx), callArg} results := h.handler.Call(args) res := results[0].Interface() err := results[1].Interface() // If an error was returned, we create an error arg3 to respond with. if err != nil { // TODO(prashantv): More consistent error handling between json/raw/thrift.. if serr, ok := err.(tchannel.SystemError); ok { return call.Response().SendSystemError(serr) } call.Response().SetApplicationError() // TODO(prashant): Allow client to customize the error in more ways. res = struct { Type string `json:"type"` Message string `json:"message"` }{ Type: "error", Message: err.(error).Error(), } } if err := tchannel.NewArgWriter(call.Response().Arg2Writer()).WriteJSON(ctx.ResponseHeaders()); err != nil { return err } return tchannel.NewArgWriter(call.Response().Arg3Writer()).WriteJSON(res) }
go
func (h *handler) Handle(tctx context.Context, call *tchannel.InboundCall) error { var headers map[string]string if err := tchannel.NewArgReader(call.Arg2Reader()).ReadJSON(&headers); err != nil { return fmt.Errorf("arg2 read failed: %v", err) } tctx = tchannel.ExtractInboundSpan(tctx, call, headers, h.tracer()) ctx := WithHeaders(tctx, headers) var arg3 reflect.Value var callArg reflect.Value if h.isArgMap { arg3 = reflect.New(h.argType) // New returns a pointer, but the method accepts the map directly. callArg = arg3.Elem() } else { arg3 = reflect.New(h.argType.Elem()) callArg = arg3 } if err := tchannel.NewArgReader(call.Arg3Reader()).ReadJSON(arg3.Interface()); err != nil { return fmt.Errorf("arg3 read failed: %v", err) } args := []reflect.Value{reflect.ValueOf(ctx), callArg} results := h.handler.Call(args) res := results[0].Interface() err := results[1].Interface() // If an error was returned, we create an error arg3 to respond with. if err != nil { // TODO(prashantv): More consistent error handling between json/raw/thrift.. if serr, ok := err.(tchannel.SystemError); ok { return call.Response().SendSystemError(serr) } call.Response().SetApplicationError() // TODO(prashant): Allow client to customize the error in more ways. res = struct { Type string `json:"type"` Message string `json:"message"` }{ Type: "error", Message: err.(error).Error(), } } if err := tchannel.NewArgWriter(call.Response().Arg2Writer()).WriteJSON(ctx.ResponseHeaders()); err != nil { return err } return tchannel.NewArgWriter(call.Response().Arg3Writer()).WriteJSON(res) }
[ "func", "(", "h", "*", "handler", ")", "Handle", "(", "tctx", "context", ".", "Context", ",", "call", "*", "tchannel", ".", "InboundCall", ")", "error", "{", "var", "headers", "map", "[", "string", "]", "string", "\n", "if", "err", ":=", "tchannel", ".", "NewArgReader", "(", "call", ".", "Arg2Reader", "(", ")", ")", ".", "ReadJSON", "(", "&", "headers", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"arg2 read failed: %v\"", ",", "err", ")", "\n", "}", "\n", "tctx", "=", "tchannel", ".", "ExtractInboundSpan", "(", "tctx", ",", "call", ",", "headers", ",", "h", ".", "tracer", "(", ")", ")", "\n", "ctx", ":=", "WithHeaders", "(", "tctx", ",", "headers", ")", "\n", "var", "arg3", "reflect", ".", "Value", "\n", "var", "callArg", "reflect", ".", "Value", "\n", "if", "h", ".", "isArgMap", "{", "arg3", "=", "reflect", ".", "New", "(", "h", ".", "argType", ")", "\n", "callArg", "=", "arg3", ".", "Elem", "(", ")", "\n", "}", "else", "{", "arg3", "=", "reflect", ".", "New", "(", "h", ".", "argType", ".", "Elem", "(", ")", ")", "\n", "callArg", "=", "arg3", "\n", "}", "\n", "if", "err", ":=", "tchannel", ".", "NewArgReader", "(", "call", ".", "Arg3Reader", "(", ")", ")", ".", "ReadJSON", "(", "arg3", ".", "Interface", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"arg3 read failed: %v\"", ",", "err", ")", "\n", "}", "\n", "args", ":=", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "ctx", ")", ",", "callArg", "}", "\n", "results", ":=", "h", ".", "handler", ".", "Call", "(", "args", ")", "\n", "res", ":=", "results", "[", "0", "]", ".", "Interface", "(", ")", "\n", "err", ":=", "results", "[", "1", "]", ".", "Interface", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "serr", ",", "ok", ":=", "err", ".", "(", "tchannel", ".", "SystemError", ")", ";", "ok", "{", "return", "call", ".", "Response", "(", ")", ".", "SendSystemError", "(", "serr", ")", "\n", "}", "\n", "call", ".", "Response", "(", ")", ".", "SetApplicationError", "(", ")", "\n", "res", "=", "struct", "{", "Type", "string", "`json:\"type\"`", "\n", "Message", "string", "`json:\"message\"`", "\n", "}", "{", "Type", ":", "\"error\"", ",", "Message", ":", "err", ".", "(", "error", ")", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "if", "err", ":=", "tchannel", ".", "NewArgWriter", "(", "call", ".", "Response", "(", ")", ".", "Arg2Writer", "(", ")", ")", ".", "WriteJSON", "(", "ctx", ".", "ResponseHeaders", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "tchannel", ".", "NewArgWriter", "(", "call", ".", "Response", "(", ")", ".", "Arg3Writer", "(", ")", ")", ".", "WriteJSON", "(", "res", ")", "\n", "}" ]
// Handle deserializes the JSON arguments and calls the underlying handler.
[ "Handle", "deserializes", "the", "JSON", "arguments", "and", "calls", "the", "underlying", "handler", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/handler.go#L127-L177
test
uber/tchannel-go
crossdock/server/server.go
Start
func (s *Server) Start() error { if s.HostPort == "" { s.HostPort = ":" + common.DefaultServerPort } channelOpts := &tchannel.ChannelOptions{ Tracer: s.Tracer, } ch, err := tchannel.NewChannel(common.DefaultServiceName, channelOpts) if err != nil { return err } if err := ch.ListenAndServe(s.HostPort); err != nil { return err } s.HostPort = ch.PeerInfo().HostPort // override in case it was ":0" log.Printf("Started tchannel server at %s\n", s.HostPort) s.Ch = ch return nil }
go
func (s *Server) Start() error { if s.HostPort == "" { s.HostPort = ":" + common.DefaultServerPort } channelOpts := &tchannel.ChannelOptions{ Tracer: s.Tracer, } ch, err := tchannel.NewChannel(common.DefaultServiceName, channelOpts) if err != nil { return err } if err := ch.ListenAndServe(s.HostPort); err != nil { return err } s.HostPort = ch.PeerInfo().HostPort // override in case it was ":0" log.Printf("Started tchannel server at %s\n", s.HostPort) s.Ch = ch return nil }
[ "func", "(", "s", "*", "Server", ")", "Start", "(", ")", "error", "{", "if", "s", ".", "HostPort", "==", "\"\"", "{", "s", ".", "HostPort", "=", "\":\"", "+", "common", ".", "DefaultServerPort", "\n", "}", "\n", "channelOpts", ":=", "&", "tchannel", ".", "ChannelOptions", "{", "Tracer", ":", "s", ".", "Tracer", ",", "}", "\n", "ch", ",", "err", ":=", "tchannel", ".", "NewChannel", "(", "common", ".", "DefaultServiceName", ",", "channelOpts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ch", ".", "ListenAndServe", "(", "s", ".", "HostPort", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "HostPort", "=", "ch", ".", "PeerInfo", "(", ")", ".", "HostPort", "\n", "log", ".", "Printf", "(", "\"Started tchannel server at %s\\n\"", ",", "\\n", ")", "\n", "s", ".", "HostPort", "\n", "s", ".", "Ch", "=", "ch", "\n", "}" ]
// Start starts the test server called by the Client and other upstream servers.
[ "Start", "starts", "the", "test", "server", "called", "by", "the", "Client", "and", "other", "upstream", "servers", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/server/server.go#L60-L79
test
uber/tchannel-go
crossdock/server/server.go
Port
func (s *Server) Port() string { hostPortSplit := strings.Split(s.HostPort, ":") port := hostPortSplit[len(hostPortSplit)-1] return port }
go
func (s *Server) Port() string { hostPortSplit := strings.Split(s.HostPort, ":") port := hostPortSplit[len(hostPortSplit)-1] return port }
[ "func", "(", "s", "*", "Server", ")", "Port", "(", ")", "string", "{", "hostPortSplit", ":=", "strings", ".", "Split", "(", "s", ".", "HostPort", ",", "\":\"", ")", "\n", "port", ":=", "hostPortSplit", "[", "len", "(", "hostPortSplit", ")", "-", "1", "]", "\n", "return", "port", "\n", "}" ]
// Port returns the actual port the server listens to
[ "Port", "returns", "the", "actual", "port", "the", "server", "listens", "to" ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/server/server.go#L87-L91
test
uber/tchannel-go
peer.go
SetStrategy
func (l *PeerList) SetStrategy(sc ScoreCalculator) { l.Lock() defer l.Unlock() l.scoreCalculator = sc for _, ps := range l.peersByHostPort { newScore := l.scoreCalculator.GetScore(ps.Peer) l.updatePeer(ps, newScore) } }
go
func (l *PeerList) SetStrategy(sc ScoreCalculator) { l.Lock() defer l.Unlock() l.scoreCalculator = sc for _, ps := range l.peersByHostPort { newScore := l.scoreCalculator.GetScore(ps.Peer) l.updatePeer(ps, newScore) } }
[ "func", "(", "l", "*", "PeerList", ")", "SetStrategy", "(", "sc", "ScoreCalculator", ")", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "l", ".", "scoreCalculator", "=", "sc", "\n", "for", "_", ",", "ps", ":=", "range", "l", ".", "peersByHostPort", "{", "newScore", ":=", "l", ".", "scoreCalculator", ".", "GetScore", "(", "ps", ".", "Peer", ")", "\n", "l", ".", "updatePeer", "(", "ps", ",", "newScore", ")", "\n", "}", "\n", "}" ]
// SetStrategy sets customized peer selection strategy.
[ "SetStrategy", "sets", "customized", "peer", "selection", "strategy", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L83-L92
test
uber/tchannel-go
peer.go
Add
func (l *PeerList) Add(hostPort string) *Peer { if ps, ok := l.exists(hostPort); ok { return ps.Peer } l.Lock() defer l.Unlock() if p, ok := l.peersByHostPort[hostPort]; ok { return p.Peer } p := l.parent.Add(hostPort) p.addSC() ps := newPeerScore(p, l.scoreCalculator.GetScore(p)) l.peersByHostPort[hostPort] = ps l.peerHeap.addPeer(ps) return p }
go
func (l *PeerList) Add(hostPort string) *Peer { if ps, ok := l.exists(hostPort); ok { return ps.Peer } l.Lock() defer l.Unlock() if p, ok := l.peersByHostPort[hostPort]; ok { return p.Peer } p := l.parent.Add(hostPort) p.addSC() ps := newPeerScore(p, l.scoreCalculator.GetScore(p)) l.peersByHostPort[hostPort] = ps l.peerHeap.addPeer(ps) return p }
[ "func", "(", "l", "*", "PeerList", ")", "Add", "(", "hostPort", "string", ")", "*", "Peer", "{", "if", "ps", ",", "ok", ":=", "l", ".", "exists", "(", "hostPort", ")", ";", "ok", "{", "return", "ps", ".", "Peer", "\n", "}", "\n", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "if", "p", ",", "ok", ":=", "l", ".", "peersByHostPort", "[", "hostPort", "]", ";", "ok", "{", "return", "p", ".", "Peer", "\n", "}", "\n", "p", ":=", "l", ".", "parent", ".", "Add", "(", "hostPort", ")", "\n", "p", ".", "addSC", "(", ")", "\n", "ps", ":=", "newPeerScore", "(", "p", ",", "l", ".", "scoreCalculator", ".", "GetScore", "(", "p", ")", ")", "\n", "l", ".", "peersByHostPort", "[", "hostPort", "]", "=", "ps", "\n", "l", ".", "peerHeap", ".", "addPeer", "(", "ps", ")", "\n", "return", "p", "\n", "}" ]
// Add adds a peer to the list if it does not exist, or returns any existing peer.
[ "Add", "adds", "a", "peer", "to", "the", "list", "if", "it", "does", "not", "exist", "or", "returns", "any", "existing", "peer", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L102-L120
test
uber/tchannel-go
peer.go
GetNew
func (l *PeerList) GetNew(prevSelected map[string]struct{}) (*Peer, error) { l.Lock() defer l.Unlock() if l.peerHeap.Len() == 0 { return nil, ErrNoPeers } // Select a peer, avoiding previously selected peers. If all peers have been previously // selected, then it's OK to repick them. peer := l.choosePeer(prevSelected, true /* avoidHost */) if peer == nil { peer = l.choosePeer(prevSelected, false /* avoidHost */) } if peer == nil { return nil, ErrNoNewPeers } return peer, nil }
go
func (l *PeerList) GetNew(prevSelected map[string]struct{}) (*Peer, error) { l.Lock() defer l.Unlock() if l.peerHeap.Len() == 0 { return nil, ErrNoPeers } // Select a peer, avoiding previously selected peers. If all peers have been previously // selected, then it's OK to repick them. peer := l.choosePeer(prevSelected, true /* avoidHost */) if peer == nil { peer = l.choosePeer(prevSelected, false /* avoidHost */) } if peer == nil { return nil, ErrNoNewPeers } return peer, nil }
[ "func", "(", "l", "*", "PeerList", ")", "GetNew", "(", "prevSelected", "map", "[", "string", "]", "struct", "{", "}", ")", "(", "*", "Peer", ",", "error", ")", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "if", "l", ".", "peerHeap", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", ",", "ErrNoPeers", "\n", "}", "\n", "peer", ":=", "l", ".", "choosePeer", "(", "prevSelected", ",", "true", ")", "\n", "if", "peer", "==", "nil", "{", "peer", "=", "l", ".", "choosePeer", "(", "prevSelected", ",", "false", ")", "\n", "}", "\n", "if", "peer", "==", "nil", "{", "return", "nil", ",", "ErrNoNewPeers", "\n", "}", "\n", "return", "peer", ",", "nil", "\n", "}" ]
// GetNew returns a new, previously unselected peer from the peer list, or nil, // if no new unselected peer can be found.
[ "GetNew", "returns", "a", "new", "previously", "unselected", "peer", "from", "the", "peer", "list", "or", "nil", "if", "no", "new", "unselected", "peer", "can", "be", "found", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L124-L141
test
uber/tchannel-go
peer.go
Get
func (l *PeerList) Get(prevSelected map[string]struct{}) (*Peer, error) { peer, err := l.GetNew(prevSelected) if err == ErrNoNewPeers { l.Lock() peer = l.choosePeer(nil, false /* avoidHost */) l.Unlock() } else if err != nil { return nil, err } if peer == nil { return nil, ErrNoPeers } return peer, nil }
go
func (l *PeerList) Get(prevSelected map[string]struct{}) (*Peer, error) { peer, err := l.GetNew(prevSelected) if err == ErrNoNewPeers { l.Lock() peer = l.choosePeer(nil, false /* avoidHost */) l.Unlock() } else if err != nil { return nil, err } if peer == nil { return nil, ErrNoPeers } return peer, nil }
[ "func", "(", "l", "*", "PeerList", ")", "Get", "(", "prevSelected", "map", "[", "string", "]", "struct", "{", "}", ")", "(", "*", "Peer", ",", "error", ")", "{", "peer", ",", "err", ":=", "l", ".", "GetNew", "(", "prevSelected", ")", "\n", "if", "err", "==", "ErrNoNewPeers", "{", "l", ".", "Lock", "(", ")", "\n", "peer", "=", "l", ".", "choosePeer", "(", "nil", ",", "false", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "peer", "==", "nil", "{", "return", "nil", ",", "ErrNoPeers", "\n", "}", "\n", "return", "peer", ",", "nil", "\n", "}" ]
// Get returns a peer from the peer list, or nil if none can be found, // will avoid previously selected peers if possible.
[ "Get", "returns", "a", "peer", "from", "the", "peer", "list", "or", "nil", "if", "none", "can", "be", "found", "will", "avoid", "previously", "selected", "peers", "if", "possible", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L145-L158
test
uber/tchannel-go
peer.go
Remove
func (l *PeerList) Remove(hostPort string) error { l.Lock() defer l.Unlock() p, ok := l.peersByHostPort[hostPort] if !ok { return ErrPeerNotFound } p.delSC() delete(l.peersByHostPort, hostPort) l.peerHeap.removePeer(p) return nil }
go
func (l *PeerList) Remove(hostPort string) error { l.Lock() defer l.Unlock() p, ok := l.peersByHostPort[hostPort] if !ok { return ErrPeerNotFound } p.delSC() delete(l.peersByHostPort, hostPort) l.peerHeap.removePeer(p) return nil }
[ "func", "(", "l", "*", "PeerList", ")", "Remove", "(", "hostPort", "string", ")", "error", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n", "p", ",", "ok", ":=", "l", ".", "peersByHostPort", "[", "hostPort", "]", "\n", "if", "!", "ok", "{", "return", "ErrPeerNotFound", "\n", "}", "\n", "p", ".", "delSC", "(", ")", "\n", "delete", "(", "l", ".", "peersByHostPort", ",", "hostPort", ")", "\n", "l", ".", "peerHeap", ".", "removePeer", "(", "p", ")", "\n", "return", "nil", "\n", "}" ]
// Remove removes a peer from the peer list. It returns an error if the peer cannot be found. // Remove does not affect connections to the peer in any way.
[ "Remove", "removes", "a", "peer", "from", "the", "peer", "list", ".", "It", "returns", "an", "error", "if", "the", "peer", "cannot", "be", "found", ".", "Remove", "does", "not", "affect", "connections", "to", "the", "peer", "in", "any", "way", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L162-L176
test
uber/tchannel-go
peer.go
Copy
func (l *PeerList) Copy() map[string]*Peer { l.RLock() defer l.RUnlock() listCopy := make(map[string]*Peer) for k, v := range l.peersByHostPort { listCopy[k] = v.Peer } return listCopy }
go
func (l *PeerList) Copy() map[string]*Peer { l.RLock() defer l.RUnlock() listCopy := make(map[string]*Peer) for k, v := range l.peersByHostPort { listCopy[k] = v.Peer } return listCopy }
[ "func", "(", "l", "*", "PeerList", ")", "Copy", "(", ")", "map", "[", "string", "]", "*", "Peer", "{", "l", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "RUnlock", "(", ")", "\n", "listCopy", ":=", "make", "(", "map", "[", "string", "]", "*", "Peer", ")", "\n", "for", "k", ",", "v", ":=", "range", "l", ".", "peersByHostPort", "{", "listCopy", "[", "k", "]", "=", "v", ".", "Peer", "\n", "}", "\n", "return", "listCopy", "\n", "}" ]
// Copy returns a copy of the PeerList as a map from hostPort to peer.
[ "Copy", "returns", "a", "copy", "of", "the", "PeerList", "as", "a", "map", "from", "hostPort", "to", "peer", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L226-L235
test
uber/tchannel-go
peer.go
Len
func (l *PeerList) Len() int { l.RLock() defer l.RUnlock() return l.peerHeap.Len() }
go
func (l *PeerList) Len() int { l.RLock() defer l.RUnlock() return l.peerHeap.Len() }
[ "func", "(", "l", "*", "PeerList", ")", "Len", "(", ")", "int", "{", "l", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "RUnlock", "(", ")", "\n", "return", "l", ".", "peerHeap", ".", "Len", "(", ")", "\n", "}" ]
// Len returns the length of the PeerList.
[ "Len", "returns", "the", "length", "of", "the", "PeerList", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L238-L242
test
uber/tchannel-go
peer.go
exists
func (l *PeerList) exists(hostPort string) (*peerScore, bool) { l.RLock() ps, ok := l.peersByHostPort[hostPort] l.RUnlock() return ps, ok }
go
func (l *PeerList) exists(hostPort string) (*peerScore, bool) { l.RLock() ps, ok := l.peersByHostPort[hostPort] l.RUnlock() return ps, ok }
[ "func", "(", "l", "*", "PeerList", ")", "exists", "(", "hostPort", "string", ")", "(", "*", "peerScore", ",", "bool", ")", "{", "l", ".", "RLock", "(", ")", "\n", "ps", ",", "ok", ":=", "l", ".", "peersByHostPort", "[", "hostPort", "]", "\n", "l", ".", "RUnlock", "(", ")", "\n", "return", "ps", ",", "ok", "\n", "}" ]
// exists checks if a hostport exists in the peer list.
[ "exists", "checks", "if", "a", "hostport", "exists", "in", "the", "peer", "list", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L245-L251
test
uber/tchannel-go
peer.go
getPeerScore
func (l *PeerList) getPeerScore(hostPort string) (*peerScore, uint64, bool) { ps, ok := l.peersByHostPort[hostPort] if !ok { return nil, 0, false } return ps, ps.score, ok }
go
func (l *PeerList) getPeerScore(hostPort string) (*peerScore, uint64, bool) { ps, ok := l.peersByHostPort[hostPort] if !ok { return nil, 0, false } return ps, ps.score, ok }
[ "func", "(", "l", "*", "PeerList", ")", "getPeerScore", "(", "hostPort", "string", ")", "(", "*", "peerScore", ",", "uint64", ",", "bool", ")", "{", "ps", ",", "ok", ":=", "l", ".", "peersByHostPort", "[", "hostPort", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "0", ",", "false", "\n", "}", "\n", "return", "ps", ",", "ps", ".", "score", ",", "ok", "\n", "}" ]
// getPeerScore is called to find the peer and its score from a host port key. // Note that at least a Read lock must be held to call this function.
[ "getPeerScore", "is", "called", "to", "find", "the", "peer", "and", "its", "score", "from", "a", "host", "port", "key", ".", "Note", "that", "at", "least", "a", "Read", "lock", "must", "be", "held", "to", "call", "this", "function", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L255-L261
test
uber/tchannel-go
peer.go
onPeerChange
func (l *PeerList) onPeerChange(p *Peer) { l.RLock() ps, psScore, ok := l.getPeerScore(p.hostPort) sc := l.scoreCalculator l.RUnlock() if !ok { return } newScore := sc.GetScore(ps.Peer) if newScore == psScore { return } l.Lock() l.updatePeer(ps, newScore) l.Unlock() }
go
func (l *PeerList) onPeerChange(p *Peer) { l.RLock() ps, psScore, ok := l.getPeerScore(p.hostPort) sc := l.scoreCalculator l.RUnlock() if !ok { return } newScore := sc.GetScore(ps.Peer) if newScore == psScore { return } l.Lock() l.updatePeer(ps, newScore) l.Unlock() }
[ "func", "(", "l", "*", "PeerList", ")", "onPeerChange", "(", "p", "*", "Peer", ")", "{", "l", ".", "RLock", "(", ")", "\n", "ps", ",", "psScore", ",", "ok", ":=", "l", ".", "getPeerScore", "(", "p", ".", "hostPort", ")", "\n", "sc", ":=", "l", ".", "scoreCalculator", "\n", "l", ".", "RUnlock", "(", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "newScore", ":=", "sc", ".", "GetScore", "(", "ps", ".", "Peer", ")", "\n", "if", "newScore", "==", "psScore", "{", "return", "\n", "}", "\n", "l", ".", "Lock", "(", ")", "\n", "l", ".", "updatePeer", "(", "ps", ",", "newScore", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "}" ]
// onPeerChange is called when there is a change that may cause the peer's score to change. // The new score is calculated, and the peer heap is updated with the new score if the score changes.
[ "onPeerChange", "is", "called", "when", "there", "is", "a", "change", "that", "may", "cause", "the", "peer", "s", "score", "to", "change", ".", "The", "new", "score", "is", "calculated", "and", "the", "peer", "heap", "is", "updated", "with", "the", "new", "score", "if", "the", "score", "changes", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L265-L282
test
uber/tchannel-go
peer.go
updatePeer
func (l *PeerList) updatePeer(ps *peerScore, newScore uint64) { if ps.score == newScore { return } ps.score = newScore l.peerHeap.updatePeer(ps) }
go
func (l *PeerList) updatePeer(ps *peerScore, newScore uint64) { if ps.score == newScore { return } ps.score = newScore l.peerHeap.updatePeer(ps) }
[ "func", "(", "l", "*", "PeerList", ")", "updatePeer", "(", "ps", "*", "peerScore", ",", "newScore", "uint64", ")", "{", "if", "ps", ".", "score", "==", "newScore", "{", "return", "\n", "}", "\n", "ps", ".", "score", "=", "newScore", "\n", "l", ".", "peerHeap", ".", "updatePeer", "(", "ps", ")", "\n", "}" ]
// updatePeer is called to update the score of the peer given the existing score. // Note that a Write lock must be held to call this function.
[ "updatePeer", "is", "called", "to", "update", "the", "score", "of", "the", "peer", "given", "the", "existing", "score", ".", "Note", "that", "a", "Write", "lock", "must", "be", "held", "to", "call", "this", "function", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L286-L293
test
uber/tchannel-go
peer.go
getConn
func (p *Peer) getConn(i int) *Connection { inboundLen := len(p.inboundConnections) if i < inboundLen { return p.inboundConnections[i] } return p.outboundConnections[i-inboundLen] }
go
func (p *Peer) getConn(i int) *Connection { inboundLen := len(p.inboundConnections) if i < inboundLen { return p.inboundConnections[i] } return p.outboundConnections[i-inboundLen] }
[ "func", "(", "p", "*", "Peer", ")", "getConn", "(", "i", "int", ")", "*", "Connection", "{", "inboundLen", ":=", "len", "(", "p", ".", "inboundConnections", ")", "\n", "if", "i", "<", "inboundLen", "{", "return", "p", ".", "inboundConnections", "[", "i", "]", "\n", "}", "\n", "return", "p", ".", "outboundConnections", "[", "i", "-", "inboundLen", "]", "\n", "}" ]
// getConn treats inbound and outbound connections as a single virtual list // that can be indexed. The peer must be read-locked.
[ "getConn", "treats", "inbound", "and", "outbound", "connections", "as", "a", "single", "virtual", "list", "that", "can", "be", "indexed", ".", "The", "peer", "must", "be", "read", "-", "locked", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L361-L368
test
uber/tchannel-go
peer.go
GetConnection
func (p *Peer) GetConnection(ctx context.Context) (*Connection, error) { if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // Lock here to restrict new connection creation attempts to one goroutine p.newConnLock.Lock() defer p.newConnLock.Unlock() // Check active connections again in case someone else got ahead of us. if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // No active connections, make a new outgoing connection. return p.Connect(ctx) }
go
func (p *Peer) GetConnection(ctx context.Context) (*Connection, error) { if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // Lock here to restrict new connection creation attempts to one goroutine p.newConnLock.Lock() defer p.newConnLock.Unlock() // Check active connections again in case someone else got ahead of us. if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // No active connections, make a new outgoing connection. return p.Connect(ctx) }
[ "func", "(", "p", "*", "Peer", ")", "GetConnection", "(", "ctx", "context", ".", "Context", ")", "(", "*", "Connection", ",", "error", ")", "{", "if", "activeConn", ",", "ok", ":=", "p", ".", "getActiveConn", "(", ")", ";", "ok", "{", "return", "activeConn", ",", "nil", "\n", "}", "\n", "p", ".", "newConnLock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "newConnLock", ".", "Unlock", "(", ")", "\n", "if", "activeConn", ",", "ok", ":=", "p", ".", "getActiveConn", "(", ")", ";", "ok", "{", "return", "activeConn", ",", "nil", "\n", "}", "\n", "return", "p", ".", "Connect", "(", "ctx", ")", "\n", "}" ]
// GetConnection returns an active connection to this peer. If no active connections // are found, it will create a new outbound connection and return it.
[ "GetConnection", "returns", "an", "active", "connection", "to", "this", "peer", ".", "If", "no", "active", "connections", "are", "found", "it", "will", "create", "a", "new", "outbound", "connection", "and", "return", "it", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L402-L418
test
uber/tchannel-go
peer.go
getConnectionRelay
func (p *Peer) getConnectionRelay(timeout time.Duration) (*Connection, error) { if conn, ok := p.getActiveConn(); ok { return conn, nil } // Lock here to restrict new connection creation attempts to one goroutine p.newConnLock.Lock() defer p.newConnLock.Unlock() // Check active connections again in case someone else got ahead of us. if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // When the relay creates outbound connections, we don't want those services // to ever connect back to us and send us traffic. We hide the host:port // so that service instances on remote machines don't try to connect back // and don't try to send Hyperbahn traffic on this connection. ctx, cancel := NewContextBuilder(timeout).HideListeningOnOutbound().Build() defer cancel() return p.Connect(ctx) }
go
func (p *Peer) getConnectionRelay(timeout time.Duration) (*Connection, error) { if conn, ok := p.getActiveConn(); ok { return conn, nil } // Lock here to restrict new connection creation attempts to one goroutine p.newConnLock.Lock() defer p.newConnLock.Unlock() // Check active connections again in case someone else got ahead of us. if activeConn, ok := p.getActiveConn(); ok { return activeConn, nil } // When the relay creates outbound connections, we don't want those services // to ever connect back to us and send us traffic. We hide the host:port // so that service instances on remote machines don't try to connect back // and don't try to send Hyperbahn traffic on this connection. ctx, cancel := NewContextBuilder(timeout).HideListeningOnOutbound().Build() defer cancel() return p.Connect(ctx) }
[ "func", "(", "p", "*", "Peer", ")", "getConnectionRelay", "(", "timeout", "time", ".", "Duration", ")", "(", "*", "Connection", ",", "error", ")", "{", "if", "conn", ",", "ok", ":=", "p", ".", "getActiveConn", "(", ")", ";", "ok", "{", "return", "conn", ",", "nil", "\n", "}", "\n", "p", ".", "newConnLock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "newConnLock", ".", "Unlock", "(", ")", "\n", "if", "activeConn", ",", "ok", ":=", "p", ".", "getActiveConn", "(", ")", ";", "ok", "{", "return", "activeConn", ",", "nil", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "NewContextBuilder", "(", "timeout", ")", ".", "HideListeningOnOutbound", "(", ")", ".", "Build", "(", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "p", ".", "Connect", "(", "ctx", ")", "\n", "}" ]
// getConnectionRelay gets a connection, and uses the given timeout to lazily // create a context if a new connection is required.
[ "getConnectionRelay", "gets", "a", "connection", "and", "uses", "the", "given", "timeout", "to", "lazily", "create", "a", "context", "if", "a", "new", "connection", "is", "required", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L422-L444
test
uber/tchannel-go
peer.go
canRemove
func (p *Peer) canRemove() bool { p.RLock() count := len(p.inboundConnections) + len(p.outboundConnections) + int(p.scCount) p.RUnlock() return count == 0 }
go
func (p *Peer) canRemove() bool { p.RLock() count := len(p.inboundConnections) + len(p.outboundConnections) + int(p.scCount) p.RUnlock() return count == 0 }
[ "func", "(", "p", "*", "Peer", ")", "canRemove", "(", ")", "bool", "{", "p", ".", "RLock", "(", ")", "\n", "count", ":=", "len", "(", "p", ".", "inboundConnections", ")", "+", "len", "(", "p", ".", "outboundConnections", ")", "+", "int", "(", "p", ".", "scCount", ")", "\n", "p", ".", "RUnlock", "(", ")", "\n", "return", "count", "==", "0", "\n", "}" ]
// canRemove returns whether this peer can be safely removed from the root peer list.
[ "canRemove", "returns", "whether", "this", "peer", "can", "be", "safely", "removed", "from", "the", "root", "peer", "list", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L461-L466
test
uber/tchannel-go
peer.go
addConnection
func (p *Peer) addConnection(c *Connection, direction connectionDirection) error { conns := p.connectionsFor(direction) if c.readState() != connectionActive { return ErrInvalidConnectionState } p.Lock() *conns = append(*conns, c) p.Unlock() // Inform third parties that a peer gained a connection. p.onStatusChanged(p) return nil }
go
func (p *Peer) addConnection(c *Connection, direction connectionDirection) error { conns := p.connectionsFor(direction) if c.readState() != connectionActive { return ErrInvalidConnectionState } p.Lock() *conns = append(*conns, c) p.Unlock() // Inform third parties that a peer gained a connection. p.onStatusChanged(p) return nil }
[ "func", "(", "p", "*", "Peer", ")", "addConnection", "(", "c", "*", "Connection", ",", "direction", "connectionDirection", ")", "error", "{", "conns", ":=", "p", ".", "connectionsFor", "(", "direction", ")", "\n", "if", "c", ".", "readState", "(", ")", "!=", "connectionActive", "{", "return", "ErrInvalidConnectionState", "\n", "}", "\n", "p", ".", "Lock", "(", ")", "\n", "*", "conns", "=", "append", "(", "*", "conns", ",", "c", ")", "\n", "p", ".", "Unlock", "(", ")", "\n", "p", ".", "onStatusChanged", "(", "p", ")", "\n", "return", "nil", "\n", "}" ]
// addConnection adds an active connection to the peer's connection list. // If a connection is not active, returns ErrInvalidConnectionState.
[ "addConnection", "adds", "an", "active", "connection", "to", "the", "peer", "s", "connection", "list", ".", "If", "a", "connection", "is", "not", "active", "returns", "ErrInvalidConnectionState", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L470-L485
test
uber/tchannel-go
peer.go
removeConnection
func (p *Peer) removeConnection(connsPtr *[]*Connection, changed *Connection) bool { conns := *connsPtr for i, c := range conns { if c == changed { // Remove the connection by moving the last item forward, and slicing the list. last := len(conns) - 1 conns[i], conns[last] = conns[last], nil *connsPtr = conns[:last] return true } } return false }
go
func (p *Peer) removeConnection(connsPtr *[]*Connection, changed *Connection) bool { conns := *connsPtr for i, c := range conns { if c == changed { // Remove the connection by moving the last item forward, and slicing the list. last := len(conns) - 1 conns[i], conns[last] = conns[last], nil *connsPtr = conns[:last] return true } } return false }
[ "func", "(", "p", "*", "Peer", ")", "removeConnection", "(", "connsPtr", "*", "[", "]", "*", "Connection", ",", "changed", "*", "Connection", ")", "bool", "{", "conns", ":=", "*", "connsPtr", "\n", "for", "i", ",", "c", ":=", "range", "conns", "{", "if", "c", "==", "changed", "{", "last", ":=", "len", "(", "conns", ")", "-", "1", "\n", "conns", "[", "i", "]", ",", "conns", "[", "last", "]", "=", "conns", "[", "last", "]", ",", "nil", "\n", "*", "connsPtr", "=", "conns", "[", ":", "last", "]", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// removeConnection will check remove the connection if it exists on connsPtr // and returns whether it removed the connection.
[ "removeConnection", "will", "check", "remove", "the", "connection", "if", "it", "exists", "on", "connsPtr", "and", "returns", "whether", "it", "removed", "the", "connection", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L496-L509
test
uber/tchannel-go
peer.go
connectionCloseStateChange
func (p *Peer) connectionCloseStateChange(changed *Connection) { if changed.IsActive() { return } p.Lock() found := p.removeConnection(&p.inboundConnections, changed) if !found { found = p.removeConnection(&p.outboundConnections, changed) } p.Unlock() if found { p.onClosedConnRemoved(p) // Inform third parties that a peer lost a connection. p.onStatusChanged(p) } }
go
func (p *Peer) connectionCloseStateChange(changed *Connection) { if changed.IsActive() { return } p.Lock() found := p.removeConnection(&p.inboundConnections, changed) if !found { found = p.removeConnection(&p.outboundConnections, changed) } p.Unlock() if found { p.onClosedConnRemoved(p) // Inform third parties that a peer lost a connection. p.onStatusChanged(p) } }
[ "func", "(", "p", "*", "Peer", ")", "connectionCloseStateChange", "(", "changed", "*", "Connection", ")", "{", "if", "changed", ".", "IsActive", "(", ")", "{", "return", "\n", "}", "\n", "p", ".", "Lock", "(", ")", "\n", "found", ":=", "p", ".", "removeConnection", "(", "&", "p", ".", "inboundConnections", ",", "changed", ")", "\n", "if", "!", "found", "{", "found", "=", "p", ".", "removeConnection", "(", "&", "p", ".", "outboundConnections", ",", "changed", ")", "\n", "}", "\n", "p", ".", "Unlock", "(", ")", "\n", "if", "found", "{", "p", ".", "onClosedConnRemoved", "(", "p", ")", "\n", "p", ".", "onStatusChanged", "(", "p", ")", "\n", "}", "\n", "}" ]
// connectionStateChanged is called when one of the peers' connections states changes. // All non-active connections are removed from the peer. The connection will // still be tracked by the channel until it's completely closed.
[ "connectionStateChanged", "is", "called", "when", "one", "of", "the", "peers", "connections", "states", "changes", ".", "All", "non", "-", "active", "connections", "are", "removed", "from", "the", "peer", ".", "The", "connection", "will", "still", "be", "tracked", "by", "the", "channel", "until", "it", "s", "completely", "closed", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L514-L531
test
uber/tchannel-go
peer.go
Connect
func (p *Peer) Connect(ctx context.Context) (*Connection, error) { return p.channel.Connect(ctx, p.hostPort) }
go
func (p *Peer) Connect(ctx context.Context) (*Connection, error) { return p.channel.Connect(ctx, p.hostPort) }
[ "func", "(", "p", "*", "Peer", ")", "Connect", "(", "ctx", "context", ".", "Context", ")", "(", "*", "Connection", ",", "error", ")", "{", "return", "p", ".", "channel", ".", "Connect", "(", "ctx", ",", "p", ".", "hostPort", ")", "\n", "}" ]
// Connect adds a new outbound connection to the peer.
[ "Connect", "adds", "a", "new", "outbound", "connection", "to", "the", "peer", "." ]
3c9ced6d946fe2fec6c915703a533e966c09e07a
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L534-L536
test