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
Shopify/toxiproxy
proxy.go
stop
func stop(proxy *Proxy) { if !proxy.Enabled { return } proxy.Enabled = false proxy.tomb.Killf("Shutting down from stop()") proxy.tomb.Wait() // Wait until we stop accepting new connections proxy.connections.Lock() defer proxy.connections.Unlock() for _, conn := range proxy.connections.list { conn.Close() } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Terminated proxy") }
go
func stop(proxy *Proxy) { if !proxy.Enabled { return } proxy.Enabled = false proxy.tomb.Killf("Shutting down from stop()") proxy.tomb.Wait() // Wait until we stop accepting new connections proxy.connections.Lock() defer proxy.connections.Unlock() for _, conn := range proxy.connections.list { conn.Close() } logrus.WithFields(logrus.Fields{ "name": proxy.Name, "proxy": proxy.Listen, "upstream": proxy.Upstream, }).Info("Terminated proxy") }
[ "func", "stop", "(", "proxy", "*", "Proxy", ")", "{", "if", "!", "proxy", ".", "Enabled", "{", "return", "\n", "}", "\n", "proxy", ".", "Enabled", "=", "false", "\n", "proxy", ".", "tomb", ".", "Killf", "(", "\"Shutting down from stop()\"", ")", "\n", "proxy", ".", "tomb", ".", "Wait", "(", ")", "\n", "proxy", ".", "connections", ".", "Lock", "(", ")", "\n", "defer", "proxy", ".", "connections", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "conn", ":=", "range", "proxy", ".", "connections", ".", "list", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"name\"", ":", "proxy", ".", "Name", ",", "\"proxy\"", ":", "proxy", ".", "Listen", ",", "\"upstream\"", ":", "proxy", ".", "Upstream", ",", "}", ")", ".", "Info", "(", "\"Terminated proxy\"", ")", "\n", "}" ]
// Stops a proxy, assumes the lock has already been taken
[ "Stops", "a", "proxy", "assumes", "the", "lock", "has", "already", "been", "taken" ]
07d7b6381cb3b059bdd3d66b1e844ccacc2f660e
https://github.com/Shopify/toxiproxy/blob/07d7b6381cb3b059bdd3d66b1e844ccacc2f660e/proxy.go#L205-L225
train
cweill/gotests
internal/goparser/goparser.go
Parse
func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error) { b, err := p.readFile(srcPath) if err != nil { return nil, err } fset := token.NewFileSet() f, err := p.parseFile(fset, srcPath) if err != nil { return nil, err } fs, err := p.parseFiles(fset, f, files) if err != nil { return nil, err } return &Result{ Header: &models.Header{ Comments: parsePkgComment(f, f.Package), Package: f.Name.String(), Imports: parseImports(f.Imports), Code: goCode(b, f), }, Funcs: p.parseFunctions(fset, f, fs), }, nil }
go
func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error) { b, err := p.readFile(srcPath) if err != nil { return nil, err } fset := token.NewFileSet() f, err := p.parseFile(fset, srcPath) if err != nil { return nil, err } fs, err := p.parseFiles(fset, f, files) if err != nil { return nil, err } return &Result{ Header: &models.Header{ Comments: parsePkgComment(f, f.Package), Package: f.Name.String(), Imports: parseImports(f.Imports), Code: goCode(b, f), }, Funcs: p.parseFunctions(fset, f, fs), }, nil }
[ "func", "(", "p", "*", "Parser", ")", "Parse", "(", "srcPath", "string", ",", "files", "[", "]", "models", ".", "Path", ")", "(", "*", "Result", ",", "error", ")", "{", "b", ",", "err", ":=", "p", ".", "readFile", "(", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "f", ",", "err", ":=", "p", ".", "parseFile", "(", "fset", ",", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fs", ",", "err", ":=", "p", ".", "parseFiles", "(", "fset", ",", "f", ",", "files", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Result", "{", "Header", ":", "&", "models", ".", "Header", "{", "Comments", ":", "parsePkgComment", "(", "f", ",", "f", ".", "Package", ")", ",", "Package", ":", "f", ".", "Name", ".", "String", "(", ")", ",", "Imports", ":", "parseImports", "(", "f", ".", "Imports", ")", ",", "Code", ":", "goCode", "(", "b", ",", "f", ")", ",", "}", ",", "Funcs", ":", "p", ".", "parseFunctions", "(", "fset", ",", "f", ",", "fs", ")", ",", "}", ",", "nil", "\n", "}" ]
// Parse parses a given Go file at srcPath, along any files that share the same // package, into a domain model for generating tests.
[ "Parse", "parses", "a", "given", "Go", "file", "at", "srcPath", "along", "any", "files", "that", "share", "the", "same", "package", "into", "a", "domain", "model", "for", "generating", "tests", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L38-L61
train
cweill/gotests
internal/goparser/goparser.go
goCode
func goCode(b []byte, f *ast.File) []byte { furthestPos := f.Name.End() for _, node := range f.Imports { if pos := node.End(); pos > furthestPos { furthestPos = pos } } if furthestPos < token.Pos(len(b)) { furthestPos++ // Avoid wrong output on windows-encoded files if b[furthestPos-2] == '\r' && b[furthestPos-1] == '\n' && furthestPos < token.Pos(len(b)) { furthestPos++ } } return b[furthestPos:] }
go
func goCode(b []byte, f *ast.File) []byte { furthestPos := f.Name.End() for _, node := range f.Imports { if pos := node.End(); pos > furthestPos { furthestPos = pos } } if furthestPos < token.Pos(len(b)) { furthestPos++ // Avoid wrong output on windows-encoded files if b[furthestPos-2] == '\r' && b[furthestPos-1] == '\n' && furthestPos < token.Pos(len(b)) { furthestPos++ } } return b[furthestPos:] }
[ "func", "goCode", "(", "b", "[", "]", "byte", ",", "f", "*", "ast", ".", "File", ")", "[", "]", "byte", "{", "furthestPos", ":=", "f", ".", "Name", ".", "End", "(", ")", "\n", "for", "_", ",", "node", ":=", "range", "f", ".", "Imports", "{", "if", "pos", ":=", "node", ".", "End", "(", ")", ";", "pos", ">", "furthestPos", "{", "furthestPos", "=", "pos", "\n", "}", "\n", "}", "\n", "if", "furthestPos", "<", "token", ".", "Pos", "(", "len", "(", "b", ")", ")", "{", "furthestPos", "++", "\n", "if", "b", "[", "furthestPos", "-", "2", "]", "==", "'\\r'", "&&", "b", "[", "furthestPos", "-", "1", "]", "==", "'\\n'", "&&", "furthestPos", "<", "token", ".", "Pos", "(", "len", "(", "b", ")", ")", "{", "furthestPos", "++", "\n", "}", "\n", "}", "\n", "return", "b", "[", "furthestPos", ":", "]", "\n", "}" ]
// Returns the Go code below the imports block.
[ "Returns", "the", "Go", "code", "below", "the", "imports", "block", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/goparser/goparser.go#L163-L179
train
cweill/gotests
internal/input/input.go
Files
func Files(srcPath string) ([]models.Path, error) { srcPath, err := filepath.Abs(srcPath) if err != nil { return nil, fmt.Errorf("filepath.Abs: %v\n", err) } var fi os.FileInfo if fi, err = os.Stat(srcPath); err != nil { return nil, fmt.Errorf("os.Stat: %v\n", err) } if fi.IsDir() { return dirFiles(srcPath) } return file(srcPath) }
go
func Files(srcPath string) ([]models.Path, error) { srcPath, err := filepath.Abs(srcPath) if err != nil { return nil, fmt.Errorf("filepath.Abs: %v\n", err) } var fi os.FileInfo if fi, err = os.Stat(srcPath); err != nil { return nil, fmt.Errorf("os.Stat: %v\n", err) } if fi.IsDir() { return dirFiles(srcPath) } return file(srcPath) }
[ "func", "Files", "(", "srcPath", "string", ")", "(", "[", "]", "models", ".", "Path", ",", "error", ")", "{", "srcPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"filepath.Abs: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "err", "\n", "var", "fi", "os", ".", "FileInfo", "\n", "if", "fi", ",", "err", "=", "os", ".", "Stat", "(", "srcPath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"os.Stat: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "err", "\n", "}" ]
// Files returns all the Golang files for the given path. Ignores hidden files.
[ "Files", "returns", "all", "the", "Golang", "files", "for", "the", "given", "path", ".", "Ignores", "hidden", "files", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/input/input.go#L13-L26
train
cweill/gotests
internal/render/render.go
LoadCustomTemplates
func LoadCustomTemplates(dir string) error { initEmptyTmpls() files, err := ioutil.ReadDir(dir) if err != nil { return fmt.Errorf("ioutil.ReadDir: %v", err) } templateFiles := []string{} for _, f := range files { templateFiles = append(templateFiles, path.Join(dir, f.Name())) } tmpls, err = tmpls.ParseFiles(templateFiles...) if err != nil { return fmt.Errorf("tmpls.ParseFiles: %v", err) } return nil }
go
func LoadCustomTemplates(dir string) error { initEmptyTmpls() files, err := ioutil.ReadDir(dir) if err != nil { return fmt.Errorf("ioutil.ReadDir: %v", err) } templateFiles := []string{} for _, f := range files { templateFiles = append(templateFiles, path.Join(dir, f.Name())) } tmpls, err = tmpls.ParseFiles(templateFiles...) if err != nil { return fmt.Errorf("tmpls.ParseFiles: %v", err) } return nil }
[ "func", "LoadCustomTemplates", "(", "dir", "string", ")", "error", "{", "initEmptyTmpls", "(", ")", "\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"ioutil.ReadDir: %v\"", ",", "err", ")", "\n", "}", "\n", "templateFiles", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "templateFiles", "=", "append", "(", "templateFiles", ",", "path", ".", "Join", "(", "dir", ",", "f", ".", "Name", "(", ")", ")", ")", "\n", "}", "\n", "tmpls", ",", "err", "=", "tmpls", ".", "ParseFiles", "(", "templateFiles", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"tmpls.ParseFiles: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LoadCustomTemplates allows to load in custom templates from a specified path.
[ "LoadCustomTemplates", "allows", "to", "load", "in", "custom", "templates", "from", "a", "specified", "path", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/render.go#L30-L47
train
cweill/gotests
internal/render/bindata/esc.go
FSByte
func FSByte(useLocal bool, name string) ([]byte, error) { if useLocal { f, err := _escLocal.Open(name) if err != nil { return nil, err } b, err := ioutil.ReadAll(f) _ = f.Close() return b, err } f, err := _escStatic.prepare(name) if err != nil { return nil, err } return f.data, nil }
go
func FSByte(useLocal bool, name string) ([]byte, error) { if useLocal { f, err := _escLocal.Open(name) if err != nil { return nil, err } b, err := ioutil.ReadAll(f) _ = f.Close() return b, err } f, err := _escStatic.prepare(name) if err != nil { return nil, err } return f.data, nil }
[ "func", "FSByte", "(", "useLocal", "bool", ",", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "useLocal", "{", "f", ",", "err", ":=", "_escLocal", ".", "Open", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "_", "=", "f", ".", "Close", "(", ")", "\n", "return", "b", ",", "err", "\n", "}", "\n", "f", ",", "err", ":=", "_escStatic", ".", "prepare", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "f", ".", "data", ",", "nil", "\n", "}" ]
// FSByte returns the named file from the embedded assets. If useLocal is // true, the filesystem's contents are instead used.
[ "FSByte", "returns", "the", "named", "file", "from", "the", "embedded", "assets", ".", "If", "useLocal", "is", "true", "the", "filesystem", "s", "contents", "are", "instead", "used", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L173-L188
train
cweill/gotests
internal/render/bindata/esc.go
FSMustByte
func FSMustByte(useLocal bool, name string) []byte { b, err := FSByte(useLocal, name) if err != nil { panic(err) } return b }
go
func FSMustByte(useLocal bool, name string) []byte { b, err := FSByte(useLocal, name) if err != nil { panic(err) } return b }
[ "func", "FSMustByte", "(", "useLocal", "bool", ",", "name", "string", ")", "[", "]", "byte", "{", "b", ",", "err", ":=", "FSByte", "(", "useLocal", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// FSMustByte is the same as FSByte, but panics if name is not present.
[ "FSMustByte", "is", "the", "same", "as", "FSByte", "but", "panics", "if", "name", "is", "not", "present", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L191-L197
train
cweill/gotests
internal/render/bindata/esc.go
FSString
func FSString(useLocal bool, name string) (string, error) { b, err := FSByte(useLocal, name) return string(b), err }
go
func FSString(useLocal bool, name string) (string, error) { b, err := FSByte(useLocal, name) return string(b), err }
[ "func", "FSString", "(", "useLocal", "bool", ",", "name", "string", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "FSByte", "(", "useLocal", ",", "name", ")", "\n", "return", "string", "(", "b", ")", ",", "err", "\n", "}" ]
// FSString is the string version of FSByte.
[ "FSString", "is", "the", "string", "version", "of", "FSByte", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L200-L203
train
cweill/gotests
internal/render/bindata/esc.go
FSMustString
func FSMustString(useLocal bool, name string) string { return string(FSMustByte(useLocal, name)) }
go
func FSMustString(useLocal bool, name string) string { return string(FSMustByte(useLocal, name)) }
[ "func", "FSMustString", "(", "useLocal", "bool", ",", "name", "string", ")", "string", "{", "return", "string", "(", "FSMustByte", "(", "useLocal", ",", "name", ")", ")", "\n", "}" ]
// FSMustString is the string version of FSMustByte.
[ "FSMustString", "is", "the", "string", "version", "of", "FSMustByte", "." ]
afa0a378663a63a98287714c3f3359e22a4ab29e
https://github.com/cweill/gotests/blob/afa0a378663a63a98287714c3f3359e22a4ab29e/internal/render/bindata/esc.go#L206-L208
train
dropbox/godropbox
database/binlog/parsed_event_reader.go
NewParsedV4EventReader
func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader { return &parsedV4EventReader{ reader: reader, eventParsers: parsers, } }
go
func NewParsedV4EventReader( reader EventReader, parsers V4EventParserMap) EventReader { return &parsedV4EventReader{ reader: reader, eventParsers: parsers, } }
[ "func", "NewParsedV4EventReader", "(", "reader", "EventReader", ",", "parsers", "V4EventParserMap", ")", "EventReader", "{", "return", "&", "parsedV4EventReader", "{", "reader", ":", "reader", ",", "eventParsers", ":", "parsers", ",", "}", "\n", "}" ]
// This returns an EventReader which applies the appropriate parser on each // raw v4 event in the stream. If no parser is available for the event, // or if an error occurs during parsing, then the reader will return the // original event along with the error.
[ "This", "returns", "an", "EventReader", "which", "applies", "the", "appropriate", "parser", "on", "each", "raw", "v4", "event", "in", "the", "stream", ".", "If", "no", "parser", "is", "available", "for", "the", "event", "or", "if", "an", "error", "occurs", "during", "parsing", "then", "the", "reader", "will", "return", "the", "original", "event", "along", "with", "the", "error", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/parsed_event_reader.go#L16-L24
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
NewWriterToReaderAdapter
func NewWriterToReaderAdapter(toBeAdapted func(io.Reader) (io.Reader, error), output io.Writer, shouldCloseDownstream bool) io.WriteCloser { retval := privateReaderAdapter{ Writer: WriterToReaderAdapter{ workChan: make(chan *[]byte), doneWorkChan: make(chan *[]byte), errChan: make(chan error, 3), closed: false, }} go copyDataToOutput(toBeAdapted, &retval, output, shouldCloseDownstream) return &retval.Writer }
go
func NewWriterToReaderAdapter(toBeAdapted func(io.Reader) (io.Reader, error), output io.Writer, shouldCloseDownstream bool) io.WriteCloser { retval := privateReaderAdapter{ Writer: WriterToReaderAdapter{ workChan: make(chan *[]byte), doneWorkChan: make(chan *[]byte), errChan: make(chan error, 3), closed: false, }} go copyDataToOutput(toBeAdapted, &retval, output, shouldCloseDownstream) return &retval.Writer }
[ "func", "NewWriterToReaderAdapter", "(", "toBeAdapted", "func", "(", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", ",", "output", "io", ".", "Writer", ",", "shouldCloseDownstream", "bool", ")", "io", ".", "WriteCloser", "{", "retval", ":=", "privateReaderAdapter", "{", "Writer", ":", "WriterToReaderAdapter", "{", "workChan", ":", "make", "(", "chan", "*", "[", "]", "byte", ")", ",", "doneWorkChan", ":", "make", "(", "chan", "*", "[", "]", "byte", ")", ",", "errChan", ":", "make", "(", "chan", "error", ",", "3", ")", ",", "closed", ":", "false", ",", "}", "}", "\n", "go", "copyDataToOutput", "(", "toBeAdapted", ",", "&", "retval", ",", "output", ",", "shouldCloseDownstream", ")", "\n", "return", "&", "retval", ".", "Writer", "\n", "}" ]
// This makes a io.Writer from a io.Reader and begins reading and writing data // The returned class is not thread safe and public methods must be called from a single thread
[ "This", "makes", "a", "io", ".", "Writer", "from", "a", "io", ".", "Reader", "and", "begins", "reading", "and", "writing", "data", "The", "returned", "class", "is", "not", "thread", "safe", "and", "public", "methods", "must", "be", "called", "from", "a", "single", "thread" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L29-L41
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
Read
func (rself *privateReaderAdapter) Read(data []byte) (int, error) { lenToCopy := len(rself.bufferToBeRead) if lenToCopy == 0 { rself.workReceipt = <-rself.Writer.workChan if rself.workReceipt == nil { // no more data to consume rself.closeReceived = true return 0, io.EOF } rself.bufferToBeRead = *rself.workReceipt lenToCopy = len(rself.bufferToBeRead) } if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rself.bufferToBeRead[:lenToCopy]) rself.bufferToBeRead = rself.bufferToBeRead[lenToCopy:] if len(rself.bufferToBeRead) == 0 { rself.Writer.doneWorkChan <- rself.workReceipt rself.workReceipt = nil } return lenToCopy, nil }
go
func (rself *privateReaderAdapter) Read(data []byte) (int, error) { lenToCopy := len(rself.bufferToBeRead) if lenToCopy == 0 { rself.workReceipt = <-rself.Writer.workChan if rself.workReceipt == nil { // no more data to consume rself.closeReceived = true return 0, io.EOF } rself.bufferToBeRead = *rself.workReceipt lenToCopy = len(rself.bufferToBeRead) } if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rself.bufferToBeRead[:lenToCopy]) rself.bufferToBeRead = rself.bufferToBeRead[lenToCopy:] if len(rself.bufferToBeRead) == 0 { rself.Writer.doneWorkChan <- rself.workReceipt rself.workReceipt = nil } return lenToCopy, nil }
[ "func", "(", "rself", "*", "privateReaderAdapter", ")", "Read", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "lenToCopy", ":=", "len", "(", "rself", ".", "bufferToBeRead", ")", "\n", "if", "lenToCopy", "==", "0", "{", "rself", ".", "workReceipt", "=", "<-", "rself", ".", "Writer", ".", "workChan", "\n", "if", "rself", ".", "workReceipt", "==", "nil", "{", "rself", ".", "closeReceived", "=", "true", "\n", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "rself", ".", "bufferToBeRead", "=", "*", "rself", ".", "workReceipt", "\n", "lenToCopy", "=", "len", "(", "rself", ".", "bufferToBeRead", ")", "\n", "}", "\n", "if", "lenToCopy", ">", "len", "(", "data", ")", "{", "lenToCopy", "=", "len", "(", "data", ")", "\n", "}", "\n", "copy", "(", "data", "[", ":", "lenToCopy", "]", ",", "rself", ".", "bufferToBeRead", "[", ":", "lenToCopy", "]", ")", "\n", "rself", ".", "bufferToBeRead", "=", "rself", ".", "bufferToBeRead", "[", "lenToCopy", ":", "]", "\n", "if", "len", "(", "rself", ".", "bufferToBeRead", ")", "==", "0", "{", "rself", ".", "Writer", ".", "doneWorkChan", "<-", "rself", ".", "workReceipt", "\n", "rself", ".", "workReceipt", "=", "nil", "\n", "}", "\n", "return", "lenToCopy", ",", "nil", "\n", "}" ]
// this is the private Read implementation, to be used with io.Copy // on the read thread
[ "this", "is", "the", "private", "Read", "implementation", "to", "be", "used", "with", "io", ".", "Copy", "on", "the", "read", "thread" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L45-L67
train
dropbox/godropbox
io2/writer_to_reader_adapter.go
copyDataToOutput
func copyDataToOutput(inputFactory func(io.Reader) (io.Reader, error), adaptedInput *privateReaderAdapter, output io.Writer, shouldCloseDownstream bool) { input, err := inputFactory(adaptedInput) if err != nil { adaptedInput.Writer.errChan <- err } else { _, err = io.Copy(output, input) if err != nil { adaptedInput.Writer.errChan <- err } } writeCloser, ok := output.(io.WriteCloser) if ok && shouldCloseDownstream { closeErr := writeCloser.Close() if closeErr != nil { adaptedInput.Writer.errChan <- closeErr } } // pulls all the data from the writer until EOF is reached // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath adaptedInput.drain() close(adaptedInput.Writer.errChan) }
go
func copyDataToOutput(inputFactory func(io.Reader) (io.Reader, error), adaptedInput *privateReaderAdapter, output io.Writer, shouldCloseDownstream bool) { input, err := inputFactory(adaptedInput) if err != nil { adaptedInput.Writer.errChan <- err } else { _, err = io.Copy(output, input) if err != nil { adaptedInput.Writer.errChan <- err } } writeCloser, ok := output.(io.WriteCloser) if ok && shouldCloseDownstream { closeErr := writeCloser.Close() if closeErr != nil { adaptedInput.Writer.errChan <- closeErr } } // pulls all the data from the writer until EOF is reached // this is because readers like zlib don't validate the CRC32 // (the last 4 bytes) in the normal codepath adaptedInput.drain() close(adaptedInput.Writer.errChan) }
[ "func", "copyDataToOutput", "(", "inputFactory", "func", "(", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", ",", "adaptedInput", "*", "privateReaderAdapter", ",", "output", "io", ".", "Writer", ",", "shouldCloseDownstream", "bool", ")", "{", "input", ",", "err", ":=", "inputFactory", "(", "adaptedInput", ")", "\n", "if", "err", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "err", "\n", "}", "else", "{", "_", ",", "err", "=", "io", ".", "Copy", "(", "output", ",", "input", ")", "\n", "if", "err", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "err", "\n", "}", "\n", "}", "\n", "writeCloser", ",", "ok", ":=", "output", ".", "(", "io", ".", "WriteCloser", ")", "\n", "if", "ok", "&&", "shouldCloseDownstream", "{", "closeErr", ":=", "writeCloser", ".", "Close", "(", ")", "\n", "if", "closeErr", "!=", "nil", "{", "adaptedInput", ".", "Writer", ".", "errChan", "<-", "closeErr", "\n", "}", "\n", "}", "\n", "adaptedInput", ".", "drain", "(", ")", "\n", "close", "(", "adaptedInput", ".", "Writer", ".", "errChan", ")", "\n", "}" ]
// This io.Copy's as much data as possible from the wrapped reader // to the corresponding writer output. // When finished it closes the downstream and drains the upstream // writer. Finally it sends any remaining errors to the errChan and // closes that channel
[ "This", "io", ".", "Copy", "s", "as", "much", "data", "as", "possible", "from", "the", "wrapped", "reader", "to", "the", "corresponding", "writer", "output", ".", "When", "finished", "it", "closes", "the", "downstream", "and", "drains", "the", "upstream", "writer", ".", "Finally", "it", "sends", "any", "remaining", "errors", "to", "the", "errChan", "and", "closes", "that", "channel" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/writer_to_reader_adapter.go#L158-L187
train
dropbox/godropbox
caching/generic_storage.go
NewGenericStorage
func NewGenericStorage(name string, options GenericStorageOptions) Storage { return &GenericStorage{ name: name, get: options.GetFunc, getMulti: options.GetMultiFunc, set: options.SetFunc, setMulti: options.SetMultiFunc, del: options.DelFunc, delMulti: options.DelMultiFunc, errorOnFlush: options.ErrorOnFlush, flush: options.FlushFunc, } }
go
func NewGenericStorage(name string, options GenericStorageOptions) Storage { return &GenericStorage{ name: name, get: options.GetFunc, getMulti: options.GetMultiFunc, set: options.SetFunc, setMulti: options.SetMultiFunc, del: options.DelFunc, delMulti: options.DelMultiFunc, errorOnFlush: options.ErrorOnFlush, flush: options.FlushFunc, } }
[ "func", "NewGenericStorage", "(", "name", "string", ",", "options", "GenericStorageOptions", ")", "Storage", "{", "return", "&", "GenericStorage", "{", "name", ":", "name", ",", "get", ":", "options", ".", "GetFunc", ",", "getMulti", ":", "options", ".", "GetMultiFunc", ",", "set", ":", "options", ".", "SetFunc", ",", "setMulti", ":", "options", ".", "SetMultiFunc", ",", "del", ":", "options", ".", "DelFunc", ",", "delMulti", ":", "options", ".", "DelMultiFunc", ",", "errorOnFlush", ":", "options", ".", "ErrorOnFlush", ",", "flush", ":", "options", ".", "FlushFunc", ",", "}", "\n", "}" ]
// This creates a GenericStorage. See GenericStorageOptions for additional // information.
[ "This", "creates", "a", "GenericStorage", ".", "See", "GenericStorageOptions", "for", "additional", "information", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/caching/generic_storage.go#L59-L71
train
dropbox/godropbox
container/set/set.go
Union
func Union(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.Copy() } s3 := s1.Copy() s3.Union(s2) return s3 }
go
func Union(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.Copy() } s3 := s1.Copy() s3.Union(s2) return s3 }
[ "func", "Union", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s2", ".", "Copy", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Union", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the union of s1 and s2. s1 and s2 are unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "union", "of", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L50-L61
train
dropbox/godropbox
container/set/set.go
Intersect
func Intersect(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Intersect(s2) return s3 }
go
func Intersect(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Intersect(s2) return s3 }
[ "func", "Intersect", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s2", ".", "New", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Intersect", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the intersect of s1 and s2. s1 and s2 are // unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "intersect", "of", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L65-L76
train
dropbox/godropbox
container/set/set.go
Subtract
func Subtract(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Subtract(s2) return s3 }
go
func Subtract(s1 Set, s2 Set) Set { if s1 == nil { if s2 == nil { return nil } return s2.New() } s3 := s1.Copy() s3.Subtract(s2) return s3 }
[ "func", "Subtract", "(", "s1", "Set", ",", "s2", "Set", ")", "Set", "{", "if", "s1", "==", "nil", "{", "if", "s2", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s2", ".", "New", "(", ")", "\n", "}", "\n", "s3", ":=", "s1", ".", "Copy", "(", ")", "\n", "s3", ".", "Subtract", "(", "s2", ")", "\n", "return", "s3", "\n", "}" ]
// Returns a new set which is the difference between s1 and s2. s1 and s2 are // unmodified.
[ "Returns", "a", "new", "set", "which", "is", "the", "difference", "between", "s1", "and", "s2", ".", "s1", "and", "s2", "are", "unmodified", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L80-L91
train
dropbox/godropbox
container/set/set.go
equal
func equal(s Set, s2 Set) bool { if s.Len() != s2.Len() { return false } return s.IsSubset(s2) }
go
func equal(s Set, s2 Set) bool { if s.Len() != s2.Len() { return false } return s.IsSubset(s2) }
[ "func", "equal", "(", "s", "Set", ",", "s2", "Set", ")", "bool", "{", "if", "s", ".", "Len", "(", ")", "!=", "s2", ".", "Len", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "s", ".", "IsSubset", "(", "s2", ")", "\n", "}" ]
// Common functions between the two implementations, since go // does not allow for any inheritance.
[ "Common", "functions", "between", "the", "two", "implementations", "since", "go", "does", "not", "allow", "for", "any", "inheritance", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/container/set/set.go#L340-L346
train
dropbox/godropbox
memcache/raw_binary_client.go
NewRawBinaryClient
func NewRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: defaultMaxValueLength, } }
go
func NewRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: defaultMaxValueLength, } }
[ "func", "NewRawBinaryClient", "(", "shard", "int", ",", "channel", "io", ".", "ReadWriter", ")", "ClientShard", "{", "return", "&", "RawBinaryClient", "{", "shard", ":", "shard", ",", "channel", ":", "channel", ",", "validState", ":", "true", ",", "maxValueLength", ":", "defaultMaxValueLength", ",", "}", "\n", "}" ]
// This creates a new memcache RawBinaryClient.
[ "This", "creates", "a", "new", "memcache", "RawBinaryClient", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L103-L110
train
dropbox/godropbox
memcache/raw_binary_client.go
NewLargeRawBinaryClient
func NewLargeRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: largeMaxValueLength, } }
go
func NewLargeRawBinaryClient(shard int, channel io.ReadWriter) ClientShard { return &RawBinaryClient{ shard: shard, channel: channel, validState: true, maxValueLength: largeMaxValueLength, } }
[ "func", "NewLargeRawBinaryClient", "(", "shard", "int", ",", "channel", "io", ".", "ReadWriter", ")", "ClientShard", "{", "return", "&", "RawBinaryClient", "{", "shard", ":", "shard", ",", "channel", ":", "channel", ",", "validState", ":", "true", ",", "maxValueLength", ":", "largeMaxValueLength", ",", "}", "\n", "}" ]
// This creates a new memcache RawBinaryClient for use with np-large cluster.
[ "This", "creates", "a", "new", "memcache", "RawBinaryClient", "for", "use", "with", "np", "-", "large", "cluster", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L113-L120
train
dropbox/godropbox
memcache/raw_binary_client.go
mutate
func (c *RawBinaryClient) mutate(code opCode, item *Item) MutateResponse { if item == nil { return NewMutateErrorResponse("", errors.New("item is nil")) } c.mutex.Lock() defer c.mutex.Unlock() if resp := c.sendMutateRequest(code, item, true); resp != nil { return resp } return c.receiveMutateResponse(code, item.Key) }
go
func (c *RawBinaryClient) mutate(code opCode, item *Item) MutateResponse { if item == nil { return NewMutateErrorResponse("", errors.New("item is nil")) } c.mutex.Lock() defer c.mutex.Unlock() if resp := c.sendMutateRequest(code, item, true); resp != nil { return resp } return c.receiveMutateResponse(code, item.Key) }
[ "func", "(", "c", "*", "RawBinaryClient", ")", "mutate", "(", "code", "opCode", ",", "item", "*", "Item", ")", "MutateResponse", "{", "if", "item", "==", "nil", "{", "return", "NewMutateErrorResponse", "(", "\"\"", ",", "errors", ".", "New", "(", "\"item is nil\"", ")", ")", "\n", "}", "\n", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "resp", ":=", "c", ".", "sendMutateRequest", "(", "code", ",", "item", ",", "true", ")", ";", "resp", "!=", "nil", "{", "return", "resp", "\n", "}", "\n", "return", "c", ".", "receiveMutateResponse", "(", "code", ",", "item", ".", "Key", ")", "\n", "}" ]
// Perform a mutation operation specified by the given code.
[ "Perform", "a", "mutation", "operation", "specified", "by", "the", "given", "code", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_binary_client.go#L443-L456
train
dropbox/godropbox
rate_limiter/rate_limiter.go
MaxQuota
func (l *rateLimiterImpl) MaxQuota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.maxQuota }
go
func (l *rateLimiterImpl) MaxQuota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.maxQuota }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "MaxQuota", "(", ")", "float64", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "maxQuota", "\n", "}" ]
// This returns the leaky bucket's maximum capacity.
[ "This", "returns", "the", "leaky", "bucket", "s", "maximum", "capacity", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L147-L151
train
dropbox/godropbox
rate_limiter/rate_limiter.go
SetMaxQuota
func (l *rateLimiterImpl) SetMaxQuota(q float64) error { if q < 0 { return errors.Newf("Max quota must be non-negative: %f", q) } l.mutex.Lock() defer l.mutex.Unlock() l.maxQuota = q if l.quota > q { l.quota = q } if l.maxQuota == 0 { l.cond.Broadcast() } return nil }
go
func (l *rateLimiterImpl) SetMaxQuota(q float64) error { if q < 0 { return errors.Newf("Max quota must be non-negative: %f", q) } l.mutex.Lock() defer l.mutex.Unlock() l.maxQuota = q if l.quota > q { l.quota = q } if l.maxQuota == 0 { l.cond.Broadcast() } return nil }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "SetMaxQuota", "(", "q", "float64", ")", "error", "{", "if", "q", "<", "0", "{", "return", "errors", ".", "Newf", "(", "\"Max quota must be non-negative: %f\"", ",", "q", ")", "\n", "}", "\n", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "l", ".", "maxQuota", "=", "q", "\n", "if", "l", ".", "quota", ">", "q", "{", "l", ".", "quota", "=", "q", "\n", "}", "\n", "if", "l", ".", "maxQuota", "==", "0", "{", "l", ".", "cond", ".", "Broadcast", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This sets the leaky bucket's maximum capacity. The value must be // non-negative.
[ "This", "sets", "the", "leaky", "bucket", "s", "maximum", "capacity", ".", "The", "value", "must", "be", "non", "-", "negative", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L155-L173
train
dropbox/godropbox
rate_limiter/rate_limiter.go
QuotaPerSec
func (l *rateLimiterImpl) QuotaPerSec() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.quotaPerSec }
go
func (l *rateLimiterImpl) QuotaPerSec() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.quotaPerSec }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "QuotaPerSec", "(", ")", "float64", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "quotaPerSec", "\n", "}" ]
// This returns the leaky bucket's fill rate.
[ "This", "returns", "the", "leaky", "bucket", "s", "fill", "rate", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L176-L181
train
dropbox/godropbox
rate_limiter/rate_limiter.go
SetQuotaPerSec
func (l *rateLimiterImpl) SetQuotaPerSec(r float64) error { if r < 0 { return errors.Newf("Quota per second must be non-negative: %f", r) } l.mutex.Lock() defer l.mutex.Unlock() l.quotaPerSec = r return nil }
go
func (l *rateLimiterImpl) SetQuotaPerSec(r float64) error { if r < 0 { return errors.Newf("Quota per second must be non-negative: %f", r) } l.mutex.Lock() defer l.mutex.Unlock() l.quotaPerSec = r return nil }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "SetQuotaPerSec", "(", "r", "float64", ")", "error", "{", "if", "r", "<", "0", "{", "return", "errors", ".", "Newf", "(", "\"Quota per second must be non-negative: %f\"", ",", "r", ")", "\n", "}", "\n", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "l", ".", "quotaPerSec", "=", "r", "\n", "return", "nil", "\n", "}" ]
// This sets the leaky bucket's fill rate. The value must be non-negative.
[ "This", "sets", "the", "leaky", "bucket", "s", "fill", "rate", ".", "The", "value", "must", "be", "non", "-", "negative", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L184-L195
train
dropbox/godropbox
rate_limiter/rate_limiter.go
Quota
func (l *rateLimiterImpl) Quota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.quota }
go
func (l *rateLimiterImpl) Quota() float64 { l.mutex.Lock() defer l.mutex.Unlock() return l.quota }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "Quota", "(", ")", "float64", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "quota", "\n", "}" ]
// This returns the current available quota.
[ "This", "returns", "the", "current", "available", "quota", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L198-L202
train
dropbox/godropbox
rate_limiter/rate_limiter.go
setQuota
func (l *rateLimiterImpl) setQuota(q float64) { l.mutex.Lock() defer l.mutex.Unlock() l.quota = q }
go
func (l *rateLimiterImpl) setQuota(q float64) { l.mutex.Lock() defer l.mutex.Unlock() l.quota = q }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "setQuota", "(", "q", "float64", ")", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "l", ".", "quota", "=", "q", "\n", "}" ]
// Only used for testing.
[ "Only", "used", "for", "testing", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L205-L209
train
dropbox/godropbox
rate_limiter/rate_limiter.go
Stop
func (l *rateLimiterImpl) Stop() { l.mutex.Lock() defer l.mutex.Unlock() if l.stopped { return } l.stopped = true close(l.stopChan) l.ticker.Stop() l.cond.Broadcast() }
go
func (l *rateLimiterImpl) Stop() { l.mutex.Lock() defer l.mutex.Unlock() if l.stopped { return } l.stopped = true close(l.stopChan) l.ticker.Stop() l.cond.Broadcast() }
[ "func", "(", "l", "*", "rateLimiterImpl", ")", "Stop", "(", ")", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "l", ".", "stopped", "{", "return", "\n", "}", "\n", "l", ".", "stopped", "=", "true", "\n", "close", "(", "l", ".", "stopChan", ")", "\n", "l", ".", "ticker", ".", "Stop", "(", ")", "\n", "l", ".", "cond", ".", "Broadcast", "(", ")", "\n", "}" ]
// Stop the rate limiter.
[ "Stop", "the", "rate", "limiter", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L262-L276
train
dropbox/godropbox
io2/reader_to_writer_adapter.go
Write
func (sbself *splitBufferedWriter) Write(data []byte) (int, error) { toCopy := len(sbself.userBuffer) - sbself.userBufferCount if toCopy > len(data) { toCopy = len(data) } copy(sbself.userBuffer[sbself.userBufferCount:sbself.userBufferCount+toCopy], data[:toCopy]) sbself.userBufferCount += toCopy if toCopy < len(data) { // we need to overflow to remainder count, err := sbself.remainder.Write(data[toCopy:]) return count + toCopy, err } return toCopy, nil }
go
func (sbself *splitBufferedWriter) Write(data []byte) (int, error) { toCopy := len(sbself.userBuffer) - sbself.userBufferCount if toCopy > len(data) { toCopy = len(data) } copy(sbself.userBuffer[sbself.userBufferCount:sbself.userBufferCount+toCopy], data[:toCopy]) sbself.userBufferCount += toCopy if toCopy < len(data) { // we need to overflow to remainder count, err := sbself.remainder.Write(data[toCopy:]) return count + toCopy, err } return toCopy, nil }
[ "func", "(", "sbself", "*", "splitBufferedWriter", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "toCopy", ":=", "len", "(", "sbself", ".", "userBuffer", ")", "-", "sbself", ".", "userBufferCount", "\n", "if", "toCopy", ">", "len", "(", "data", ")", "{", "toCopy", "=", "len", "(", "data", ")", "\n", "}", "\n", "copy", "(", "sbself", ".", "userBuffer", "[", "sbself", ".", "userBufferCount", ":", "sbself", ".", "userBufferCount", "+", "toCopy", "]", ",", "data", "[", ":", "toCopy", "]", ")", "\n", "sbself", ".", "userBufferCount", "+=", "toCopy", "\n", "if", "toCopy", "<", "len", "(", "data", ")", "{", "count", ",", "err", ":=", "sbself", ".", "remainder", ".", "Write", "(", "data", "[", "toCopy", ":", "]", ")", "\n", "return", "count", "+", "toCopy", ",", "err", "\n", "}", "\n", "return", "toCopy", ",", "nil", "\n", "}" ]
// writes, preferably to the userBuffer but then optionally to the remainder
[ "writes", "preferably", "to", "the", "userBuffer", "but", "then", "optionally", "to", "the", "remainder" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L67-L79
train
dropbox/godropbox
io2/reader_to_writer_adapter.go
RemoveUserBuffer
func (sbself *splitBufferedWriter) RemoveUserBuffer() (amountReturned int, err error) { if len(sbself.userBuffer) > sbself.userBufferCount { if len(sbself.remainder.Bytes()) != 0 { err = errors.New("remainder must be clear if userBuffer isn't full") panic(err) } } amountReturned = sbself.userBufferCount sbself.userBuffer = nil sbself.userBufferCount = 0 return }
go
func (sbself *splitBufferedWriter) RemoveUserBuffer() (amountReturned int, err error) { if len(sbself.userBuffer) > sbself.userBufferCount { if len(sbself.remainder.Bytes()) != 0 { err = errors.New("remainder must be clear if userBuffer isn't full") panic(err) } } amountReturned = sbself.userBufferCount sbself.userBuffer = nil sbself.userBufferCount = 0 return }
[ "func", "(", "sbself", "*", "splitBufferedWriter", ")", "RemoveUserBuffer", "(", ")", "(", "amountReturned", "int", ",", "err", "error", ")", "{", "if", "len", "(", "sbself", ".", "userBuffer", ")", ">", "sbself", ".", "userBufferCount", "{", "if", "len", "(", "sbself", ".", "remainder", ".", "Bytes", "(", ")", ")", "!=", "0", "{", "err", "=", "errors", ".", "New", "(", "\"remainder must be clear if userBuffer isn't full\"", ")", "\n", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "amountReturned", "=", "sbself", ".", "userBufferCount", "\n", "sbself", ".", "userBuffer", "=", "nil", "\n", "sbself", ".", "userBufferCount", "=", "0", "\n", "return", "\n", "}" ]
// removes the user buffer from the splitBufferedWriter // This makes sure that if the user buffer is only somewhat full, no data remains in the remainder // This preserves the remainder buffer, since that will be consumed later
[ "removes", "the", "user", "buffer", "from", "the", "splitBufferedWriter", "This", "makes", "sure", "that", "if", "the", "user", "buffer", "is", "only", "somewhat", "full", "no", "data", "remains", "in", "the", "remainder", "This", "preserves", "the", "remainder", "buffer", "since", "that", "will", "be", "consumed", "later" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L88-L100
train
dropbox/godropbox
io2/reader_to_writer_adapter.go
InstallNewUserBufferAndResetRemainder
func (sbself *splitBufferedWriter) InstallNewUserBufferAndResetRemainder( data []byte) { sbself.remainder.Reset() sbself.userBuffer = data sbself.userBufferCount = 0 }
go
func (sbself *splitBufferedWriter) InstallNewUserBufferAndResetRemainder( data []byte) { sbself.remainder.Reset() sbself.userBuffer = data sbself.userBufferCount = 0 }
[ "func", "(", "sbself", "*", "splitBufferedWriter", ")", "InstallNewUserBufferAndResetRemainder", "(", "data", "[", "]", "byte", ")", "{", "sbself", ".", "remainder", ".", "Reset", "(", ")", "\n", "sbself", ".", "userBuffer", "=", "data", "\n", "sbself", ".", "userBufferCount", "=", "0", "\n", "}" ]
// installs a user buffer into the splitBufferedWriter, resetting // the remainder and original buffer
[ "installs", "a", "user", "buffer", "into", "the", "splitBufferedWriter", "resetting", "the", "remainder", "and", "original", "buffer" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L104-L110
train
dropbox/godropbox
io2/reader_to_writer_adapter.go
Read
func (rwaself *ReaderToWriterAdapter) Read(data []byte) (int, error) { lenToCopy := len(rwaself.writeBuffer.Bytes()) - rwaself.offset if lenToCopy > 0 { // if we have leftover data from a previous call, we can return that only if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rwaself.writeBuffer.Bytes()[rwaself.offset:rwaself.offset+lenToCopy]) rwaself.offset += lenToCopy // only return deferred errors if we have consumed the entire remainder if rwaself.offset < len(rwaself.writeBuffer.Bytes()) { return lenToCopy, nil // if still remainder left, return nil } else { err := rwaself.deferredErr rwaself.deferredErr = nil return lenToCopy, err } } rwaself.offset = 0 // if we have no data from previous runs, lets install the buffer and copy to the writer rwaself.writeBuffer.InstallNewUserBufferAndResetRemainder(data) for { // read from the upstream readBufferLenValid, err := rwaself.upstream.Read(rwaself.readBuffer) var writeErr error var closeErr error if readBufferLenValid > 0 { // copy data to the writer _, writeErr = rwaself.writer.Write(rwaself.readBuffer[:readBufferLenValid]) } if err == io.EOF && !rwaself.closedWriter { rwaself.closedWriter = true if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok { closeErr = writeCloser.Close() } } if err == nil && (writeErr != nil || closeErr != nil) { _ = rwaself.drain() // if there was an error with the writer, drain the upstream } if (err == nil || err == io.EOF) && writeErr != nil { err = writeErr } if (err == nil || err == io.EOF) && closeErr != nil { err = closeErr } if rwaself.writeBuffer.GetAmountCopiedToUser() > 0 || err != nil { if rwaself.offset < len(rwaself.writeBuffer.Bytes()) { rwaself.deferredErr = err err = nil } amountCopiedToUser, err2 := rwaself.writeBuffer.RemoveUserBuffer() if err == nil && err2 != nil { err = err2 // this is an internal assertion/check. it should not trip } // possibly change to a panic? return amountCopiedToUser, err } } }
go
func (rwaself *ReaderToWriterAdapter) Read(data []byte) (int, error) { lenToCopy := len(rwaself.writeBuffer.Bytes()) - rwaself.offset if lenToCopy > 0 { // if we have leftover data from a previous call, we can return that only if lenToCopy > len(data) { lenToCopy = len(data) } copy(data[:lenToCopy], rwaself.writeBuffer.Bytes()[rwaself.offset:rwaself.offset+lenToCopy]) rwaself.offset += lenToCopy // only return deferred errors if we have consumed the entire remainder if rwaself.offset < len(rwaself.writeBuffer.Bytes()) { return lenToCopy, nil // if still remainder left, return nil } else { err := rwaself.deferredErr rwaself.deferredErr = nil return lenToCopy, err } } rwaself.offset = 0 // if we have no data from previous runs, lets install the buffer and copy to the writer rwaself.writeBuffer.InstallNewUserBufferAndResetRemainder(data) for { // read from the upstream readBufferLenValid, err := rwaself.upstream.Read(rwaself.readBuffer) var writeErr error var closeErr error if readBufferLenValid > 0 { // copy data to the writer _, writeErr = rwaself.writer.Write(rwaself.readBuffer[:readBufferLenValid]) } if err == io.EOF && !rwaself.closedWriter { rwaself.closedWriter = true if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok { closeErr = writeCloser.Close() } } if err == nil && (writeErr != nil || closeErr != nil) { _ = rwaself.drain() // if there was an error with the writer, drain the upstream } if (err == nil || err == io.EOF) && writeErr != nil { err = writeErr } if (err == nil || err == io.EOF) && closeErr != nil { err = closeErr } if rwaself.writeBuffer.GetAmountCopiedToUser() > 0 || err != nil { if rwaself.offset < len(rwaself.writeBuffer.Bytes()) { rwaself.deferredErr = err err = nil } amountCopiedToUser, err2 := rwaself.writeBuffer.RemoveUserBuffer() if err == nil && err2 != nil { err = err2 // this is an internal assertion/check. it should not trip } // possibly change to a panic? return amountCopiedToUser, err } } }
[ "func", "(", "rwaself", "*", "ReaderToWriterAdapter", ")", "Read", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "lenToCopy", ":=", "len", "(", "rwaself", ".", "writeBuffer", ".", "Bytes", "(", ")", ")", "-", "rwaself", ".", "offset", "\n", "if", "lenToCopy", ">", "0", "{", "if", "lenToCopy", ">", "len", "(", "data", ")", "{", "lenToCopy", "=", "len", "(", "data", ")", "\n", "}", "\n", "copy", "(", "data", "[", ":", "lenToCopy", "]", ",", "rwaself", ".", "writeBuffer", ".", "Bytes", "(", ")", "[", "rwaself", ".", "offset", ":", "rwaself", ".", "offset", "+", "lenToCopy", "]", ")", "\n", "rwaself", ".", "offset", "+=", "lenToCopy", "\n", "if", "rwaself", ".", "offset", "<", "len", "(", "rwaself", ".", "writeBuffer", ".", "Bytes", "(", ")", ")", "{", "return", "lenToCopy", ",", "nil", "\n", "}", "else", "{", "err", ":=", "rwaself", ".", "deferredErr", "\n", "rwaself", ".", "deferredErr", "=", "nil", "\n", "return", "lenToCopy", ",", "err", "\n", "}", "\n", "}", "\n", "rwaself", ".", "offset", "=", "0", "\n", "rwaself", ".", "writeBuffer", ".", "InstallNewUserBufferAndResetRemainder", "(", "data", ")", "\n", "for", "{", "readBufferLenValid", ",", "err", ":=", "rwaself", ".", "upstream", ".", "Read", "(", "rwaself", ".", "readBuffer", ")", "\n", "var", "writeErr", "error", "\n", "var", "closeErr", "error", "\n", "if", "readBufferLenValid", ">", "0", "{", "_", ",", "writeErr", "=", "rwaself", ".", "writer", ".", "Write", "(", "rwaself", ".", "readBuffer", "[", ":", "readBufferLenValid", "]", ")", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "&&", "!", "rwaself", ".", "closedWriter", "{", "rwaself", ".", "closedWriter", "=", "true", "\n", "if", "writeCloser", ",", "ok", ":=", "rwaself", ".", "writer", ".", "(", "io", ".", "WriteCloser", ")", ";", "ok", "{", "closeErr", "=", "writeCloser", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "if", "err", "==", "nil", "&&", "(", "writeErr", "!=", "nil", "||", "closeErr", "!=", "nil", ")", "{", "_", "=", "rwaself", ".", "drain", "(", ")", "\n", "}", "\n", "if", "(", "err", "==", "nil", "||", "err", "==", "io", ".", "EOF", ")", "&&", "writeErr", "!=", "nil", "{", "err", "=", "writeErr", "\n", "}", "\n", "if", "(", "err", "==", "nil", "||", "err", "==", "io", ".", "EOF", ")", "&&", "closeErr", "!=", "nil", "{", "err", "=", "closeErr", "\n", "}", "\n", "if", "rwaself", ".", "writeBuffer", ".", "GetAmountCopiedToUser", "(", ")", ">", "0", "||", "err", "!=", "nil", "{", "if", "rwaself", ".", "offset", "<", "len", "(", "rwaself", ".", "writeBuffer", ".", "Bytes", "(", ")", ")", "{", "rwaself", ".", "deferredErr", "=", "err", "\n", "err", "=", "nil", "\n", "}", "\n", "amountCopiedToUser", ",", "err2", ":=", "rwaself", ".", "writeBuffer", ".", "RemoveUserBuffer", "(", ")", "\n", "if", "err", "==", "nil", "&&", "err2", "!=", "nil", "{", "err", "=", "err2", "\n", "}", "\n", "return", "amountCopiedToUser", ",", "err", "\n", "}", "\n", "}", "\n", "}" ]
// implements the Read interface by wrapping the Writer with some buffers
[ "implements", "the", "Read", "interface", "by", "wrapping", "the", "Writer", "with", "some", "buffers" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L117-L177
train
dropbox/godropbox
io2/reader_to_writer_adapter.go
Close
func (rwaself *ReaderToWriterAdapter) Close() error { var wCloseErr error var rCloseErr error if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok { if !rwaself.closedWriter { wCloseErr = writeCloser.Close() } } if readCloser, ok := rwaself.upstream.(io.ReadCloser); ok { rCloseErr = readCloser.Close() } else { rCloseErr = rwaself.drain() } if rCloseErr != nil && rCloseErr != io.EOF { return rCloseErr } if wCloseErr != nil && wCloseErr != io.EOF { return wCloseErr } return nil }
go
func (rwaself *ReaderToWriterAdapter) Close() error { var wCloseErr error var rCloseErr error if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok { if !rwaself.closedWriter { wCloseErr = writeCloser.Close() } } if readCloser, ok := rwaself.upstream.(io.ReadCloser); ok { rCloseErr = readCloser.Close() } else { rCloseErr = rwaself.drain() } if rCloseErr != nil && rCloseErr != io.EOF { return rCloseErr } if wCloseErr != nil && wCloseErr != io.EOF { return wCloseErr } return nil }
[ "func", "(", "rwaself", "*", "ReaderToWriterAdapter", ")", "Close", "(", ")", "error", "{", "var", "wCloseErr", "error", "\n", "var", "rCloseErr", "error", "\n", "if", "writeCloser", ",", "ok", ":=", "rwaself", ".", "writer", ".", "(", "io", ".", "WriteCloser", ")", ";", "ok", "{", "if", "!", "rwaself", ".", "closedWriter", "{", "wCloseErr", "=", "writeCloser", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "if", "readCloser", ",", "ok", ":=", "rwaself", ".", "upstream", ".", "(", "io", ".", "ReadCloser", ")", ";", "ok", "{", "rCloseErr", "=", "readCloser", ".", "Close", "(", ")", "\n", "}", "else", "{", "rCloseErr", "=", "rwaself", ".", "drain", "(", ")", "\n", "}", "\n", "if", "rCloseErr", "!=", "nil", "&&", "rCloseErr", "!=", "io", ".", "EOF", "{", "return", "rCloseErr", "\n", "}", "\n", "if", "wCloseErr", "!=", "nil", "&&", "wCloseErr", "!=", "io", ".", "EOF", "{", "return", "wCloseErr", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// interrupt the read by closing all resources
[ "interrupt", "the", "read", "by", "closing", "all", "resources" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L180-L200
train
dropbox/godropbox
net2/http2/gzip.go
NewGzipResponseWriter
func NewGzipResponseWriter(writer http.ResponseWriter, compressionLevel int) gzipResponseWriter { gzWriter, _ := gzip.NewWriterLevel(writer, compressionLevel) return gzipResponseWriter{ResponseWriter: writer, gzWriter: gzWriter} }
go
func NewGzipResponseWriter(writer http.ResponseWriter, compressionLevel int) gzipResponseWriter { gzWriter, _ := gzip.NewWriterLevel(writer, compressionLevel) return gzipResponseWriter{ResponseWriter: writer, gzWriter: gzWriter} }
[ "func", "NewGzipResponseWriter", "(", "writer", "http", ".", "ResponseWriter", ",", "compressionLevel", "int", ")", "gzipResponseWriter", "{", "gzWriter", ",", "_", ":=", "gzip", ".", "NewWriterLevel", "(", "writer", ",", "compressionLevel", ")", "\n", "return", "gzipResponseWriter", "{", "ResponseWriter", ":", "writer", ",", "gzWriter", ":", "gzWriter", "}", "\n", "}" ]
// compressionLevel - one of the compression levels in the gzip package.
[ "compressionLevel", "-", "one", "of", "the", "compression", "levels", "in", "the", "gzip", "package", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/gzip.go#L19-L22
train
dropbox/godropbox
sys/filelock/filelock.go
TryRLock
func (f *FileLock) TryRLock() error { return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB) }
go
func (f *FileLock) TryRLock() error { return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB) }
[ "func", "(", "f", "*", "FileLock", ")", "TryRLock", "(", ")", "error", "{", "return", "f", ".", "performLock", "(", "syscall", ".", "LOCK_SH", "|", "syscall", ".", "LOCK_NB", ")", "\n", "}" ]
// Non blocking way to try to acquire a shared lock.
[ "Non", "blocking", "way", "to", "try", "to", "acquire", "a", "shared", "lock", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sys/filelock/filelock.go#L70-L72
train
dropbox/godropbox
sys/filelock/filelock.go
TryLock
func (f *FileLock) TryLock() error { return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB) }
go
func (f *FileLock) TryLock() error { return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB) }
[ "func", "(", "f", "*", "FileLock", ")", "TryLock", "(", ")", "error", "{", "return", "f", ".", "performLock", "(", "syscall", ".", "LOCK_EX", "|", "syscall", ".", "LOCK_NB", ")", "\n", "}" ]
// Non blocking way to try to acquire an exclusive lock.
[ "Non", "blocking", "way", "to", "try", "to", "acquire", "an", "exclusive", "lock", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sys/filelock/filelock.go#L80-L82
train
dropbox/godropbox
database/sqlbuilder/column.go
DateTimeColumn
func DateTimeColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in datetime column") } dc := &dateTimeColumn{} dc.name = name dc.nullable = nullable return dc }
go
func DateTimeColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in datetime column") } dc := &dateTimeColumn{} dc.name = name dc.nullable = nullable return dc }
[ "func", "DateTimeColumn", "(", "name", "string", ",", "nullable", "NullableColumn", ")", "NonAliasColumn", "{", "if", "!", "validIdentifierName", "(", "name", ")", "{", "panic", "(", "\"Invalid column name in datetime column\"", ")", "\n", "}", "\n", "dc", ":=", "&", "dateTimeColumn", "{", "}", "\n", "dc", ".", "name", "=", "name", "\n", "dc", ".", "nullable", "=", "nullable", "\n", "return", "dc", "\n", "}" ]
// Representation of DateTime columns // This function will panic if name is not valid
[ "Representation", "of", "DateTime", "columns", "This", "function", "will", "panic", "if", "name", "is", "not", "valid" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L140-L148
train
dropbox/godropbox
database/sqlbuilder/column.go
IntColumn
func IntColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in int column") } ic := &integerColumn{} ic.name = name ic.nullable = nullable return ic }
go
func IntColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in int column") } ic := &integerColumn{} ic.name = name ic.nullable = nullable return ic }
[ "func", "IntColumn", "(", "name", "string", ",", "nullable", "NullableColumn", ")", "NonAliasColumn", "{", "if", "!", "validIdentifierName", "(", "name", ")", "{", "panic", "(", "\"Invalid column name in int column\"", ")", "\n", "}", "\n", "ic", ":=", "&", "integerColumn", "{", "}", "\n", "ic", ".", "name", "=", "name", "\n", "ic", ".", "nullable", "=", "nullable", "\n", "return", "ic", "\n", "}" ]
// Representation of any integer column // This function will panic if name is not valid
[ "Representation", "of", "any", "integer", "column", "This", "function", "will", "panic", "if", "name", "is", "not", "valid" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L157-L165
train
dropbox/godropbox
database/sqlbuilder/column.go
DoubleColumn
func DoubleColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in int column") } ic := &doubleColumn{} ic.name = name ic.nullable = nullable return ic }
go
func DoubleColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in int column") } ic := &doubleColumn{} ic.name = name ic.nullable = nullable return ic }
[ "func", "DoubleColumn", "(", "name", "string", ",", "nullable", "NullableColumn", ")", "NonAliasColumn", "{", "if", "!", "validIdentifierName", "(", "name", ")", "{", "panic", "(", "\"Invalid column name in int column\"", ")", "\n", "}", "\n", "ic", ":=", "&", "doubleColumn", "{", "}", "\n", "ic", ".", "name", "=", "name", "\n", "ic", ".", "nullable", "=", "nullable", "\n", "return", "ic", "\n", "}" ]
// Representation of any double column // This function will panic if name is not valid
[ "Representation", "of", "any", "double", "column", "This", "function", "will", "panic", "if", "name", "is", "not", "valid" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L174-L182
train
dropbox/godropbox
database/sqlbuilder/column.go
BoolColumn
func BoolColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in bool column") } bc := &booleanColumn{} bc.name = name bc.nullable = nullable return bc }
go
func BoolColumn(name string, nullable NullableColumn) NonAliasColumn { if !validIdentifierName(name) { panic("Invalid column name in bool column") } bc := &booleanColumn{} bc.name = name bc.nullable = nullable return bc }
[ "func", "BoolColumn", "(", "name", "string", ",", "nullable", "NullableColumn", ")", "NonAliasColumn", "{", "if", "!", "validIdentifierName", "(", "name", ")", "{", "panic", "(", "\"Invalid column name in bool column\"", ")", "\n", "}", "\n", "bc", ":=", "&", "booleanColumn", "{", "}", "\n", "bc", ".", "name", "=", "name", "\n", "bc", ".", "nullable", "=", "nullable", "\n", "return", "bc", "\n", "}" ]
// Representation of TINYINT used as a bool // This function will panic if name is not valid
[ "Representation", "of", "TINYINT", "used", "as", "a", "bool", "This", "function", "will", "panic", "if", "name", "is", "not", "valid" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L194-L202
train
dropbox/godropbox
resource_pool/managed_handle.go
NewManagedHandle
func NewManagedHandle( resourceLocation string, handle interface{}, pool ResourcePool, options Options) ManagedHandle { h := &managedHandleImpl{ location: resourceLocation, handle: handle, pool: pool, options: options, } atomic.StoreInt32(&h.isActive, 1) return h }
go
func NewManagedHandle( resourceLocation string, handle interface{}, pool ResourcePool, options Options) ManagedHandle { h := &managedHandleImpl{ location: resourceLocation, handle: handle, pool: pool, options: options, } atomic.StoreInt32(&h.isActive, 1) return h }
[ "func", "NewManagedHandle", "(", "resourceLocation", "string", ",", "handle", "interface", "{", "}", ",", "pool", "ResourcePool", ",", "options", "Options", ")", "ManagedHandle", "{", "h", ":=", "&", "managedHandleImpl", "{", "location", ":", "resourceLocation", ",", "handle", ":", "handle", ",", "pool", ":", "pool", ",", "options", ":", "options", ",", "}", "\n", "atomic", ".", "StoreInt32", "(", "&", "h", ".", "isActive", ",", "1", ")", "\n", "return", "h", "\n", "}" ]
// This creates a managed handle wrapper.
[ "This", "creates", "a", "managed", "handle", "wrapper", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/managed_handle.go#L46-L61
train
dropbox/godropbox
memcache/static_shard_manager.go
NewStaticShardManager
func NewStaticShardManager( serverAddrs []string, shardFunc func(key string, numShard int) (shard int), options net2.ConnectionOptions) ShardManager { manager := &StaticShardManager{} manager.Init( shardFunc, func(err error) { log.Print(err) }, log.Print, options) shardStates := make([]ShardState, len(serverAddrs), len(serverAddrs)) for i, addr := range serverAddrs { shardStates[i].Address = addr shardStates[i].State = ActiveServer } manager.UpdateShardStates(shardStates) return manager }
go
func NewStaticShardManager( serverAddrs []string, shardFunc func(key string, numShard int) (shard int), options net2.ConnectionOptions) ShardManager { manager := &StaticShardManager{} manager.Init( shardFunc, func(err error) { log.Print(err) }, log.Print, options) shardStates := make([]ShardState, len(serverAddrs), len(serverAddrs)) for i, addr := range serverAddrs { shardStates[i].Address = addr shardStates[i].State = ActiveServer } manager.UpdateShardStates(shardStates) return manager }
[ "func", "NewStaticShardManager", "(", "serverAddrs", "[", "]", "string", ",", "shardFunc", "func", "(", "key", "string", ",", "numShard", "int", ")", "(", "shard", "int", ")", ",", "options", "net2", ".", "ConnectionOptions", ")", "ShardManager", "{", "manager", ":=", "&", "StaticShardManager", "{", "}", "\n", "manager", ".", "Init", "(", "shardFunc", ",", "func", "(", "err", "error", ")", "{", "log", ".", "Print", "(", "err", ")", "}", ",", "log", ".", "Print", ",", "options", ")", "\n", "shardStates", ":=", "make", "(", "[", "]", "ShardState", ",", "len", "(", "serverAddrs", ")", ",", "len", "(", "serverAddrs", ")", ")", "\n", "for", "i", ",", "addr", ":=", "range", "serverAddrs", "{", "shardStates", "[", "i", "]", ".", "Address", "=", "addr", "\n", "shardStates", "[", "i", "]", ".", "State", "=", "ActiveServer", "\n", "}", "\n", "manager", ".", "UpdateShardStates", "(", "shardStates", ")", "\n", "return", "manager", "\n", "}" ]
// This creates a StaticShardManager, which returns connections from a static // list of memcache shards.
[ "This", "creates", "a", "StaticShardManager", "which", "returns", "connections", "from", "a", "static", "list", "of", "memcache", "shards", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/static_shard_manager.go#L22-L43
train
dropbox/godropbox
bufio2/look_ahead_buffer.go
NewLookAheadBuffer
func NewLookAheadBuffer(src io.Reader, bufferSize int) *LookAheadBuffer { return NewLookAheadBufferUsing(src, make([]byte, bufferSize, bufferSize)) }
go
func NewLookAheadBuffer(src io.Reader, bufferSize int) *LookAheadBuffer { return NewLookAheadBufferUsing(src, make([]byte, bufferSize, bufferSize)) }
[ "func", "NewLookAheadBuffer", "(", "src", "io", ".", "Reader", ",", "bufferSize", "int", ")", "*", "LookAheadBuffer", "{", "return", "NewLookAheadBufferUsing", "(", "src", ",", "make", "(", "[", "]", "byte", ",", "bufferSize", ",", "bufferSize", ")", ")", "\n", "}" ]
// NewLookAheadBuffer returns a new LookAheadBuffer whose raw buffer has EXACTLY // the specified size.
[ "NewLookAheadBuffer", "returns", "a", "new", "LookAheadBuffer", "whose", "raw", "buffer", "has", "EXACTLY", "the", "specified", "size", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L24-L26
train
dropbox/godropbox
bufio2/look_ahead_buffer.go
NewLookAheadBufferUsing
func NewLookAheadBufferUsing(src io.Reader, rawBuffer []byte) *LookAheadBuffer { return &LookAheadBuffer{ src: src, buffer: rawBuffer, bytesBuffered: 0, } }
go
func NewLookAheadBufferUsing(src io.Reader, rawBuffer []byte) *LookAheadBuffer { return &LookAheadBuffer{ src: src, buffer: rawBuffer, bytesBuffered: 0, } }
[ "func", "NewLookAheadBufferUsing", "(", "src", "io", ".", "Reader", ",", "rawBuffer", "[", "]", "byte", ")", "*", "LookAheadBuffer", "{", "return", "&", "LookAheadBuffer", "{", "src", ":", "src", ",", "buffer", ":", "rawBuffer", ",", "bytesBuffered", ":", "0", ",", "}", "\n", "}" ]
// NewLookAheadBufferUsing returns a new LookAheadBuffer which uses the // provided buffer as its raw buffer. This allows buffer reuse, which reduces // unnecessary memory allocation.
[ "NewLookAheadBufferUsing", "returns", "a", "new", "LookAheadBuffer", "which", "uses", "the", "provided", "buffer", "as", "its", "raw", "buffer", ".", "This", "allows", "buffer", "reuse", "which", "reduces", "unnecessary", "memory", "allocation", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L31-L37
train
dropbox/godropbox
bufio2/look_ahead_buffer.go
ConsumeAll
func (b *LookAheadBuffer) ConsumeAll() { err := b.Consume(b.bytesBuffered) if err != nil { // This should never happen panic(err) } }
go
func (b *LookAheadBuffer) ConsumeAll() { err := b.Consume(b.bytesBuffered) if err != nil { // This should never happen panic(err) } }
[ "func", "(", "b", "*", "LookAheadBuffer", ")", "ConsumeAll", "(", ")", "{", "err", ":=", "b", ".", "Consume", "(", "b", ".", "bytesBuffered", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// ConsumeAll drops all populated bytes from the look ahead buffer.
[ "ConsumeAll", "drops", "all", "populated", "bytes", "from", "the", "look", "ahead", "buffer", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L126-L131
train
dropbox/godropbox
database/binlog/query_event.go
IsModeEnabled
func (e *QueryEvent) IsModeEnabled(mode mysql_proto.SqlMode_BitPosition) bool { if e.sqlMode == nil { return false } return (*e.sqlMode & (uint64(1) << uint(mode))) != 0 }
go
func (e *QueryEvent) IsModeEnabled(mode mysql_proto.SqlMode_BitPosition) bool { if e.sqlMode == nil { return false } return (*e.sqlMode & (uint64(1) << uint(mode))) != 0 }
[ "func", "(", "e", "*", "QueryEvent", ")", "IsModeEnabled", "(", "mode", "mysql_proto", ".", "SqlMode_BitPosition", ")", "bool", "{", "if", "e", ".", "sqlMode", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "(", "*", "e", ".", "sqlMode", "&", "(", "uint64", "(", "1", ")", "<<", "uint", "(", "mode", ")", ")", ")", "!=", "0", "\n", "}" ]
// IsModeEnabled returns true iff sql mode status is set and the mode bit is // set.
[ "IsModeEnabled", "returns", "true", "iff", "sql", "mode", "status", "is", "set", "and", "the", "mode", "bit", "is", "set", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/query_event.go#L152-L158
train
dropbox/godropbox
database/binlog/query_event.go
Parse
func (p *QueryEventParser) Parse(raw *RawV4Event) (Event, error) { query := &QueryEvent{ Event: raw, } type fixedBodyStruct struct { ThreadId uint32 Duration uint32 DatabaseNameLength uint8 ErrorCode uint16 StatusLength uint16 } fixed := fixedBodyStruct{} _, err := readLittleEndian(raw.FixedLengthData(), &fixed) if err != nil { return raw, errors.Wrap(err, "Failed to read fixed body") } query.threadId = fixed.ThreadId query.duration = fixed.Duration query.errorCode = mysql_proto.ErrorCode_Type(fixed.ErrorCode) data := raw.VariableLengthData() dbNameEnd := int(fixed.StatusLength) + int(fixed.DatabaseNameLength) if dbNameEnd+1 > len(data) { return raw, errors.Newf("Invalid message length") } query.statusBytes = data[:fixed.StatusLength] query.databaseName = data[fixed.StatusLength:dbNameEnd] query.query = data[dbNameEnd+1:] err = p.parseStatus(query) if err != nil { return raw, err } return query, nil }
go
func (p *QueryEventParser) Parse(raw *RawV4Event) (Event, error) { query := &QueryEvent{ Event: raw, } type fixedBodyStruct struct { ThreadId uint32 Duration uint32 DatabaseNameLength uint8 ErrorCode uint16 StatusLength uint16 } fixed := fixedBodyStruct{} _, err := readLittleEndian(raw.FixedLengthData(), &fixed) if err != nil { return raw, errors.Wrap(err, "Failed to read fixed body") } query.threadId = fixed.ThreadId query.duration = fixed.Duration query.errorCode = mysql_proto.ErrorCode_Type(fixed.ErrorCode) data := raw.VariableLengthData() dbNameEnd := int(fixed.StatusLength) + int(fixed.DatabaseNameLength) if dbNameEnd+1 > len(data) { return raw, errors.Newf("Invalid message length") } query.statusBytes = data[:fixed.StatusLength] query.databaseName = data[fixed.StatusLength:dbNameEnd] query.query = data[dbNameEnd+1:] err = p.parseStatus(query) if err != nil { return raw, err } return query, nil }
[ "func", "(", "p", "*", "QueryEventParser", ")", "Parse", "(", "raw", "*", "RawV4Event", ")", "(", "Event", ",", "error", ")", "{", "query", ":=", "&", "QueryEvent", "{", "Event", ":", "raw", ",", "}", "\n", "type", "fixedBodyStruct", "struct", "{", "ThreadId", "uint32", "\n", "Duration", "uint32", "\n", "DatabaseNameLength", "uint8", "\n", "ErrorCode", "uint16", "\n", "StatusLength", "uint16", "\n", "}", "\n", "fixed", ":=", "fixedBodyStruct", "{", "}", "\n", "_", ",", "err", ":=", "readLittleEndian", "(", "raw", ".", "FixedLengthData", "(", ")", ",", "&", "fixed", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read fixed body\"", ")", "\n", "}", "\n", "query", ".", "threadId", "=", "fixed", ".", "ThreadId", "\n", "query", ".", "duration", "=", "fixed", ".", "Duration", "\n", "query", ".", "errorCode", "=", "mysql_proto", ".", "ErrorCode_Type", "(", "fixed", ".", "ErrorCode", ")", "\n", "data", ":=", "raw", ".", "VariableLengthData", "(", ")", "\n", "dbNameEnd", ":=", "int", "(", "fixed", ".", "StatusLength", ")", "+", "int", "(", "fixed", ".", "DatabaseNameLength", ")", "\n", "if", "dbNameEnd", "+", "1", ">", "len", "(", "data", ")", "{", "return", "raw", ",", "errors", ".", "Newf", "(", "\"Invalid message length\"", ")", "\n", "}", "\n", "query", ".", "statusBytes", "=", "data", "[", ":", "fixed", ".", "StatusLength", "]", "\n", "query", ".", "databaseName", "=", "data", "[", "fixed", ".", "StatusLength", ":", "dbNameEnd", "]", "\n", "query", ".", "query", "=", "data", "[", "dbNameEnd", "+", "1", ":", "]", "\n", "err", "=", "p", ".", "parseStatus", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "err", "\n", "}", "\n", "return", "query", ",", "nil", "\n", "}" ]
// QueryEventParser's Parse processes a raw query event into a QueryEvent.
[ "QueryEventParser", "s", "Parse", "processes", "a", "raw", "query", "event", "into", "a", "QueryEvent", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/query_event.go#L259-L302
train
dropbox/godropbox
database/binlog/rotate_event.go
Parse
func (p *RotateEventParser) Parse(raw *RawV4Event) (Event, error) { rotate := &RotateEvent{ Event: raw, newLogName: raw.VariableLengthData(), } _, err := readLittleEndian(raw.FixedLengthData(), &rotate.newPosition) if err != nil { return raw, errors.Wrap(err, "Failed to read new log position") } return rotate, nil }
go
func (p *RotateEventParser) Parse(raw *RawV4Event) (Event, error) { rotate := &RotateEvent{ Event: raw, newLogName: raw.VariableLengthData(), } _, err := readLittleEndian(raw.FixedLengthData(), &rotate.newPosition) if err != nil { return raw, errors.Wrap(err, "Failed to read new log position") } return rotate, nil }
[ "func", "(", "p", "*", "RotateEventParser", ")", "Parse", "(", "raw", "*", "RawV4Event", ")", "(", "Event", ",", "error", ")", "{", "rotate", ":=", "&", "RotateEvent", "{", "Event", ":", "raw", ",", "newLogName", ":", "raw", ".", "VariableLengthData", "(", ")", ",", "}", "\n", "_", ",", "err", ":=", "readLittleEndian", "(", "raw", ".", "FixedLengthData", "(", ")", ",", "&", "rotate", ".", "newPosition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read new log position\"", ")", "\n", "}", "\n", "return", "rotate", ",", "nil", "\n", "}" ]
// RotateEventParser's Parse processes a raw rotate event into a RotateEvent.
[ "RotateEventParser", "s", "Parse", "processes", "a", "raw", "rotate", "event", "into", "a", "RotateEvent", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/rotate_event.go#L57-L69
train
dropbox/godropbox
database/binlog/format_description_event.go
FixedLengthDataSizeForType
func (e *FormatDescriptionEvent) FixedLengthDataSizeForType( eventType mysql_proto.LogEventType_Type) int { return e.fixedLengthSizes[eventType] }
go
func (e *FormatDescriptionEvent) FixedLengthDataSizeForType( eventType mysql_proto.LogEventType_Type) int { return e.fixedLengthSizes[eventType] }
[ "func", "(", "e", "*", "FormatDescriptionEvent", ")", "FixedLengthDataSizeForType", "(", "eventType", "mysql_proto", ".", "LogEventType_Type", ")", "int", "{", "return", "e", ".", "fixedLengthSizes", "[", "eventType", "]", "\n", "}" ]
// FixedLengthDataSizeForType returns the size of fixed length data for each // event type.
[ "FixedLengthDataSizeForType", "returns", "the", "size", "of", "fixed", "length", "data", "for", "each", "event", "type", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/format_description_event.go#L73-L77
train
dropbox/godropbox
database/binlog/format_description_event.go
Parse
func (p *FormatDescriptionEventParser) Parse(raw *RawV4Event) (Event, error) { fde := &FormatDescriptionEvent{ Event: raw, fixedLengthSizes: make(map[mysql_proto.LogEventType_Type]int), } data := raw.VariableLengthData() data, err := readLittleEndian(data, &fde.binlogVersion) if err != nil { return raw, errors.Wrap(err, "Failed to read binlog version") } serverVersion, data, err := readSlice(data, 50) if err != nil { return raw, errors.Wrap(err, "Failed to read server version") } if idx := bytes.IndexByte(serverVersion, byte(0)); idx > -1 { serverVersion = serverVersion[:idx] } fde.serverVersion = serverVersion data, err = readLittleEndian(data, &fde.createdTimestamp) if err != nil { return raw, errors.Wrap(err, "Failed to read created timestamp") } var totalHeaderSize uint8 data, err = readLittleEndian(data, &totalHeaderSize) if err != nil { return raw, errors.Wrap(err, "Failed to read total header size") } fde.extraHeadersSize = int(totalHeaderSize) - sizeOfBasicV4EventHeader numEvents := len(mysql_proto.LogEventType_Type_value) hasChecksum := true if len(data) == 27 { // mysql 5.5(.37) numEvents = 28 hasChecksum = false } else if len(data) == 40 { // mysql 5.6(.17) // This is a relay log where the master is 5.5 and slave is 5.6 if data[int(mysql_proto.LogEventType_WRITE_ROWS_EVENT)-1] == 0 { numEvents = 28 } } else { return raw, errors.Newf( "Unable to parse FDE for mysql variant: %s", fde.serverVersion) } // unknown event's fixed length is implicit. fde.fixedLengthSizes[mysql_proto.LogEventType_UNKNOWN_EVENT] = 0 for i := 1; i < numEvents; i++ { fde.fixedLengthSizes[mysql_proto.LogEventType_Type(i)] = int(data[i-1]) } if hasChecksum { fde.checksumAlgorithm = mysql_proto.ChecksumAlgorithm_Type( data[len(data)-5]) raw.SetChecksumSize(4) } return fde, nil }
go
func (p *FormatDescriptionEventParser) Parse(raw *RawV4Event) (Event, error) { fde := &FormatDescriptionEvent{ Event: raw, fixedLengthSizes: make(map[mysql_proto.LogEventType_Type]int), } data := raw.VariableLengthData() data, err := readLittleEndian(data, &fde.binlogVersion) if err != nil { return raw, errors.Wrap(err, "Failed to read binlog version") } serverVersion, data, err := readSlice(data, 50) if err != nil { return raw, errors.Wrap(err, "Failed to read server version") } if idx := bytes.IndexByte(serverVersion, byte(0)); idx > -1 { serverVersion = serverVersion[:idx] } fde.serverVersion = serverVersion data, err = readLittleEndian(data, &fde.createdTimestamp) if err != nil { return raw, errors.Wrap(err, "Failed to read created timestamp") } var totalHeaderSize uint8 data, err = readLittleEndian(data, &totalHeaderSize) if err != nil { return raw, errors.Wrap(err, "Failed to read total header size") } fde.extraHeadersSize = int(totalHeaderSize) - sizeOfBasicV4EventHeader numEvents := len(mysql_proto.LogEventType_Type_value) hasChecksum := true if len(data) == 27 { // mysql 5.5(.37) numEvents = 28 hasChecksum = false } else if len(data) == 40 { // mysql 5.6(.17) // This is a relay log where the master is 5.5 and slave is 5.6 if data[int(mysql_proto.LogEventType_WRITE_ROWS_EVENT)-1] == 0 { numEvents = 28 } } else { return raw, errors.Newf( "Unable to parse FDE for mysql variant: %s", fde.serverVersion) } // unknown event's fixed length is implicit. fde.fixedLengthSizes[mysql_proto.LogEventType_UNKNOWN_EVENT] = 0 for i := 1; i < numEvents; i++ { fde.fixedLengthSizes[mysql_proto.LogEventType_Type(i)] = int(data[i-1]) } if hasChecksum { fde.checksumAlgorithm = mysql_proto.ChecksumAlgorithm_Type( data[len(data)-5]) raw.SetChecksumSize(4) } return fde, nil }
[ "func", "(", "p", "*", "FormatDescriptionEventParser", ")", "Parse", "(", "raw", "*", "RawV4Event", ")", "(", "Event", ",", "error", ")", "{", "fde", ":=", "&", "FormatDescriptionEvent", "{", "Event", ":", "raw", ",", "fixedLengthSizes", ":", "make", "(", "map", "[", "mysql_proto", ".", "LogEventType_Type", "]", "int", ")", ",", "}", "\n", "data", ":=", "raw", ".", "VariableLengthData", "(", ")", "\n", "data", ",", "err", ":=", "readLittleEndian", "(", "data", ",", "&", "fde", ".", "binlogVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read binlog version\"", ")", "\n", "}", "\n", "serverVersion", ",", "data", ",", "err", ":=", "readSlice", "(", "data", ",", "50", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read server version\"", ")", "\n", "}", "\n", "if", "idx", ":=", "bytes", ".", "IndexByte", "(", "serverVersion", ",", "byte", "(", "0", ")", ")", ";", "idx", ">", "-", "1", "{", "serverVersion", "=", "serverVersion", "[", ":", "idx", "]", "\n", "}", "\n", "fde", ".", "serverVersion", "=", "serverVersion", "\n", "data", ",", "err", "=", "readLittleEndian", "(", "data", ",", "&", "fde", ".", "createdTimestamp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read created timestamp\"", ")", "\n", "}", "\n", "var", "totalHeaderSize", "uint8", "\n", "data", ",", "err", "=", "readLittleEndian", "(", "data", ",", "&", "totalHeaderSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "raw", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to read total header size\"", ")", "\n", "}", "\n", "fde", ".", "extraHeadersSize", "=", "int", "(", "totalHeaderSize", ")", "-", "sizeOfBasicV4EventHeader", "\n", "numEvents", ":=", "len", "(", "mysql_proto", ".", "LogEventType_Type_value", ")", "\n", "hasChecksum", ":=", "true", "\n", "if", "len", "(", "data", ")", "==", "27", "{", "numEvents", "=", "28", "\n", "hasChecksum", "=", "false", "\n", "}", "else", "if", "len", "(", "data", ")", "==", "40", "{", "if", "data", "[", "int", "(", "mysql_proto", ".", "LogEventType_WRITE_ROWS_EVENT", ")", "-", "1", "]", "==", "0", "{", "numEvents", "=", "28", "\n", "}", "\n", "}", "else", "{", "return", "raw", ",", "errors", ".", "Newf", "(", "\"Unable to parse FDE for mysql variant: %s\"", ",", "fde", ".", "serverVersion", ")", "\n", "}", "\n", "fde", ".", "fixedLengthSizes", "[", "mysql_proto", ".", "LogEventType_UNKNOWN_EVENT", "]", "=", "0", "\n", "for", "i", ":=", "1", ";", "i", "<", "numEvents", ";", "i", "++", "{", "fde", ".", "fixedLengthSizes", "[", "mysql_proto", ".", "LogEventType_Type", "(", "i", ")", "]", "=", "int", "(", "data", "[", "i", "-", "1", "]", ")", "\n", "}", "\n", "if", "hasChecksum", "{", "fde", ".", "checksumAlgorithm", "=", "mysql_proto", ".", "ChecksumAlgorithm_Type", "(", "data", "[", "len", "(", "data", ")", "-", "5", "]", ")", "\n", "raw", ".", "SetChecksumSize", "(", "4", ")", "\n", "}", "\n", "return", "fde", ",", "nil", "\n", "}" ]
// FormatDecriptionEventParser's Parse processes a raw FDE event into a // FormatDescriptionEvent.
[ "FormatDecriptionEventParser", "s", "Parse", "processes", "a", "raw", "FDE", "event", "into", "a", "FormatDescriptionEvent", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/format_description_event.go#L116-L182
train
dropbox/godropbox
lockstore/store.go
New
func New(options LockStoreOptions) LockStore { testTryLockCallback := options.testTryLockCallback if testTryLockCallback == nil { testTryLockCallback = func() {} } lock := _LockStoreImp{ granularity: options.Granularity, testTryLockCallback: testTryLockCallback, } switch options.Granularity { case PerKeyGranularity: lock.perKeyLocks = make(map[string]*_LockImp) case ShardedGranularity: lock.shardedLocks = make([]*sync.RWMutex, options.LockCount) for i := range lock.shardedLocks { lock.shardedLocks[i] = &sync.RWMutex{} } } return &lock }
go
func New(options LockStoreOptions) LockStore { testTryLockCallback := options.testTryLockCallback if testTryLockCallback == nil { testTryLockCallback = func() {} } lock := _LockStoreImp{ granularity: options.Granularity, testTryLockCallback: testTryLockCallback, } switch options.Granularity { case PerKeyGranularity: lock.perKeyLocks = make(map[string]*_LockImp) case ShardedGranularity: lock.shardedLocks = make([]*sync.RWMutex, options.LockCount) for i := range lock.shardedLocks { lock.shardedLocks[i] = &sync.RWMutex{} } } return &lock }
[ "func", "New", "(", "options", "LockStoreOptions", ")", "LockStore", "{", "testTryLockCallback", ":=", "options", ".", "testTryLockCallback", "\n", "if", "testTryLockCallback", "==", "nil", "{", "testTryLockCallback", "=", "func", "(", ")", "{", "}", "\n", "}", "\n", "lock", ":=", "_LockStoreImp", "{", "granularity", ":", "options", ".", "Granularity", ",", "testTryLockCallback", ":", "testTryLockCallback", ",", "}", "\n", "switch", "options", ".", "Granularity", "{", "case", "PerKeyGranularity", ":", "lock", ".", "perKeyLocks", "=", "make", "(", "map", "[", "string", "]", "*", "_LockImp", ")", "\n", "case", "ShardedGranularity", ":", "lock", ".", "shardedLocks", "=", "make", "(", "[", "]", "*", "sync", ".", "RWMutex", ",", "options", ".", "LockCount", ")", "\n", "for", "i", ":=", "range", "lock", ".", "shardedLocks", "{", "lock", ".", "shardedLocks", "[", "i", "]", "=", "&", "sync", ".", "RWMutex", "{", "}", "\n", "}", "\n", "}", "\n", "return", "&", "lock", "\n", "}" ]
// New creates a new LockStore given the options
[ "New", "creates", "a", "new", "LockStore", "given", "the", "options" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/store.go#L91-L113
train
dropbox/godropbox
memcache/sharded_client.go
NewShardedClient
func NewShardedClient( manager ShardManager, builder ClientShardBuilder) Client { return &ShardedClient{ manager: manager, builder: builder, } }
go
func NewShardedClient( manager ShardManager, builder ClientShardBuilder) Client { return &ShardedClient{ manager: manager, builder: builder, } }
[ "func", "NewShardedClient", "(", "manager", "ShardManager", ",", "builder", "ClientShardBuilder", ")", "Client", "{", "return", "&", "ShardedClient", "{", "manager", ":", "manager", ",", "builder", ":", "builder", ",", "}", "\n", "}" ]
// This creates a new ShardedClient.
[ "This", "creates", "a", "new", "ShardedClient", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L24-L32
train
dropbox/godropbox
memcache/sharded_client.go
setMultiMutator
func setMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.SetMulti(mapping.Items) }
go
func setMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.SetMulti(mapping.Items) }
[ "func", "setMultiMutator", "(", "shardClient", "Client", ",", "mapping", "*", "ShardMapping", ")", "[", "]", "MutateResponse", "{", "return", "shardClient", ".", "SetMulti", "(", "mapping", ".", "Items", ")", "\n", "}" ]
// A helper used to specify a SetMulti mutation operation on a shard client.
[ "A", "helper", "used", "to", "specify", "a", "SetMulti", "mutation", "operation", "on", "a", "shard", "client", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L260-L262
train
dropbox/godropbox
memcache/sharded_client.go
casMultiMutator
func casMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.CasMulti(mapping.Items) }
go
func casMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.CasMulti(mapping.Items) }
[ "func", "casMultiMutator", "(", "shardClient", "Client", ",", "mapping", "*", "ShardMapping", ")", "[", "]", "MutateResponse", "{", "return", "shardClient", ".", "CasMulti", "(", "mapping", ".", "Items", ")", "\n", "}" ]
// A helper used to specify a CasMulti mutation operation on a shard client.
[ "A", "helper", "used", "to", "specify", "a", "CasMulti", "mutation", "operation", "on", "a", "shard", "client", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L265-L267
train
dropbox/godropbox
memcache/sharded_client.go
addMultiMutator
func addMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.AddMulti(mapping.Items) }
go
func addMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.AddMulti(mapping.Items) }
[ "func", "addMultiMutator", "(", "shardClient", "Client", ",", "mapping", "*", "ShardMapping", ")", "[", "]", "MutateResponse", "{", "return", "shardClient", ".", "AddMulti", "(", "mapping", ".", "Items", ")", "\n", "}" ]
// A helper used to specify a AddMulti mutation operation on a shard client.
[ "A", "helper", "used", "to", "specify", "a", "AddMulti", "mutation", "operation", "on", "a", "shard", "client", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L299-L301
train
dropbox/godropbox
memcache/sharded_client.go
deleteMultiMutator
func deleteMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.DeleteMulti(mapping.Keys) }
go
func deleteMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse { return shardClient.DeleteMulti(mapping.Keys) }
[ "func", "deleteMultiMutator", "(", "shardClient", "Client", ",", "mapping", "*", "ShardMapping", ")", "[", "]", "MutateResponse", "{", "return", "shardClient", ".", "DeleteMulti", "(", "mapping", ".", "Keys", ")", "\n", "}" ]
// A helper used to specify a DeleteMulti mutation operation on a shard client.
[ "A", "helper", "used", "to", "specify", "a", "DeleteMulti", "mutation", "operation", "on", "a", "shard", "client", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L327-L329
train
dropbox/godropbox
database/binlog/event_parser.go
NewV4EventParserMap
func NewV4EventParserMap() V4EventParserMap { m := &v4EventParserMap{ extraHeadersSize: nonFDEExtraHeadersSize, checksumSize: 0, parsers: make(map[mysql_proto.LogEventType_Type]V4EventParser), } // TODO(patrick): implement parsers m.set(&FormatDescriptionEventParser{}) m.set(&QueryEventParser{}) m.set(&RotateEventParser{}) m.set(&TableMapEventParser{}) m.set(&XidEventParser{}) m.set(&RowsQueryEventParser{}) m.set(&GtidLogEventParser{}) m.set(&PreviousGtidsLogEventParser{}) m.set(newWriteRowsEventV1Parser()) m.set(newWriteRowsEventV2Parser()) m.set(newUpdateRowsEventV1Parser()) m.set(newUpdateRowsEventV2Parser()) m.set(newDeleteRowsEventV1Parser()) m.set(newDeleteRowsEventV2Parser()) m.set(newStopEventParser()) m.numSupportedEventTypes = len(mysql_proto.LogEventType_Type_name) return m }
go
func NewV4EventParserMap() V4EventParserMap { m := &v4EventParserMap{ extraHeadersSize: nonFDEExtraHeadersSize, checksumSize: 0, parsers: make(map[mysql_proto.LogEventType_Type]V4EventParser), } // TODO(patrick): implement parsers m.set(&FormatDescriptionEventParser{}) m.set(&QueryEventParser{}) m.set(&RotateEventParser{}) m.set(&TableMapEventParser{}) m.set(&XidEventParser{}) m.set(&RowsQueryEventParser{}) m.set(&GtidLogEventParser{}) m.set(&PreviousGtidsLogEventParser{}) m.set(newWriteRowsEventV1Parser()) m.set(newWriteRowsEventV2Parser()) m.set(newUpdateRowsEventV1Parser()) m.set(newUpdateRowsEventV2Parser()) m.set(newDeleteRowsEventV1Parser()) m.set(newDeleteRowsEventV2Parser()) m.set(newStopEventParser()) m.numSupportedEventTypes = len(mysql_proto.LogEventType_Type_name) return m }
[ "func", "NewV4EventParserMap", "(", ")", "V4EventParserMap", "{", "m", ":=", "&", "v4EventParserMap", "{", "extraHeadersSize", ":", "nonFDEExtraHeadersSize", ",", "checksumSize", ":", "0", ",", "parsers", ":", "make", "(", "map", "[", "mysql_proto", ".", "LogEventType_Type", "]", "V4EventParser", ")", ",", "}", "\n", "m", ".", "set", "(", "&", "FormatDescriptionEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "QueryEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "RotateEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "TableMapEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "XidEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "RowsQueryEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "GtidLogEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "&", "PreviousGtidsLogEventParser", "{", "}", ")", "\n", "m", ".", "set", "(", "newWriteRowsEventV1Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newWriteRowsEventV2Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newUpdateRowsEventV1Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newUpdateRowsEventV2Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newDeleteRowsEventV1Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newDeleteRowsEventV2Parser", "(", ")", ")", "\n", "m", ".", "set", "(", "newStopEventParser", "(", ")", ")", "\n", "m", ".", "numSupportedEventTypes", "=", "len", "(", "mysql_proto", ".", "LogEventType_Type_name", ")", "\n", "return", "m", "\n", "}" ]
// NewV4EventParserMap returns an initialize V4EventParserMap with all handled // event types' parsers registered.
[ "NewV4EventParserMap", "returns", "an", "initialize", "V4EventParserMap", "with", "all", "handled", "event", "types", "parsers", "registered", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event_parser.go#L92-L119
train
dropbox/godropbox
errors/errors.go
GetMessage
func GetMessage(err interface{}) string { switch e := err.(type) { case DropboxError: return extractFullErrorMessage(e, false) case runtime.Error: return runtime.Error(e).Error() case error: return e.Error() default: return "Passed a non-error to GetMessage" } }
go
func GetMessage(err interface{}) string { switch e := err.(type) { case DropboxError: return extractFullErrorMessage(e, false) case runtime.Error: return runtime.Error(e).Error() case error: return e.Error() default: return "Passed a non-error to GetMessage" } }
[ "func", "GetMessage", "(", "err", "interface", "{", "}", ")", "string", "{", "switch", "e", ":=", "err", ".", "(", "type", ")", "{", "case", "DropboxError", ":", "return", "extractFullErrorMessage", "(", "e", ",", "false", ")", "\n", "case", "runtime", ".", "Error", ":", "return", "runtime", ".", "Error", "(", "e", ")", ".", "Error", "(", ")", "\n", "case", "error", ":", "return", "e", ".", "Error", "(", ")", "\n", "default", ":", "return", "\"Passed a non-error to GetMessage\"", "\n", "}", "\n", "}" ]
// This returns the error string without stack trace information.
[ "This", "returns", "the", "error", "string", "without", "stack", "trace", "information", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L72-L83
train
dropbox/godropbox
errors/errors.go
Newf
func Newf(format string, args ...interface{}) DropboxError { return new(nil, fmt.Sprintf(format, args...)) }
go
func Newf(format string, args ...interface{}) DropboxError { return new(nil, fmt.Sprintf(format, args...)) }
[ "func", "Newf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "DropboxError", "{", "return", "new", "(", "nil", ",", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ")", "\n", "}" ]
// Same as New, but with fmt.Printf-style parameters.
[ "Same", "as", "New", "but", "with", "fmt", ".", "Printf", "-", "style", "parameters", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L148-L150
train
dropbox/godropbox
errors/errors.go
Wrapf
func Wrapf(err error, format string, args ...interface{}) DropboxError { return new(err, fmt.Sprintf(format, args...)) }
go
func Wrapf(err error, format string, args ...interface{}) DropboxError { return new(err, fmt.Sprintf(format, args...)) }
[ "func", "Wrapf", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "DropboxError", "{", "return", "new", "(", "err", ",", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ")", "\n", "}" ]
// Same as Wrap, but with fmt.Printf-style parameters.
[ "Same", "as", "Wrap", "but", "with", "fmt", ".", "Printf", "-", "style", "parameters", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L158-L160
train
dropbox/godropbox
errors/errors.go
new
func new(err error, msg string) *baseError { stack := make([]uintptr, 200) stackLength := runtime.Callers(3, stack) return &baseError{ msg: msg, stack: stack[:stackLength], inner: err, } }
go
func new(err error, msg string) *baseError { stack := make([]uintptr, 200) stackLength := runtime.Callers(3, stack) return &baseError{ msg: msg, stack: stack[:stackLength], inner: err, } }
[ "func", "new", "(", "err", "error", ",", "msg", "string", ")", "*", "baseError", "{", "stack", ":=", "make", "(", "[", "]", "uintptr", ",", "200", ")", "\n", "stackLength", ":=", "runtime", ".", "Callers", "(", "3", ",", "stack", ")", "\n", "return", "&", "baseError", "{", "msg", ":", "msg", ",", "stack", ":", "stack", "[", ":", "stackLength", "]", ",", "inner", ":", "err", ",", "}", "\n", "}" ]
// Internal helper function to create new baseError objects, // note that if there is more than one level of redirection to call this function, // stack frame information will include that level too.
[ "Internal", "helper", "function", "to", "create", "new", "baseError", "objects", "note", "that", "if", "there", "is", "more", "than", "one", "level", "of", "redirection", "to", "call", "this", "function", "stack", "frame", "information", "will", "include", "that", "level", "too", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L165-L173
train
dropbox/godropbox
errors/errors.go
extractFullErrorMessage
func extractFullErrorMessage(e DropboxError, includeStack bool) string { var ok bool var lastDbxErr DropboxError errMsg := bytes.NewBuffer(make([]byte, 0, 1024)) dbxErr := e for { lastDbxErr = dbxErr errMsg.WriteString(dbxErr.GetMessage()) innerErr := dbxErr.GetInner() if innerErr == nil { break } dbxErr, ok = innerErr.(DropboxError) if !ok { // We have reached the end and traveresed all inner errors. // Add last message and exit loop. errMsg.WriteString(innerErr.Error()) break } errMsg.WriteString("\n") } if includeStack { errMsg.WriteString("\nORIGINAL STACK TRACE:\n") errMsg.WriteString(lastDbxErr.GetStack()) } return errMsg.String() }
go
func extractFullErrorMessage(e DropboxError, includeStack bool) string { var ok bool var lastDbxErr DropboxError errMsg := bytes.NewBuffer(make([]byte, 0, 1024)) dbxErr := e for { lastDbxErr = dbxErr errMsg.WriteString(dbxErr.GetMessage()) innerErr := dbxErr.GetInner() if innerErr == nil { break } dbxErr, ok = innerErr.(DropboxError) if !ok { // We have reached the end and traveresed all inner errors. // Add last message and exit loop. errMsg.WriteString(innerErr.Error()) break } errMsg.WriteString("\n") } if includeStack { errMsg.WriteString("\nORIGINAL STACK TRACE:\n") errMsg.WriteString(lastDbxErr.GetStack()) } return errMsg.String() }
[ "func", "extractFullErrorMessage", "(", "e", "DropboxError", ",", "includeStack", "bool", ")", "string", "{", "var", "ok", "bool", "\n", "var", "lastDbxErr", "DropboxError", "\n", "errMsg", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "1024", ")", ")", "\n", "dbxErr", ":=", "e", "\n", "for", "{", "lastDbxErr", "=", "dbxErr", "\n", "errMsg", ".", "WriteString", "(", "dbxErr", ".", "GetMessage", "(", ")", ")", "\n", "innerErr", ":=", "dbxErr", ".", "GetInner", "(", ")", "\n", "if", "innerErr", "==", "nil", "{", "break", "\n", "}", "\n", "dbxErr", ",", "ok", "=", "innerErr", ".", "(", "DropboxError", ")", "\n", "if", "!", "ok", "{", "errMsg", ".", "WriteString", "(", "innerErr", ".", "Error", "(", ")", ")", "\n", "break", "\n", "}", "\n", "errMsg", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "}", "\n", "\\n", "\n", "if", "includeStack", "{", "errMsg", ".", "WriteString", "(", "\"\\nORIGINAL STACK TRACE:\\n\"", ")", "\n", "\\n", "\n", "}", "\n", "}" ]
// Constructs full error message for a given DropboxError by traversing // all of its inner errors. If includeStack is True it will also include // stack trace from deepest DropboxError in the chain.
[ "Constructs", "full", "error", "message", "for", "a", "given", "DropboxError", "by", "traversing", "all", "of", "its", "inner", "errors", ".", "If", "includeStack", "is", "True", "it", "will", "also", "include", "stack", "trace", "from", "deepest", "DropboxError", "in", "the", "chain", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L178-L206
train
dropbox/godropbox
errors/errors.go
unwrapError
func unwrapError(ierr error) (nerr error) { // Internal errors have a well defined bit of context. if dbxErr, ok := ierr.(DropboxError); ok { return dbxErr.GetInner() } // At this point, if anything goes wrong, just return nil. defer func() { if x := recover(); x != nil { nerr = nil } }() // Go system errors have a convention but paradoxically no // interface. All of these panic on error. errV := reflect.ValueOf(ierr).Elem() errV = errV.FieldByName("Err") return errV.Interface().(error) }
go
func unwrapError(ierr error) (nerr error) { // Internal errors have a well defined bit of context. if dbxErr, ok := ierr.(DropboxError); ok { return dbxErr.GetInner() } // At this point, if anything goes wrong, just return nil. defer func() { if x := recover(); x != nil { nerr = nil } }() // Go system errors have a convention but paradoxically no // interface. All of these panic on error. errV := reflect.ValueOf(ierr).Elem() errV = errV.FieldByName("Err") return errV.Interface().(error) }
[ "func", "unwrapError", "(", "ierr", "error", ")", "(", "nerr", "error", ")", "{", "if", "dbxErr", ",", "ok", ":=", "ierr", ".", "(", "DropboxError", ")", ";", "ok", "{", "return", "dbxErr", ".", "GetInner", "(", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "x", ":=", "recover", "(", ")", ";", "x", "!=", "nil", "{", "nerr", "=", "nil", "\n", "}", "\n", "}", "(", ")", "\n", "errV", ":=", "reflect", ".", "ValueOf", "(", "ierr", ")", ".", "Elem", "(", ")", "\n", "errV", "=", "errV", ".", "FieldByName", "(", "\"Err\"", ")", "\n", "return", "errV", ".", "Interface", "(", ")", ".", "(", "error", ")", "\n", "}" ]
// Return a wrapped error or nil if there is none.
[ "Return", "a", "wrapped", "error", "or", "nil", "if", "there", "is", "none", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L209-L227
train
dropbox/godropbox
errors/errors.go
RootError
func RootError(ierr error) (nerr error) { nerr = ierr for i := 0; i < 20; i++ { terr := unwrapError(nerr) if terr == nil { return nerr } nerr = terr } return fmt.Errorf("too many iterations: %T", nerr) }
go
func RootError(ierr error) (nerr error) { nerr = ierr for i := 0; i < 20; i++ { terr := unwrapError(nerr) if terr == nil { return nerr } nerr = terr } return fmt.Errorf("too many iterations: %T", nerr) }
[ "func", "RootError", "(", "ierr", "error", ")", "(", "nerr", "error", ")", "{", "nerr", "=", "ierr", "\n", "for", "i", ":=", "0", ";", "i", "<", "20", ";", "i", "++", "{", "terr", ":=", "unwrapError", "(", "nerr", ")", "\n", "if", "terr", "==", "nil", "{", "return", "nerr", "\n", "}", "\n", "nerr", "=", "terr", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"too many iterations: %T\"", ",", "nerr", ")", "\n", "}" ]
// Keep peeling away layers or context until a primitive error is revealed.
[ "Keep", "peeling", "away", "layers", "or", "context", "until", "a", "primitive", "error", "is", "revealed", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L230-L240
train
dropbox/godropbox
errors/errors.go
IsError
func IsError(err, errConst error) bool { if err == errConst { return true } // Must rely on string equivalence, otherwise a value is not equal // to its pointer value. rootErrStr := "" rootErr := RootError(err) if rootErr != nil { rootErrStr = rootErr.Error() } errConstStr := "" if errConst != nil { errConstStr = errConst.Error() } return rootErrStr == errConstStr }
go
func IsError(err, errConst error) bool { if err == errConst { return true } // Must rely on string equivalence, otherwise a value is not equal // to its pointer value. rootErrStr := "" rootErr := RootError(err) if rootErr != nil { rootErrStr = rootErr.Error() } errConstStr := "" if errConst != nil { errConstStr = errConst.Error() } return rootErrStr == errConstStr }
[ "func", "IsError", "(", "err", ",", "errConst", "error", ")", "bool", "{", "if", "err", "==", "errConst", "{", "return", "true", "\n", "}", "\n", "rootErrStr", ":=", "\"\"", "\n", "rootErr", ":=", "RootError", "(", "err", ")", "\n", "if", "rootErr", "!=", "nil", "{", "rootErrStr", "=", "rootErr", ".", "Error", "(", ")", "\n", "}", "\n", "errConstStr", ":=", "\"\"", "\n", "if", "errConst", "!=", "nil", "{", "errConstStr", "=", "errConst", ".", "Error", "(", ")", "\n", "}", "\n", "return", "rootErrStr", "==", "errConstStr", "\n", "}" ]
// Perform a deep check, unwrapping errors as much as possilbe and // comparing the string version of the error.
[ "Perform", "a", "deep", "check", "unwrapping", "errors", "as", "much", "as", "possilbe", "and", "comparing", "the", "string", "version", "of", "the", "error", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L244-L260
train
dropbox/godropbox
database/binlog/rows_query_event.go
Parse
func (p *RowsQueryEventParser) Parse(raw *RawV4Event) (Event, error) { query := &RowsQueryEvent{ Event: raw, } data := raw.VariableLengthData() if len(data) < 1 { return raw, errors.Newf("Invalid message length") } query.truncatedQuery = data[1:] return query, nil }
go
func (p *RowsQueryEventParser) Parse(raw *RawV4Event) (Event, error) { query := &RowsQueryEvent{ Event: raw, } data := raw.VariableLengthData() if len(data) < 1 { return raw, errors.Newf("Invalid message length") } query.truncatedQuery = data[1:] return query, nil }
[ "func", "(", "p", "*", "RowsQueryEventParser", ")", "Parse", "(", "raw", "*", "RawV4Event", ")", "(", "Event", ",", "error", ")", "{", "query", ":=", "&", "RowsQueryEvent", "{", "Event", ":", "raw", ",", "}", "\n", "data", ":=", "raw", ".", "VariableLengthData", "(", ")", "\n", "if", "len", "(", "data", ")", "<", "1", "{", "return", "raw", ",", "errors", ".", "Newf", "(", "\"Invalid message length\"", ")", "\n", "}", "\n", "query", ".", "truncatedQuery", "=", "data", "[", "1", ":", "]", "\n", "return", "query", ",", "nil", "\n", "}" ]
// RowsQueryEventParser's Parse processes a raw query event into a // RowsQueryEvent.
[ "RowsQueryEventParser", "s", "Parse", "processes", "a", "raw", "query", "event", "into", "a", "RowsQueryEvent", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/rows_query_event.go#L49-L62
train
dropbox/godropbox
resource_pool/simple_resource_pool.go
NewSimpleResourcePool
func NewSimpleResourcePool(options Options) ResourcePool { numActive := new(int32) atomic.StoreInt32(numActive, 0) activeHighWaterMark := new(int32) atomic.StoreInt32(activeHighWaterMark, 0) var tokens sync2.Semaphore if options.OpenMaxConcurrency > 0 { tokens = sync2.NewBoundedSemaphore(uint(options.OpenMaxConcurrency)) } return &simpleResourcePool{ location: "", options: options, numActive: numActive, activeHighWaterMark: activeHighWaterMark, openTokens: tokens, mutex: sync.Mutex{}, idleHandles: make([]*idleHandle, 0, 0), isLameDuck: false, } }
go
func NewSimpleResourcePool(options Options) ResourcePool { numActive := new(int32) atomic.StoreInt32(numActive, 0) activeHighWaterMark := new(int32) atomic.StoreInt32(activeHighWaterMark, 0) var tokens sync2.Semaphore if options.OpenMaxConcurrency > 0 { tokens = sync2.NewBoundedSemaphore(uint(options.OpenMaxConcurrency)) } return &simpleResourcePool{ location: "", options: options, numActive: numActive, activeHighWaterMark: activeHighWaterMark, openTokens: tokens, mutex: sync.Mutex{}, idleHandles: make([]*idleHandle, 0, 0), isLameDuck: false, } }
[ "func", "NewSimpleResourcePool", "(", "options", "Options", ")", "ResourcePool", "{", "numActive", ":=", "new", "(", "int32", ")", "\n", "atomic", ".", "StoreInt32", "(", "numActive", ",", "0", ")", "\n", "activeHighWaterMark", ":=", "new", "(", "int32", ")", "\n", "atomic", ".", "StoreInt32", "(", "activeHighWaterMark", ",", "0", ")", "\n", "var", "tokens", "sync2", ".", "Semaphore", "\n", "if", "options", ".", "OpenMaxConcurrency", ">", "0", "{", "tokens", "=", "sync2", ".", "NewBoundedSemaphore", "(", "uint", "(", "options", ".", "OpenMaxConcurrency", ")", ")", "\n", "}", "\n", "return", "&", "simpleResourcePool", "{", "location", ":", "\"\"", ",", "options", ":", "options", ",", "numActive", ":", "numActive", ",", "activeHighWaterMark", ":", "activeHighWaterMark", ",", "openTokens", ":", "tokens", ",", "mutex", ":", "sync", ".", "Mutex", "{", "}", ",", "idleHandles", ":", "make", "(", "[", "]", "*", "idleHandle", ",", "0", ",", "0", ")", ",", "isLameDuck", ":", "false", ",", "}", "\n", "}" ]
// This returns a SimpleResourcePool, where all handles are associated to a // single resource location.
[ "This", "returns", "a", "SimpleResourcePool", "where", "all", "handles", "are", "associated", "to", "a", "single", "resource", "location", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L54-L76
train
dropbox/godropbox
resource_pool/simple_resource_pool.go
getIdleHandle
func (p *simpleResourcePool) getIdleHandle() ManagedHandle { var toClose []*idleHandle defer func() { // NOTE: Must keep the closure around to late bind the toClose slice. p.closeHandles(toClose) }() now := p.options.getCurrentTime() p.mutex.Lock() defer p.mutex.Unlock() var i int for i = 0; i < len(p.idleHandles); i++ { idle := p.idleHandles[i] if idle.keepUntil == nil || now.Before(*idle.keepUntil) { break } } if i > 0 { toClose = p.idleHandles[0:i] } if i < len(p.idleHandles) { idle := p.idleHandles[i] p.idleHandles = p.idleHandles[i+1:] return NewManagedHandle(p.location, idle.handle, p, p.options) } if len(p.idleHandles) > 0 { p.idleHandles = []*idleHandle{} } return nil }
go
func (p *simpleResourcePool) getIdleHandle() ManagedHandle { var toClose []*idleHandle defer func() { // NOTE: Must keep the closure around to late bind the toClose slice. p.closeHandles(toClose) }() now := p.options.getCurrentTime() p.mutex.Lock() defer p.mutex.Unlock() var i int for i = 0; i < len(p.idleHandles); i++ { idle := p.idleHandles[i] if idle.keepUntil == nil || now.Before(*idle.keepUntil) { break } } if i > 0 { toClose = p.idleHandles[0:i] } if i < len(p.idleHandles) { idle := p.idleHandles[i] p.idleHandles = p.idleHandles[i+1:] return NewManagedHandle(p.location, idle.handle, p, p.options) } if len(p.idleHandles) > 0 { p.idleHandles = []*idleHandle{} } return nil }
[ "func", "(", "p", "*", "simpleResourcePool", ")", "getIdleHandle", "(", ")", "ManagedHandle", "{", "var", "toClose", "[", "]", "*", "idleHandle", "\n", "defer", "func", "(", ")", "{", "p", ".", "closeHandles", "(", "toClose", ")", "\n", "}", "(", ")", "\n", "now", ":=", "p", ".", "options", ".", "getCurrentTime", "(", ")", "\n", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n", "var", "i", "int", "\n", "for", "i", "=", "0", ";", "i", "<", "len", "(", "p", ".", "idleHandles", ")", ";", "i", "++", "{", "idle", ":=", "p", ".", "idleHandles", "[", "i", "]", "\n", "if", "idle", ".", "keepUntil", "==", "nil", "||", "now", ".", "Before", "(", "*", "idle", ".", "keepUntil", ")", "{", "break", "\n", "}", "\n", "}", "\n", "if", "i", ">", "0", "{", "toClose", "=", "p", ".", "idleHandles", "[", "0", ":", "i", "]", "\n", "}", "\n", "if", "i", "<", "len", "(", "p", ".", "idleHandles", ")", "{", "idle", ":=", "p", ".", "idleHandles", "[", "i", "]", "\n", "p", ".", "idleHandles", "=", "p", ".", "idleHandles", "[", "i", "+", "1", ":", "]", "\n", "return", "NewManagedHandle", "(", "p", ".", "location", ",", "idle", ".", "handle", ",", "p", ",", "p", ".", "options", ")", "\n", "}", "\n", "if", "len", "(", "p", ".", "idleHandles", ")", ">", "0", "{", "p", ".", "idleHandles", "=", "[", "]", "*", "idleHandle", "{", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This returns an idle resource, if there is one.
[ "This", "returns", "an", "idle", "resource", "if", "there", "is", "one", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L263-L296
train
dropbox/godropbox
resource_pool/simple_resource_pool.go
queueIdleHandles
func (p *simpleResourcePool) queueIdleHandles(handle interface{}) { var toClose []*idleHandle defer func() { // NOTE: Must keep the closure around to late bind the toClose slice. p.closeHandles(toClose) }() now := p.options.getCurrentTime() var keepUntil *time.Time if p.options.MaxIdleTime != nil { // NOTE: Assign to temp variable first to work around compiler bug x := now.Add(*p.options.MaxIdleTime) keepUntil = &x } p.mutex.Lock() defer p.mutex.Unlock() if p.isLameDuck { toClose = []*idleHandle{ {handle: handle}, } return } p.idleHandles = append( p.idleHandles, &idleHandle{ handle: handle, keepUntil: keepUntil, }) nIdleHandles := uint32(len(p.idleHandles)) if nIdleHandles > p.options.MaxIdleHandles { handlesToClose := nIdleHandles - p.options.MaxIdleHandles toClose = p.idleHandles[0:handlesToClose] p.idleHandles = p.idleHandles[handlesToClose:nIdleHandles] } }
go
func (p *simpleResourcePool) queueIdleHandles(handle interface{}) { var toClose []*idleHandle defer func() { // NOTE: Must keep the closure around to late bind the toClose slice. p.closeHandles(toClose) }() now := p.options.getCurrentTime() var keepUntil *time.Time if p.options.MaxIdleTime != nil { // NOTE: Assign to temp variable first to work around compiler bug x := now.Add(*p.options.MaxIdleTime) keepUntil = &x } p.mutex.Lock() defer p.mutex.Unlock() if p.isLameDuck { toClose = []*idleHandle{ {handle: handle}, } return } p.idleHandles = append( p.idleHandles, &idleHandle{ handle: handle, keepUntil: keepUntil, }) nIdleHandles := uint32(len(p.idleHandles)) if nIdleHandles > p.options.MaxIdleHandles { handlesToClose := nIdleHandles - p.options.MaxIdleHandles toClose = p.idleHandles[0:handlesToClose] p.idleHandles = p.idleHandles[handlesToClose:nIdleHandles] } }
[ "func", "(", "p", "*", "simpleResourcePool", ")", "queueIdleHandles", "(", "handle", "interface", "{", "}", ")", "{", "var", "toClose", "[", "]", "*", "idleHandle", "\n", "defer", "func", "(", ")", "{", "p", ".", "closeHandles", "(", "toClose", ")", "\n", "}", "(", ")", "\n", "now", ":=", "p", ".", "options", ".", "getCurrentTime", "(", ")", "\n", "var", "keepUntil", "*", "time", ".", "Time", "\n", "if", "p", ".", "options", ".", "MaxIdleTime", "!=", "nil", "{", "x", ":=", "now", ".", "Add", "(", "*", "p", ".", "options", ".", "MaxIdleTime", ")", "\n", "keepUntil", "=", "&", "x", "\n", "}", "\n", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "isLameDuck", "{", "toClose", "=", "[", "]", "*", "idleHandle", "{", "{", "handle", ":", "handle", "}", ",", "}", "\n", "return", "\n", "}", "\n", "p", ".", "idleHandles", "=", "append", "(", "p", ".", "idleHandles", ",", "&", "idleHandle", "{", "handle", ":", "handle", ",", "keepUntil", ":", "keepUntil", ",", "}", ")", "\n", "nIdleHandles", ":=", "uint32", "(", "len", "(", "p", ".", "idleHandles", ")", ")", "\n", "if", "nIdleHandles", ">", "p", ".", "options", ".", "MaxIdleHandles", "{", "handlesToClose", ":=", "nIdleHandles", "-", "p", ".", "options", ".", "MaxIdleHandles", "\n", "toClose", "=", "p", ".", "idleHandles", "[", "0", ":", "handlesToClose", "]", "\n", "p", ".", "idleHandles", "=", "p", ".", "idleHandles", "[", "handlesToClose", ":", "nIdleHandles", "]", "\n", "}", "\n", "}" ]
// This adds an idle resource to the pool.
[ "This", "adds", "an", "idle", "resource", "to", "the", "pool", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L299-L337
train
dropbox/godropbox
resource_pool/simple_resource_pool.go
closeHandles
func (p *simpleResourcePool) closeHandles(handles []*idleHandle) { for _, handle := range handles { _ = p.options.Close(handle.handle) } }
go
func (p *simpleResourcePool) closeHandles(handles []*idleHandle) { for _, handle := range handles { _ = p.options.Close(handle.handle) } }
[ "func", "(", "p", "*", "simpleResourcePool", ")", "closeHandles", "(", "handles", "[", "]", "*", "idleHandle", ")", "{", "for", "_", ",", "handle", ":=", "range", "handles", "{", "_", "=", "p", ".", "options", ".", "Close", "(", "handle", ".", "handle", ")", "\n", "}", "\n", "}" ]
// Closes resources, at this point it is assumed that this resources // are no longer referenced from the main idleHandles slice.
[ "Closes", "resources", "at", "this", "point", "it", "is", "assumed", "that", "this", "resources", "are", "no", "longer", "referenced", "from", "the", "main", "idleHandles", "slice", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L341-L345
train
dropbox/godropbox
database/sqlbuilder/table.go
NewTable
func NewTable(name string, columns ...NonAliasColumn) *Table { if !validIdentifierName(name) { panic("Invalid table name") } t := &Table{ name: name, columns: columns, columnLookup: make(map[string]NonAliasColumn), } for _, c := range columns { err := c.setTableName(name) if err != nil { panic(err) } t.columnLookup[c.Name()] = c } if len(columns) == 0 { panic(fmt.Sprintf("Table %s has no columns", name)) } return t }
go
func NewTable(name string, columns ...NonAliasColumn) *Table { if !validIdentifierName(name) { panic("Invalid table name") } t := &Table{ name: name, columns: columns, columnLookup: make(map[string]NonAliasColumn), } for _, c := range columns { err := c.setTableName(name) if err != nil { panic(err) } t.columnLookup[c.Name()] = c } if len(columns) == 0 { panic(fmt.Sprintf("Table %s has no columns", name)) } return t }
[ "func", "NewTable", "(", "name", "string", ",", "columns", "...", "NonAliasColumn", ")", "*", "Table", "{", "if", "!", "validIdentifierName", "(", "name", ")", "{", "panic", "(", "\"Invalid table name\"", ")", "\n", "}", "\n", "t", ":=", "&", "Table", "{", "name", ":", "name", ",", "columns", ":", "columns", ",", "columnLookup", ":", "make", "(", "map", "[", "string", "]", "NonAliasColumn", ")", ",", "}", "\n", "for", "_", ",", "c", ":=", "range", "columns", "{", "err", ":=", "c", ".", "setTableName", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "t", ".", "columnLookup", "[", "c", ".", "Name", "(", ")", "]", "=", "c", "\n", "}", "\n", "if", "len", "(", "columns", ")", "==", "0", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Table %s has no columns\"", ",", "name", ")", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// Defines a physical table in the database that is both readable and writable. // This function will panic if name is not valid
[ "Defines", "a", "physical", "table", "in", "the", "database", "that", "is", "both", "readable", "and", "writable", ".", "This", "function", "will", "panic", "if", "name", "is", "not", "valid" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L53-L76
train
dropbox/godropbox
database/sqlbuilder/table.go
getColumn
func (t *Table) getColumn(name string) (NonAliasColumn, error) { if c, ok := t.columnLookup[name]; ok { return c, nil } return nil, errors.Newf("No such column '%s' in table '%s'", name, t.name) }
go
func (t *Table) getColumn(name string) (NonAliasColumn, error) { if c, ok := t.columnLookup[name]; ok { return c, nil } return nil, errors.Newf("No such column '%s' in table '%s'", name, t.name) }
[ "func", "(", "t", "*", "Table", ")", "getColumn", "(", "name", "string", ")", "(", "NonAliasColumn", ",", "error", ")", "{", "if", "c", ",", "ok", ":=", "t", ".", "columnLookup", "[", "name", "]", ";", "ok", "{", "return", "c", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Newf", "(", "\"No such column '%s' in table '%s'\"", ",", "name", ",", "t", ".", "name", ")", "\n", "}" ]
// Returns the specified column, or errors if it doesn't exist in the table
[ "Returns", "the", "specified", "column", "or", "errors", "if", "it", "doesn", "t", "exist", "in", "the", "table" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L87-L92
train
dropbox/godropbox
database/sqlbuilder/table.go
C
func (t *Table) C(name string) NonAliasColumn { return &deferredLookupColumn{ table: t, colName: name, } }
go
func (t *Table) C(name string) NonAliasColumn { return &deferredLookupColumn{ table: t, colName: name, } }
[ "func", "(", "t", "*", "Table", ")", "C", "(", "name", "string", ")", "NonAliasColumn", "{", "return", "&", "deferredLookupColumn", "{", "table", ":", "t", ",", "colName", ":", "name", ",", "}", "\n", "}" ]
// Returns a pseudo column representation of the column name. Error checking // is deferred to SerializeSql.
[ "Returns", "a", "pseudo", "column", "representation", "of", "the", "column", "name", ".", "Error", "checking", "is", "deferred", "to", "SerializeSql", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L96-L101
train
dropbox/godropbox
database/sqlbuilder/table.go
Projections
func (t *Table) Projections() []Projection { result := make([]Projection, 0) for _, col := range t.columns { result = append(result, col) } return result }
go
func (t *Table) Projections() []Projection { result := make([]Projection, 0) for _, col := range t.columns { result = append(result, col) } return result }
[ "func", "(", "t", "*", "Table", ")", "Projections", "(", ")", "[", "]", "Projection", "{", "result", ":=", "make", "(", "[", "]", "Projection", ",", "0", ")", "\n", "for", "_", ",", "col", ":=", "range", "t", ".", "columns", "{", "result", "=", "append", "(", "result", ",", "col", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Returns all columns for a table as a slice of projections
[ "Returns", "all", "columns", "for", "a", "table", "as", "a", "slice", "of", "projections" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L104-L112
train
dropbox/godropbox
database/sqlbuilder/table.go
ForceIndex
func (t *Table) ForceIndex(index string) *Table { newTable := *t newTable.forcedIndex = index return &newTable }
go
func (t *Table) ForceIndex(index string) *Table { newTable := *t newTable.forcedIndex = index return &newTable }
[ "func", "(", "t", "*", "Table", ")", "ForceIndex", "(", "index", "string", ")", "*", "Table", "{", "newTable", ":=", "*", "t", "\n", "newTable", ".", "forcedIndex", "=", "index", "\n", "return", "&", "newTable", "\n", "}" ]
// Returns a copy of this table, but with the specified index forced.
[ "Returns", "a", "copy", "of", "this", "table", "but", "with", "the", "specified", "index", "forced", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L125-L129
train
dropbox/godropbox
database/sqlbuilder/table.go
InnerJoinOn
func (t *Table) InnerJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return InnerJoinOn(t, table, onCondition) }
go
func (t *Table) InnerJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return InnerJoinOn(t, table, onCondition) }
[ "func", "(", "t", "*", "Table", ")", "InnerJoinOn", "(", "table", "ReadableTable", ",", "onCondition", "BoolExpression", ")", "ReadableTable", "{", "return", "InnerJoinOn", "(", "t", ",", "table", ",", "onCondition", ")", "\n", "}" ]
// Creates a inner join table expression using onCondition.
[ "Creates", "a", "inner", "join", "table", "expression", "using", "onCondition", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L158-L163
train
dropbox/godropbox
database/sqlbuilder/table.go
LeftJoinOn
func (t *Table) LeftJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return LeftJoinOn(t, table, onCondition) }
go
func (t *Table) LeftJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return LeftJoinOn(t, table, onCondition) }
[ "func", "(", "t", "*", "Table", ")", "LeftJoinOn", "(", "table", "ReadableTable", ",", "onCondition", "BoolExpression", ")", "ReadableTable", "{", "return", "LeftJoinOn", "(", "t", ",", "table", ",", "onCondition", ")", "\n", "}" ]
// Creates a left join table expression using onCondition.
[ "Creates", "a", "left", "join", "table", "expression", "using", "onCondition", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L166-L171
train
dropbox/godropbox
database/sqlbuilder/table.go
RightJoinOn
func (t *Table) RightJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return RightJoinOn(t, table, onCondition) }
go
func (t *Table) RightJoinOn( table ReadableTable, onCondition BoolExpression) ReadableTable { return RightJoinOn(t, table, onCondition) }
[ "func", "(", "t", "*", "Table", ")", "RightJoinOn", "(", "table", "ReadableTable", ",", "onCondition", "BoolExpression", ")", "ReadableTable", "{", "return", "RightJoinOn", "(", "t", ",", "table", ",", "onCondition", ")", "\n", "}" ]
// Creates a right join table expression using onCondition.
[ "Creates", "a", "right", "join", "table", "expression", "using", "onCondition", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L174-L179
train
dropbox/godropbox
database/binlog/previous_gtid_log_event.go
Parse
func (p *PreviousGtidsLogEventParser) Parse(raw *RawV4Event) (Event, error) { pgle := &PreviousGtidsLogEvent{ Event: raw, set: make(map[string][]GtidRange), } data := raw.VariableLengthData() if len(data) < 8 { return nil, errors.Newf("Not enough bytes for n_sids: %v", data) } nSids, data := LittleEndian.Uint64(data[:8]), data[8:] for i := uint64(0); i < nSids; i++ { if len(data) < 16 { return nil, errors.Newf("Not enough bytes for sid: %v", data) } var sid string sid, data = string(data[:16]), data[16:] if len(data) < 8 { return nil, errors.Newf("Not enough bytes for n_intervals: %v", data) } var nIntervals uint64 nIntervals, data = LittleEndian.Uint64(data[:8]), data[8:] for j := uint64(0); j < nIntervals; j++ { if len(data) < 16 { return nil, errors.Newf("Not enough bytes for start/end: %v", data) } var start, end uint64 start, data = LittleEndian.Uint64(data[:8]), data[8:] end, data = LittleEndian.Uint64(data[:8]), data[8:] pgle.set[sid] = append(pgle.set[sid], GtidRange{start, end}) } } if len(data) > 0 { return nil, errors.Newf("Extra bytes at the end: %v", data) } return pgle, nil }
go
func (p *PreviousGtidsLogEventParser) Parse(raw *RawV4Event) (Event, error) { pgle := &PreviousGtidsLogEvent{ Event: raw, set: make(map[string][]GtidRange), } data := raw.VariableLengthData() if len(data) < 8 { return nil, errors.Newf("Not enough bytes for n_sids: %v", data) } nSids, data := LittleEndian.Uint64(data[:8]), data[8:] for i := uint64(0); i < nSids; i++ { if len(data) < 16 { return nil, errors.Newf("Not enough bytes for sid: %v", data) } var sid string sid, data = string(data[:16]), data[16:] if len(data) < 8 { return nil, errors.Newf("Not enough bytes for n_intervals: %v", data) } var nIntervals uint64 nIntervals, data = LittleEndian.Uint64(data[:8]), data[8:] for j := uint64(0); j < nIntervals; j++ { if len(data) < 16 { return nil, errors.Newf("Not enough bytes for start/end: %v", data) } var start, end uint64 start, data = LittleEndian.Uint64(data[:8]), data[8:] end, data = LittleEndian.Uint64(data[:8]), data[8:] pgle.set[sid] = append(pgle.set[sid], GtidRange{start, end}) } } if len(data) > 0 { return nil, errors.Newf("Extra bytes at the end: %v", data) } return pgle, nil }
[ "func", "(", "p", "*", "PreviousGtidsLogEventParser", ")", "Parse", "(", "raw", "*", "RawV4Event", ")", "(", "Event", ",", "error", ")", "{", "pgle", ":=", "&", "PreviousGtidsLogEvent", "{", "Event", ":", "raw", ",", "set", ":", "make", "(", "map", "[", "string", "]", "[", "]", "GtidRange", ")", ",", "}", "\n", "data", ":=", "raw", ".", "VariableLengthData", "(", ")", "\n", "if", "len", "(", "data", ")", "<", "8", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Not enough bytes for n_sids: %v\"", ",", "data", ")", "\n", "}", "\n", "nSids", ",", "data", ":=", "LittleEndian", ".", "Uint64", "(", "data", "[", ":", "8", "]", ")", ",", "data", "[", "8", ":", "]", "\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<", "nSids", ";", "i", "++", "{", "if", "len", "(", "data", ")", "<", "16", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Not enough bytes for sid: %v\"", ",", "data", ")", "\n", "}", "\n", "var", "sid", "string", "\n", "sid", ",", "data", "=", "string", "(", "data", "[", ":", "16", "]", ")", ",", "data", "[", "16", ":", "]", "\n", "if", "len", "(", "data", ")", "<", "8", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Not enough bytes for n_intervals: %v\"", ",", "data", ")", "\n", "}", "\n", "var", "nIntervals", "uint64", "\n", "nIntervals", ",", "data", "=", "LittleEndian", ".", "Uint64", "(", "data", "[", ":", "8", "]", ")", ",", "data", "[", "8", ":", "]", "\n", "for", "j", ":=", "uint64", "(", "0", ")", ";", "j", "<", "nIntervals", ";", "j", "++", "{", "if", "len", "(", "data", ")", "<", "16", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Not enough bytes for start/end: %v\"", ",", "data", ")", "\n", "}", "\n", "var", "start", ",", "end", "uint64", "\n", "start", ",", "data", "=", "LittleEndian", ".", "Uint64", "(", "data", "[", ":", "8", "]", ")", ",", "data", "[", "8", ":", "]", "\n", "end", ",", "data", "=", "LittleEndian", ".", "Uint64", "(", "data", "[", ":", "8", "]", ")", ",", "data", "[", "8", ":", "]", "\n", "pgle", ".", "set", "[", "sid", "]", "=", "append", "(", "pgle", ".", "set", "[", "sid", "]", ",", "GtidRange", "{", "start", ",", "end", "}", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "data", ")", ">", "0", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Extra bytes at the end: %v\"", ",", "data", ")", "\n", "}", "\n", "return", "pgle", ",", "nil", "\n", "}" ]
// PreviousGtidLogEventParser's Parse processes a raw gtid log event into a PreviousGtidLogEvent.
[ "PreviousGtidLogEventParser", "s", "Parse", "processes", "a", "raw", "gtid", "log", "event", "into", "a", "PreviousGtidLogEvent", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/previous_gtid_log_event.go#L54-L97
train
dropbox/godropbox
encoding2/hex.go
HexEncodeToWriter
func HexEncodeToWriter(w BinaryWriter, data []byte) { for _, b := range data { w.Write(hexMap[b]) } }
go
func HexEncodeToWriter(w BinaryWriter, data []byte) { for _, b := range data { w.Write(hexMap[b]) } }
[ "func", "HexEncodeToWriter", "(", "w", "BinaryWriter", ",", "data", "[", "]", "byte", ")", "{", "for", "_", ",", "b", ":=", "range", "data", "{", "w", ".", "Write", "(", "hexMap", "[", "b", "]", ")", "\n", "}", "\n", "}" ]
// This hex encodes the binary data and writes the encoded data to the writer.
[ "This", "hex", "encodes", "the", "binary", "data", "and", "writes", "the", "encoded", "data", "to", "the", "writer", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/encoding2/hex.go#L10-L14
train
dropbox/godropbox
resource_pool/round_robin_resource_pool.go
NewRoundRobinResourcePool
func NewRoundRobinResourcePool( options Options, createPool func(Options) ResourcePool, pools ...*ResourceLocationPool) (ResourcePool, error) { locations := make(map[string]bool) for _, pool := range pools { if pool.ResourceLocation == "" { return nil, errors.New("Invalid resource location") } if locations[pool.ResourceLocation] { return nil, errors.Newf( "Duplication resource location %s", pool.ResourceLocation) } locations[pool.ResourceLocation] = true if pool.Pool == nil { return nil, errors.New("Invalid pool") } } if createPool == nil { createPool = NewSimpleResourcePool } counter := new(int64) atomic.StoreInt64(counter, 0) shuffle(pools) return &roundRobinResourcePool{ options: options, createPool: createPool, rwMutex: sync.RWMutex{}, isLameDuck: false, pools: pools, counter: counter, }, nil }
go
func NewRoundRobinResourcePool( options Options, createPool func(Options) ResourcePool, pools ...*ResourceLocationPool) (ResourcePool, error) { locations := make(map[string]bool) for _, pool := range pools { if pool.ResourceLocation == "" { return nil, errors.New("Invalid resource location") } if locations[pool.ResourceLocation] { return nil, errors.Newf( "Duplication resource location %s", pool.ResourceLocation) } locations[pool.ResourceLocation] = true if pool.Pool == nil { return nil, errors.New("Invalid pool") } } if createPool == nil { createPool = NewSimpleResourcePool } counter := new(int64) atomic.StoreInt64(counter, 0) shuffle(pools) return &roundRobinResourcePool{ options: options, createPool: createPool, rwMutex: sync.RWMutex{}, isLameDuck: false, pools: pools, counter: counter, }, nil }
[ "func", "NewRoundRobinResourcePool", "(", "options", "Options", ",", "createPool", "func", "(", "Options", ")", "ResourcePool", ",", "pools", "...", "*", "ResourceLocationPool", ")", "(", "ResourcePool", ",", "error", ")", "{", "locations", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "pool", ":=", "range", "pools", "{", "if", "pool", ".", "ResourceLocation", "==", "\"\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"Invalid resource location\"", ")", "\n", "}", "\n", "if", "locations", "[", "pool", ".", "ResourceLocation", "]", "{", "return", "nil", ",", "errors", ".", "Newf", "(", "\"Duplication resource location %s\"", ",", "pool", ".", "ResourceLocation", ")", "\n", "}", "\n", "locations", "[", "pool", ".", "ResourceLocation", "]", "=", "true", "\n", "if", "pool", ".", "Pool", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"Invalid pool\"", ")", "\n", "}", "\n", "}", "\n", "if", "createPool", "==", "nil", "{", "createPool", "=", "NewSimpleResourcePool", "\n", "}", "\n", "counter", ":=", "new", "(", "int64", ")", "\n", "atomic", ".", "StoreInt64", "(", "counter", ",", "0", ")", "\n", "shuffle", "(", "pools", ")", "\n", "return", "&", "roundRobinResourcePool", "{", "options", ":", "options", ",", "createPool", ":", "createPool", ",", "rwMutex", ":", "sync", ".", "RWMutex", "{", "}", ",", "isLameDuck", ":", "false", ",", "pools", ":", "pools", ",", "counter", ":", "counter", ",", "}", ",", "nil", "\n", "}" ]
// This returns a RoundRobinResourcePool.
[ "This", "returns", "a", "RoundRobinResourcePool", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/round_robin_resource_pool.go#L38-L79
train
dropbox/godropbox
database/binlog/event.go
EventType
func (e *RawV4Event) EventType() mysql_proto.LogEventType_Type { return mysql_proto.LogEventType_Type(e.header.EventType) }
go
func (e *RawV4Event) EventType() mysql_proto.LogEventType_Type { return mysql_proto.LogEventType_Type(e.header.EventType) }
[ "func", "(", "e", "*", "RawV4Event", ")", "EventType", "(", ")", "mysql_proto", ".", "LogEventType_Type", "{", "return", "mysql_proto", ".", "LogEventType_Type", "(", "e", ".", "header", ".", "EventType", ")", "\n", "}" ]
// EventType returns the event's type.
[ "EventType", "returns", "the", "event", "s", "type", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L108-L110
train
dropbox/godropbox
database/binlog/event.go
VariableLengthData
func (e *RawV4Event) VariableLengthData() []byte { begin := (sizeOfBasicV4EventHeader + e.extraHeadersSize + e.fixedLengthDataSize) end := len(e.data) - e.checksumSize return e.data[begin:end] }
go
func (e *RawV4Event) VariableLengthData() []byte { begin := (sizeOfBasicV4EventHeader + e.extraHeadersSize + e.fixedLengthDataSize) end := len(e.data) - e.checksumSize return e.data[begin:end] }
[ "func", "(", "e", "*", "RawV4Event", ")", "VariableLengthData", "(", ")", "[", "]", "byte", "{", "begin", ":=", "(", "sizeOfBasicV4EventHeader", "+", "e", ".", "extraHeadersSize", "+", "e", ".", "fixedLengthDataSize", ")", "\n", "end", ":=", "len", "(", "e", ".", "data", ")", "-", "e", ".", "checksumSize", "\n", "return", "e", ".", "data", "[", "begin", ":", "end", "]", "\n", "}" ]
// VariableLengthData returns the variable length data associated to the event. // By default, the variable length data also include the extra headers, the // fixed length data and the optional checksum footer.
[ "VariableLengthData", "returns", "the", "variable", "length", "data", "associated", "to", "the", "event", ".", "By", "default", "the", "variable", "length", "data", "also", "include", "the", "extra", "headers", "the", "fixed", "length", "data", "and", "the", "optional", "checksum", "footer", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L167-L173
train
dropbox/godropbox
database/binlog/event.go
SetExtraHeadersSize
func (e *RawV4Event) SetExtraHeadersSize(size int) error { newFixedSize := (size + sizeOfBasicV4EventHeader + e.fixedLengthDataSize + e.checksumSize) if size < 0 || newFixedSize > len(e.data) { return errors.Newf( "Invalid extra headers size (data size: %d basic header size: %d"+ "fixed length data size: %d checksum size: %d input: %d)", len(e.data), sizeOfBasicV4EventHeader, e.fixedLengthDataSize, e.checksumSize, size) } e.extraHeadersSize = size return nil }
go
func (e *RawV4Event) SetExtraHeadersSize(size int) error { newFixedSize := (size + sizeOfBasicV4EventHeader + e.fixedLengthDataSize + e.checksumSize) if size < 0 || newFixedSize > len(e.data) { return errors.Newf( "Invalid extra headers size (data size: %d basic header size: %d"+ "fixed length data size: %d checksum size: %d input: %d)", len(e.data), sizeOfBasicV4EventHeader, e.fixedLengthDataSize, e.checksumSize, size) } e.extraHeadersSize = size return nil }
[ "func", "(", "e", "*", "RawV4Event", ")", "SetExtraHeadersSize", "(", "size", "int", ")", "error", "{", "newFixedSize", ":=", "(", "size", "+", "sizeOfBasicV4EventHeader", "+", "e", ".", "fixedLengthDataSize", "+", "e", ".", "checksumSize", ")", "\n", "if", "size", "<", "0", "||", "newFixedSize", ">", "len", "(", "e", ".", "data", ")", "{", "return", "errors", ".", "Newf", "(", "\"Invalid extra headers size (data size: %d basic header size: %d\"", "+", "\"fixed length data size: %d checksum size: %d input: %d)\"", ",", "len", "(", "e", ".", "data", ")", ",", "sizeOfBasicV4EventHeader", ",", "e", ".", "fixedLengthDataSize", ",", "e", ".", "checksumSize", ",", "size", ")", "\n", "}", "\n", "e", ".", "extraHeadersSize", "=", "size", "\n", "return", "nil", "\n", "}" ]
// Set the extra headers' size.
[ "Set", "the", "extra", "headers", "size", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L183-L200
train
dropbox/godropbox
caching/cache_on_storage.go
NewCacheOnStorage
func NewCacheOnStorage( cache Storage, storage Storage) Storage { return &CacheOnStorage{ cache: cache, storage: storage, } }
go
func NewCacheOnStorage( cache Storage, storage Storage) Storage { return &CacheOnStorage{ cache: cache, storage: storage, } }
[ "func", "NewCacheOnStorage", "(", "cache", "Storage", ",", "storage", "Storage", ")", "Storage", "{", "return", "&", "CacheOnStorage", "{", "cache", ":", "cache", ",", "storage", ":", "storage", ",", "}", "\n", "}" ]
// This returns a CacheOnStorage, which adds a cache layer on top of the // storage.
[ "This", "returns", "a", "CacheOnStorage", "which", "adds", "a", "cache", "layer", "on", "top", "of", "the", "storage", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/caching/cache_on_storage.go#L17-L25
train
dropbox/godropbox
cinterop/maximally_batched_work.go
readUntilNullWorkSizeBatch
func readUntilNullWorkSizeBatch(socketRead io.ReadCloser, batch []byte, workSize int) (size int, err error) { err = nil size = 0 if workSize == 0 { size, err = io.ReadFull(socketRead, batch) } else { lastCheckedForNull := 0 for err == nil { var offset int offset, err = socketRead.Read(batch[size:]) size += offset if err == nil && size < len(batch) { endCheck := size - (size % workSize) if zeroWorkItem(batch[lastCheckedForNull:endCheck], workSize) { if size%workSize != 0 { rem := workSize - (size % workSize) offset, err = io.ReadFull(socketRead, batch[size:size+rem]) size += offset } return } lastCheckedForNull = endCheck // need to check partial work items } else { return } } } return }
go
func readUntilNullWorkSizeBatch(socketRead io.ReadCloser, batch []byte, workSize int) (size int, err error) { err = nil size = 0 if workSize == 0 { size, err = io.ReadFull(socketRead, batch) } else { lastCheckedForNull := 0 for err == nil { var offset int offset, err = socketRead.Read(batch[size:]) size += offset if err == nil && size < len(batch) { endCheck := size - (size % workSize) if zeroWorkItem(batch[lastCheckedForNull:endCheck], workSize) { if size%workSize != 0 { rem := workSize - (size % workSize) offset, err = io.ReadFull(socketRead, batch[size:size+rem]) size += offset } return } lastCheckedForNull = endCheck // need to check partial work items } else { return } } } return }
[ "func", "readUntilNullWorkSizeBatch", "(", "socketRead", "io", ".", "ReadCloser", ",", "batch", "[", "]", "byte", ",", "workSize", "int", ")", "(", "size", "int", ",", "err", "error", ")", "{", "err", "=", "nil", "\n", "size", "=", "0", "\n", "if", "workSize", "==", "0", "{", "size", ",", "err", "=", "io", ".", "ReadFull", "(", "socketRead", ",", "batch", ")", "\n", "}", "else", "{", "lastCheckedForNull", ":=", "0", "\n", "for", "err", "==", "nil", "{", "var", "offset", "int", "\n", "offset", ",", "err", "=", "socketRead", ".", "Read", "(", "batch", "[", "size", ":", "]", ")", "\n", "size", "+=", "offset", "\n", "if", "err", "==", "nil", "&&", "size", "<", "len", "(", "batch", ")", "{", "endCheck", ":=", "size", "-", "(", "size", "%", "workSize", ")", "\n", "if", "zeroWorkItem", "(", "batch", "[", "lastCheckedForNull", ":", "endCheck", "]", ",", "workSize", ")", "{", "if", "size", "%", "workSize", "!=", "0", "{", "rem", ":=", "workSize", "-", "(", "size", "%", "workSize", ")", "\n", "offset", ",", "err", "=", "io", ".", "ReadFull", "(", "socketRead", ",", "batch", "[", "size", ":", "size", "+", "rem", "]", ")", "\n", "size", "+=", "offset", "\n", "}", "\n", "return", "\n", "}", "\n", "lastCheckedForNull", "=", "endCheck", "\n", "}", "else", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// this reads socketRead to fill up the given buffer unless an error is encountered or // workSize zeros in a row are discovered, aligned with WorkSize, causing a flush
[ "this", "reads", "socketRead", "to", "fill", "up", "the", "given", "buffer", "unless", "an", "error", "is", "encountered", "or", "workSize", "zeros", "in", "a", "row", "are", "discovered", "aligned", "with", "WorkSize", "causing", "a", "flush" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/maximally_batched_work.go#L30-L59
train
dropbox/godropbox
cinterop/maximally_batched_work.go
readBatch
func readBatch(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int) { defer close(copyTo) for { batch := make([]byte, batchSize) size, err := readUntilNullWorkSizeBatch(socketRead, batch, workSize) if size > 0 { if err != nil && workSize != 0 { size -= (size % workSize) } copyTo <- batch[:size] } if err != nil { if err != io.EOF { log.Print("Error encountered in readBatch:", err) } return } } }
go
func readBatch(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int) { defer close(copyTo) for { batch := make([]byte, batchSize) size, err := readUntilNullWorkSizeBatch(socketRead, batch, workSize) if size > 0 { if err != nil && workSize != 0 { size -= (size % workSize) } copyTo <- batch[:size] } if err != nil { if err != io.EOF { log.Print("Error encountered in readBatch:", err) } return } } }
[ "func", "readBatch", "(", "copyTo", "chan", "<-", "[", "]", "byte", ",", "socketRead", "io", ".", "ReadCloser", ",", "batchSize", "int", ",", "workSize", "int", ")", "{", "defer", "close", "(", "copyTo", ")", "\n", "for", "{", "batch", ":=", "make", "(", "[", "]", "byte", ",", "batchSize", ")", "\n", "size", ",", "err", ":=", "readUntilNullWorkSizeBatch", "(", "socketRead", ",", "batch", ",", "workSize", ")", "\n", "if", "size", ">", "0", "{", "if", "err", "!=", "nil", "&&", "workSize", "!=", "0", "{", "size", "-=", "(", "size", "%", "workSize", ")", "\n", "}", "\n", "copyTo", "<-", "batch", "[", ":", "size", "]", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "log", ".", "Print", "(", "\"Error encountered in readBatch:\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// this reads in a loop from socketRead putting batchSize bytes of work to copyTo until // the socketRead is empty. // Batches may be shorter than batchSize if a whole workSize element is all zeros // If workSize of zero is passed in, then the entire batchSize will be filled up regardless, // unless socketRead returns an error when Read
[ "this", "reads", "in", "a", "loop", "from", "socketRead", "putting", "batchSize", "bytes", "of", "work", "to", "copyTo", "until", "the", "socketRead", "is", "empty", ".", "Batches", "may", "be", "shorter", "than", "batchSize", "if", "a", "whole", "workSize", "element", "is", "all", "zeros", "If", "workSize", "of", "zero", "is", "passed", "in", "then", "the", "entire", "batchSize", "will", "be", "filled", "up", "regardless", "unless", "socketRead", "returns", "an", "error", "when", "Read" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/maximally_batched_work.go#L66-L84
train
dropbox/godropbox
time2/mock_clock.go
Advance
func (c *MockClock) Advance(delta time.Duration) { c.mutex.Lock() defer c.mutex.Unlock() end := c.now.Add(delta) c.advanceTo(end) }
go
func (c *MockClock) Advance(delta time.Duration) { c.mutex.Lock() defer c.mutex.Unlock() end := c.now.Add(delta) c.advanceTo(end) }
[ "func", "(", "c", "*", "MockClock", ")", "Advance", "(", "delta", "time", ".", "Duration", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "end", ":=", "c", ".", "now", ".", "Add", "(", "delta", ")", "\n", "c", ".", "advanceTo", "(", "end", ")", "\n", "}" ]
// Advances the mock clock by the specified duration.
[ "Advances", "the", "mock", "clock", "by", "the", "specified", "duration", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L65-L71
train
dropbox/godropbox
time2/mock_clock.go
AdvanceTo
func (c *MockClock) AdvanceTo(t time.Time) { c.mutex.Lock() defer c.mutex.Unlock() c.advanceTo(t) }
go
func (c *MockClock) AdvanceTo(t time.Time) { c.mutex.Lock() defer c.mutex.Unlock() c.advanceTo(t) }
[ "func", "(", "c", "*", "MockClock", ")", "AdvanceTo", "(", "t", "time", ".", "Time", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "c", ".", "advanceTo", "(", "t", ")", "\n", "}" ]
// Advance to a specific time.
[ "Advance", "to", "a", "specific", "time", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L74-L79
train
dropbox/godropbox
time2/mock_clock.go
Now
func (c *MockClock) Now() time.Time { c.mutex.Lock() defer c.mutex.Unlock() return c.now }
go
func (c *MockClock) Now() time.Time { c.mutex.Lock() defer c.mutex.Unlock() return c.now }
[ "func", "(", "c", "*", "MockClock", ")", "Now", "(", ")", "time", ".", "Time", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "now", "\n", "}" ]
// Returns the fake current time.
[ "Returns", "the", "fake", "current", "time", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L89-L94
train
dropbox/godropbox
net2/http2/simple_pool.go
Do
func (pool *SimplePool) Do(req *http.Request) (resp *http.Response, err error) { conn, err := pool.Get() if err != nil { return nil, errors.Wrap(err, err.Error()) } if pool.params.UseSSL { req.URL.Scheme = "https" } else { req.URL.Scheme = "http" } if pool.params.UseRequestHost && req.Host != "" { req.URL.Host = req.Host } else { if pool.params.HostHeader != nil { req.URL.Host = *pool.params.HostHeader } else { req.URL.Host = pool.addr } } if pool.connsLimiter != nil { now := time.Now() acquired := pool.connsLimiter.TryAcquire(pool.params.ConnectionAcquireTimeout) acquiredMs := time.Now().Sub(now).Seconds() * 1000 pool.connAcquireMsSummary.Observe(acquiredMs) if acquired { pool.acquiredConnsGauge.Inc() defer func() { pool.acquiredConnsGauge.Dec() pool.connsLimiter.Release() }() } else { return nil, DialError{errors.New( "Dial Error: Reached maximum active requests for connection pool")} } } resp, err = conn.Do(req) if err != nil { if _, ok := err.(DialError); ok { // do nothing. err is already wrapped. } else if urlErr, ok := err.(*url.Error); ok { if urlErr.Err == errFollowRedirectDisabled { // This is not an actual error return resp, nil } if _, ok := urlErr.Err.(DialError); ok { err = urlErr.Err } else { err = errors.Wrap(err, err.Error()) } } else { err = errors.Wrap(err, err.Error()) } } return }
go
func (pool *SimplePool) Do(req *http.Request) (resp *http.Response, err error) { conn, err := pool.Get() if err != nil { return nil, errors.Wrap(err, err.Error()) } if pool.params.UseSSL { req.URL.Scheme = "https" } else { req.URL.Scheme = "http" } if pool.params.UseRequestHost && req.Host != "" { req.URL.Host = req.Host } else { if pool.params.HostHeader != nil { req.URL.Host = *pool.params.HostHeader } else { req.URL.Host = pool.addr } } if pool.connsLimiter != nil { now := time.Now() acquired := pool.connsLimiter.TryAcquire(pool.params.ConnectionAcquireTimeout) acquiredMs := time.Now().Sub(now).Seconds() * 1000 pool.connAcquireMsSummary.Observe(acquiredMs) if acquired { pool.acquiredConnsGauge.Inc() defer func() { pool.acquiredConnsGauge.Dec() pool.connsLimiter.Release() }() } else { return nil, DialError{errors.New( "Dial Error: Reached maximum active requests for connection pool")} } } resp, err = conn.Do(req) if err != nil { if _, ok := err.(DialError); ok { // do nothing. err is already wrapped. } else if urlErr, ok := err.(*url.Error); ok { if urlErr.Err == errFollowRedirectDisabled { // This is not an actual error return resp, nil } if _, ok := urlErr.Err.(DialError); ok { err = urlErr.Err } else { err = errors.Wrap(err, err.Error()) } } else { err = errors.Wrap(err, err.Error()) } } return }
[ "func", "(", "pool", "*", "SimplePool", ")", "Do", "(", "req", "*", "http", ".", "Request", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "conn", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "pool", ".", "params", ".", "UseSSL", "{", "req", ".", "URL", ".", "Scheme", "=", "\"https\"", "\n", "}", "else", "{", "req", ".", "URL", ".", "Scheme", "=", "\"http\"", "\n", "}", "\n", "if", "pool", ".", "params", ".", "UseRequestHost", "&&", "req", ".", "Host", "!=", "\"\"", "{", "req", ".", "URL", ".", "Host", "=", "req", ".", "Host", "\n", "}", "else", "{", "if", "pool", ".", "params", ".", "HostHeader", "!=", "nil", "{", "req", ".", "URL", ".", "Host", "=", "*", "pool", ".", "params", ".", "HostHeader", "\n", "}", "else", "{", "req", ".", "URL", ".", "Host", "=", "pool", ".", "addr", "\n", "}", "\n", "}", "\n", "if", "pool", ".", "connsLimiter", "!=", "nil", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "acquired", ":=", "pool", ".", "connsLimiter", ".", "TryAcquire", "(", "pool", ".", "params", ".", "ConnectionAcquireTimeout", ")", "\n", "acquiredMs", ":=", "time", ".", "Now", "(", ")", ".", "Sub", "(", "now", ")", ".", "Seconds", "(", ")", "*", "1000", "\n", "pool", ".", "connAcquireMsSummary", ".", "Observe", "(", "acquiredMs", ")", "\n", "if", "acquired", "{", "pool", ".", "acquiredConnsGauge", ".", "Inc", "(", ")", "\n", "defer", "func", "(", ")", "{", "pool", ".", "acquiredConnsGauge", ".", "Dec", "(", ")", "\n", "pool", ".", "connsLimiter", ".", "Release", "(", ")", "\n", "}", "(", ")", "\n", "}", "else", "{", "return", "nil", ",", "DialError", "{", "errors", ".", "New", "(", "\"Dial Error: Reached maximum active requests for connection pool\"", ")", "}", "\n", "}", "\n", "}", "\n", "resp", ",", "err", "=", "conn", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "DialError", ")", ";", "ok", "{", "}", "else", "if", "urlErr", ",", "ok", ":=", "err", ".", "(", "*", "url", ".", "Error", ")", ";", "ok", "{", "if", "urlErr", ".", "Err", "==", "errFollowRedirectDisabled", "{", "return", "resp", ",", "nil", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "urlErr", ".", "Err", ".", "(", "DialError", ")", ";", "ok", "{", "err", "=", "urlErr", ".", "Err", "\n", "}", "else", "{", "err", "=", "errors", ".", "Wrap", "(", "err", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "err", "=", "errors", ".", "Wrap", "(", "err", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Performs the HTTP request using our HTTP client
[ "Performs", "the", "HTTP", "request", "using", "our", "HTTP", "client" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L163-L221
train
dropbox/godropbox
net2/http2/simple_pool.go
DoWithTimeout
func (pool *SimplePool) DoWithTimeout(req *http.Request, timeout time.Duration) (resp *http.Response, err error) { return pool.DoWithParams(req, DoParams{Timeout: timeout}) }
go
func (pool *SimplePool) DoWithTimeout(req *http.Request, timeout time.Duration) (resp *http.Response, err error) { return pool.DoWithParams(req, DoParams{Timeout: timeout}) }
[ "func", "(", "pool", "*", "SimplePool", ")", "DoWithTimeout", "(", "req", "*", "http", ".", "Request", ",", "timeout", "time", ".", "Duration", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "pool", ".", "DoWithParams", "(", "req", ",", "DoParams", "{", "Timeout", ":", "timeout", "}", ")", "\n", "}" ]
// Set a local timeout the actually cancels the request if we've given up.
[ "Set", "a", "local", "timeout", "the", "actually", "cancels", "the", "request", "if", "we", "ve", "given", "up", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L241-L244
train
dropbox/godropbox
net2/http2/simple_pool.go
GetWithKey
func (pool *SimplePool) GetWithKey(key []byte, limit int) (*http.Client, error) { return pool.Get() }
go
func (pool *SimplePool) GetWithKey(key []byte, limit int) (*http.Client, error) { return pool.Get() }
[ "func", "(", "pool", "*", "SimplePool", ")", "GetWithKey", "(", "key", "[", "]", "byte", ",", "limit", "int", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "return", "pool", ".", "Get", "(", ")", "\n", "}" ]
// SimplePool doesn't care about the key
[ "SimplePool", "doesn", "t", "care", "about", "the", "key" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L256-L258
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
SetActiveSetSize
func (pool *LoadBalancedPool) SetActiveSetSize(size uint64) { pool.lock.Lock() defer pool.lock.Unlock() pool.activeSetSize = size }
go
func (pool *LoadBalancedPool) SetActiveSetSize(size uint64) { pool.lock.Lock() defer pool.lock.Unlock() pool.activeSetSize = size }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "SetActiveSetSize", "(", "size", "uint64", ")", "{", "pool", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "lock", ".", "Unlock", "(", ")", "\n", "pool", ".", "activeSetSize", "=", "size", "\n", "}" ]
// For the round robin strategy, sets the number of servers to round-robin // between. The default is 6.
[ "For", "the", "round", "robin", "strategy", "sets", "the", "number", "of", "servers", "to", "round", "-", "robin", "between", ".", "The", "default", "is", "6", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L137-L141
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
Do
func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error) { return pool.DoWithTimeout(req, 0) }
go
func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error) { return pool.DoWithTimeout(req, 0) }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "Do", "(", "req", "*", "http", ".", "Request", ")", "(", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "return", "pool", ".", "DoWithTimeout", "(", "req", ",", "0", ")", "\n", "}" ]
// // Pool interface methods //
[ "Pool", "interface", "methods" ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L223-L225
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
DoWithTimeout
func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request, timeout time.Duration) (*http.Response, error) { return pool.DoWithParams(req, DoParams{Timeout: timeout}) }
go
func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request, timeout time.Duration) (*http.Response, error) { return pool.DoWithParams(req, DoParams{Timeout: timeout}) }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "DoWithTimeout", "(", "req", "*", "http", ".", "Request", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "pool", ".", "DoWithParams", "(", "req", ",", "DoParams", "{", "Timeout", ":", "timeout", "}", ")", "\n", "}" ]
// Issues an HTTP request, distributing more load to relatively unloaded instances.
[ "Issues", "an", "HTTP", "request", "distributing", "more", "load", "to", "relatively", "unloaded", "instances", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L288-L291
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
getInstance
func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) ( idx int, instance *instancePool, isDown bool, err error) { pool.lock.RLock() defer pool.lock.RUnlock() if len(pool.instanceList) == 0 { return 0, nil, false, errors.Newf("no available instances") } now := time.Now().Unix() numInstancesToTry := uint64(len(pool.instanceList)) start := 0 // map used to implement soft swapping to avoid picking the same instance multiple times // when we randomly pick instances for consistent-hashing. We could have used this actually // for the other strategies. // TODO(bashar): get rid of the random shuffle for the other strategies var idxMap map[int]int if pool.strategy == LBRoundRobin && pool.activeSetSize < numInstancesToTry { numInstancesToTry = pool.activeSetSize } else if pool.strategy == LBConsistentHashing { // we must have a key if len(key) == 0 { return 0, nil, false, errors.Newf("key was not specified for consistent-hashing") } else if maxInstances <= 0 { return 0, nil, false, errors.Newf( "invalid maxInstances for consistent-hashing: %v", maxInstances) } // in case we're asked to try more than the number of servers we have if maxInstances > int(numInstancesToTry) { maxInstances = int(numInstancesToTry) } // let's find the closest server to start. We don't start from 0 in that case hash := pool.hashFunction(key, pool.hashSeed) // we need to find the closest server that hashes to >= hash. start = sort.Search(len(pool.instanceList), func(i int) bool { return pool.instanceHashes[i] >= hash }) // In the case where hash > all elements, sort.Search returns len(pool.instanceList). // Hence, we mod the result start = start % len(pool.instanceHashes) idxMap = make(map[int]int) } for i := 0; uint64(i) < numInstancesToTry; i++ { switch pool.strategy { case LBRoundRobin: // In RoundRobin strategy instanceIdx keeps changing, to // achieve round robin load balancing. instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1) idx = int(instanceIdx % numInstancesToTry) case LBSortedFixed: // In SortedFixed strategy instances are always traversed in same // exact order. idx = i case LBShuffledFixed: // In ShuffledFixed strategy instances are also always traversed in // same exact order. idx = i case LBConsistentHashing: // In ConsistentHashing strategy instances are picked up randomly between // start and start + numInstancesToTry. This is to load balance between // the alive servers that are closest to the key in the hash space // consistent-hashing will prefer availability over consistency. In the case some // server is down, we will try new servers in the hash-ring. The way we do this is by // picking random instances next (excluding already picked instances). That's why we // do a 'soft-swap' between already picked instance and move the start offset by 1 // every time. We don't touch the pool.instanceList to make sure we don't // screw up any order. The swap below guarantees that start always has an idx that // has never been tried before. newStart := i + start idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList) // we need to swap idxMap[newStart] with idxMap[idx] (or fill them). var ok bool if idxMap[idx], ok = idxMap[idx]; ok { idxMap[newStart] = idxMap[idx] } else { idxMap[newStart] = idx } idxMap[idx] = newStart // we need to pick the correct idx after the swap idx = idxMap[newStart] } if pool.markDownUntil[idx] < now { break } } return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil }
go
func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) ( idx int, instance *instancePool, isDown bool, err error) { pool.lock.RLock() defer pool.lock.RUnlock() if len(pool.instanceList) == 0 { return 0, nil, false, errors.Newf("no available instances") } now := time.Now().Unix() numInstancesToTry := uint64(len(pool.instanceList)) start := 0 // map used to implement soft swapping to avoid picking the same instance multiple times // when we randomly pick instances for consistent-hashing. We could have used this actually // for the other strategies. // TODO(bashar): get rid of the random shuffle for the other strategies var idxMap map[int]int if pool.strategy == LBRoundRobin && pool.activeSetSize < numInstancesToTry { numInstancesToTry = pool.activeSetSize } else if pool.strategy == LBConsistentHashing { // we must have a key if len(key) == 0 { return 0, nil, false, errors.Newf("key was not specified for consistent-hashing") } else if maxInstances <= 0 { return 0, nil, false, errors.Newf( "invalid maxInstances for consistent-hashing: %v", maxInstances) } // in case we're asked to try more than the number of servers we have if maxInstances > int(numInstancesToTry) { maxInstances = int(numInstancesToTry) } // let's find the closest server to start. We don't start from 0 in that case hash := pool.hashFunction(key, pool.hashSeed) // we need to find the closest server that hashes to >= hash. start = sort.Search(len(pool.instanceList), func(i int) bool { return pool.instanceHashes[i] >= hash }) // In the case where hash > all elements, sort.Search returns len(pool.instanceList). // Hence, we mod the result start = start % len(pool.instanceHashes) idxMap = make(map[int]int) } for i := 0; uint64(i) < numInstancesToTry; i++ { switch pool.strategy { case LBRoundRobin: // In RoundRobin strategy instanceIdx keeps changing, to // achieve round robin load balancing. instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1) idx = int(instanceIdx % numInstancesToTry) case LBSortedFixed: // In SortedFixed strategy instances are always traversed in same // exact order. idx = i case LBShuffledFixed: // In ShuffledFixed strategy instances are also always traversed in // same exact order. idx = i case LBConsistentHashing: // In ConsistentHashing strategy instances are picked up randomly between // start and start + numInstancesToTry. This is to load balance between // the alive servers that are closest to the key in the hash space // consistent-hashing will prefer availability over consistency. In the case some // server is down, we will try new servers in the hash-ring. The way we do this is by // picking random instances next (excluding already picked instances). That's why we // do a 'soft-swap' between already picked instance and move the start offset by 1 // every time. We don't touch the pool.instanceList to make sure we don't // screw up any order. The swap below guarantees that start always has an idx that // has never been tried before. newStart := i + start idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList) // we need to swap idxMap[newStart] with idxMap[idx] (or fill them). var ok bool if idxMap[idx], ok = idxMap[idx]; ok { idxMap[newStart] = idxMap[idx] } else { idxMap[newStart] = idx } idxMap[idx] = newStart // we need to pick the correct idx after the swap idx = idxMap[newStart] } if pool.markDownUntil[idx] < now { break } } return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "getInstance", "(", "key", "[", "]", "byte", ",", "maxInstances", "int", ")", "(", "idx", "int", ",", "instance", "*", "instancePool", ",", "isDown", "bool", ",", "err", "error", ")", "{", "pool", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "pool", ".", "lock", ".", "RUnlock", "(", ")", "\n", "if", "len", "(", "pool", ".", "instanceList", ")", "==", "0", "{", "return", "0", ",", "nil", ",", "false", ",", "errors", ".", "Newf", "(", "\"no available instances\"", ")", "\n", "}", "\n", "now", ":=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "numInstancesToTry", ":=", "uint64", "(", "len", "(", "pool", ".", "instanceList", ")", ")", "\n", "start", ":=", "0", "\n", "var", "idxMap", "map", "[", "int", "]", "int", "\n", "if", "pool", ".", "strategy", "==", "LBRoundRobin", "&&", "pool", ".", "activeSetSize", "<", "numInstancesToTry", "{", "numInstancesToTry", "=", "pool", ".", "activeSetSize", "\n", "}", "else", "if", "pool", ".", "strategy", "==", "LBConsistentHashing", "{", "if", "len", "(", "key", ")", "==", "0", "{", "return", "0", ",", "nil", ",", "false", ",", "errors", ".", "Newf", "(", "\"key was not specified for consistent-hashing\"", ")", "\n", "}", "else", "if", "maxInstances", "<=", "0", "{", "return", "0", ",", "nil", ",", "false", ",", "errors", ".", "Newf", "(", "\"invalid maxInstances for consistent-hashing: %v\"", ",", "maxInstances", ")", "\n", "}", "\n", "if", "maxInstances", ">", "int", "(", "numInstancesToTry", ")", "{", "maxInstances", "=", "int", "(", "numInstancesToTry", ")", "\n", "}", "\n", "hash", ":=", "pool", ".", "hashFunction", "(", "key", ",", "pool", ".", "hashSeed", ")", "\n", "start", "=", "sort", ".", "Search", "(", "len", "(", "pool", ".", "instanceList", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", "pool", ".", "instanceHashes", "[", "i", "]", ">=", "hash", "\n", "}", ")", "\n", "start", "=", "start", "%", "len", "(", "pool", ".", "instanceHashes", ")", "\n", "idxMap", "=", "make", "(", "map", "[", "int", "]", "int", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "uint64", "(", "i", ")", "<", "numInstancesToTry", ";", "i", "++", "{", "switch", "pool", ".", "strategy", "{", "case", "LBRoundRobin", ":", "instanceIdx", ":=", "atomic", ".", "AddUint64", "(", "&", "pool", ".", "instanceIdx", ",", "1", ")", "\n", "idx", "=", "int", "(", "instanceIdx", "%", "numInstancesToTry", ")", "\n", "case", "LBSortedFixed", ":", "idx", "=", "i", "\n", "case", "LBShuffledFixed", ":", "idx", "=", "i", "\n", "case", "LBConsistentHashing", ":", "newStart", ":=", "i", "+", "start", "\n", "idx", "=", "(", "newStart", "+", "rand2", ".", "Intn", "(", "maxInstances", ")", ")", "%", "len", "(", "pool", ".", "instanceList", ")", "\n", "var", "ok", "bool", "\n", "if", "idxMap", "[", "idx", "]", ",", "ok", "=", "idxMap", "[", "idx", "]", ";", "ok", "{", "idxMap", "[", "newStart", "]", "=", "idxMap", "[", "idx", "]", "\n", "}", "else", "{", "idxMap", "[", "newStart", "]", "=", "idx", "\n", "}", "\n", "idxMap", "[", "idx", "]", "=", "newStart", "\n", "idx", "=", "idxMap", "[", "newStart", "]", "\n", "}", "\n", "if", "pool", ".", "markDownUntil", "[", "idx", "]", "<", "now", "{", "break", "\n", "}", "\n", "}", "\n", "return", "idx", ",", "pool", ".", "instanceList", "[", "idx", "]", ",", "(", "pool", ".", "markDownUntil", "[", "idx", "]", ">=", "now", ")", ",", "nil", "\n", "}" ]
// Returns instance that isn't marked down, if all instances are // marked as down it will just choose a next one.
[ "Returns", "instance", "that", "isn", "t", "marked", "down", "if", "all", "instances", "are", "marked", "as", "down", "it", "will", "just", "choose", "a", "next", "one", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L312-L412
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
GetSingleInstance
func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error) { _, instance, _, err := pool.getInstance(nil, 1) return instance, err }
go
func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error) { _, instance, _, err := pool.getInstance(nil, 1) return instance, err }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "GetSingleInstance", "(", ")", "(", "Pool", ",", "error", ")", "{", "_", ",", "instance", ",", "_", ",", "err", ":=", "pool", ".", "getInstance", "(", "nil", ",", "1", ")", "\n", "return", "instance", ",", "err", "\n", "}" ]
// Returns a Pool for an instance selected based on load balancing strategy.
[ "Returns", "a", "Pool", "for", "an", "instance", "selected", "based", "on", "load", "balancing", "strategy", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L415-L418
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
markInstanceDown
func (pool *LoadBalancedPool) markInstanceDown( idx int, instance *instancePool, downUntil int64) { pool.lock.Lock() defer pool.lock.Unlock() if idx < len(pool.instanceList) && pool.instanceList[idx] == instance { pool.markDownUntil[idx] = downUntil } }
go
func (pool *LoadBalancedPool) markInstanceDown( idx int, instance *instancePool, downUntil int64) { pool.lock.Lock() defer pool.lock.Unlock() if idx < len(pool.instanceList) && pool.instanceList[idx] == instance { pool.markDownUntil[idx] = downUntil } }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "markInstanceDown", "(", "idx", "int", ",", "instance", "*", "instancePool", ",", "downUntil", "int64", ")", "{", "pool", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "idx", "<", "len", "(", "pool", ".", "instanceList", ")", "&&", "pool", ".", "instanceList", "[", "idx", "]", "==", "instance", "{", "pool", ".", "markDownUntil", "[", "idx", "]", "=", "downUntil", "\n", "}", "\n", "}" ]
// Marks instance down till downUntil epoch in seconds.
[ "Marks", "instance", "down", "till", "downUntil", "epoch", "in", "seconds", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L441-L448
train
dropbox/godropbox
net2/http2/load_balanced_pool.go
markInstanceUp
func (pool *LoadBalancedPool) markInstanceUp( idx int, instance *instancePool) { pool.markInstanceDown(idx, instance, 0) }
go
func (pool *LoadBalancedPool) markInstanceUp( idx int, instance *instancePool) { pool.markInstanceDown(idx, instance, 0) }
[ "func", "(", "pool", "*", "LoadBalancedPool", ")", "markInstanceUp", "(", "idx", "int", ",", "instance", "*", "instancePool", ")", "{", "pool", ".", "markInstanceDown", "(", "idx", ",", "instance", ",", "0", ")", "\n", "}" ]
// Marks instance as ready to be used.
[ "Marks", "instance", "as", "ready", "to", "be", "used", "." ]
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L451-L454
train