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
weaveworks/mesh
protocol_crypto.go
Receive
func (receiver *lengthPrefixTCPReceiver) Receive() ([]byte, error) { lenPrefix := make([]byte, 4) if _, err := io.ReadFull(receiver.reader, lenPrefix); err != nil { return nil, err } l := binary.BigEndian.Uint32(lenPrefix) if l > maxTCPMsgSize { return nil, fmt.Errorf("incoming message exceeds maximum size: %d > %d", l, maxTCPMsgSize) } msg := make([]byte, l) _, err := io.ReadFull(receiver.reader, msg) return msg, err }
go
func (receiver *lengthPrefixTCPReceiver) Receive() ([]byte, error) { lenPrefix := make([]byte, 4) if _, err := io.ReadFull(receiver.reader, lenPrefix); err != nil { return nil, err } l := binary.BigEndian.Uint32(lenPrefix) if l > maxTCPMsgSize { return nil, fmt.Errorf("incoming message exceeds maximum size: %d > %d", l, maxTCPMsgSize) } msg := make([]byte, l) _, err := io.ReadFull(receiver.reader, msg) return msg, err }
[ "func", "(", "receiver", "*", "lengthPrefixTCPReceiver", ")", "Receive", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "lenPrefix", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "receiver", ".", "reader", ",", "lenPrefix", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "l", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "lenPrefix", ")", "\n", "if", "l", ">", "maxTCPMsgSize", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"incoming message exceeds maximum size: %d > %d\"", ",", "l", ",", "maxTCPMsgSize", ")", "\n", "}", "\n", "msg", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "receiver", ".", "reader", ",", "msg", ")", "\n", "return", "msg", ",", "err", "\n", "}" ]
// Receive implements TCPReceiver by making a length-limited read into a byte buffer.
[ "Receive", "implements", "TCPReceiver", "by", "making", "a", "length", "-", "limited", "read", "into", "a", "byte", "buffer", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L166-L178
test
weaveworks/mesh
protocol_crypto.go
Receive
func (receiver *encryptedTCPReceiver) Receive() ([]byte, error) { msg, err := receiver.receiver.Receive() if err != nil { return nil, err } decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey) if !success { return nil, fmt.Errorf("Unable to decrypt TCP msg") } receiver.state.advance() return decodedMsg, nil }
go
func (receiver *encryptedTCPReceiver) Receive() ([]byte, error) { msg, err := receiver.receiver.Receive() if err != nil { return nil, err } decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey) if !success { return nil, fmt.Errorf("Unable to decrypt TCP msg") } receiver.state.advance() return decodedMsg, nil }
[ "func", "(", "receiver", "*", "encryptedTCPReceiver", ")", "Receive", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "msg", ",", "err", ":=", "receiver", ".", "receiver", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "decodedMsg", ",", "success", ":=", "secretbox", ".", "Open", "(", "nil", ",", "msg", ",", "&", "receiver", ".", "state", ".", "nonce", ",", "receiver", ".", "state", ".", "sessionKey", ")", "\n", "if", "!", "success", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to decrypt TCP msg\"", ")", "\n", "}", "\n", "receiver", ".", "state", ".", "advance", "(", ")", "\n", "return", "decodedMsg", ",", "nil", "\n", "}" ]
// Receive implements TCPReceiver by reading from the wrapped TCPReceiver and // unboxing the encrypted message, returning the decoded message.
[ "Receive", "implements", "TCPReceiver", "by", "reading", "from", "the", "wrapped", "TCPReceiver", "and", "unboxing", "the", "encrypted", "message", "returning", "the", "decoded", "message", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L192-L205
test
weaveworks/mesh
examples/increment-only-counter/peer.go
newPeer
func newPeer(self mesh.PeerName, logger *log.Logger) *peer { actions := make(chan func()) p := &peer{ st: newState(self), send: nil, // must .register() later actions: actions, quit: make(chan struct{}), logger: logger, } go p.loop(actions) return p }
go
func newPeer(self mesh.PeerName, logger *log.Logger) *peer { actions := make(chan func()) p := &peer{ st: newState(self), send: nil, // must .register() later actions: actions, quit: make(chan struct{}), logger: logger, } go p.loop(actions) return p }
[ "func", "newPeer", "(", "self", "mesh", ".", "PeerName", ",", "logger", "*", "log", ".", "Logger", ")", "*", "peer", "{", "actions", ":=", "make", "(", "chan", "func", "(", ")", ")", "\n", "p", ":=", "&", "peer", "{", "st", ":", "newState", "(", "self", ")", ",", "send", ":", "nil", ",", "actions", ":", "actions", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "logger", ":", "logger", ",", "}", "\n", "go", "p", ".", "loop", "(", "actions", ")", "\n", "return", "p", "\n", "}" ]
// Construct a peer with empty state. // Be sure to register a channel, later, // so we can make outbound communication.
[ "Construct", "a", "peer", "with", "empty", "state", ".", "Be", "sure", "to", "register", "a", "channel", "later", "so", "we", "can", "make", "outbound", "communication", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L30-L41
test
weaveworks/mesh
examples/increment-only-counter/peer.go
incr
func (p *peer) incr() (result int) { c := make(chan struct{}) p.actions <- func() { defer close(c) st := p.st.incr() if p.send != nil { p.send.GossipBroadcast(st) } else { p.logger.Printf("no sender configured; not broadcasting update right now") } result = st.get() } <-c return result }
go
func (p *peer) incr() (result int) { c := make(chan struct{}) p.actions <- func() { defer close(c) st := p.st.incr() if p.send != nil { p.send.GossipBroadcast(st) } else { p.logger.Printf("no sender configured; not broadcasting update right now") } result = st.get() } <-c return result }
[ "func", "(", "p", "*", "peer", ")", "incr", "(", ")", "(", "result", "int", ")", "{", "c", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "p", ".", "actions", "<-", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "st", ":=", "p", ".", "st", ".", "incr", "(", ")", "\n", "if", "p", ".", "send", "!=", "nil", "{", "p", ".", "send", ".", "GossipBroadcast", "(", "st", ")", "\n", "}", "else", "{", "p", ".", "logger", ".", "Printf", "(", "\"no sender configured; not broadcasting update right now\"", ")", "\n", "}", "\n", "result", "=", "st", ".", "get", "(", ")", "\n", "}", "\n", "<-", "c", "\n", "return", "result", "\n", "}" ]
// Increment the counter by one.
[ "Increment", "the", "counter", "by", "one", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L65-L79
test
weaveworks/mesh
examples/increment-only-counter/peer.go
Gossip
func (p *peer) Gossip() (complete mesh.GossipData) { complete = p.st.copy() p.logger.Printf("Gossip => complete %v", complete.(*state).set) return complete }
go
func (p *peer) Gossip() (complete mesh.GossipData) { complete = p.st.copy() p.logger.Printf("Gossip => complete %v", complete.(*state).set) return complete }
[ "func", "(", "p", "*", "peer", ")", "Gossip", "(", ")", "(", "complete", "mesh", ".", "GossipData", ")", "{", "complete", "=", "p", ".", "st", ".", "copy", "(", ")", "\n", "p", ".", "logger", ".", "Printf", "(", "\"Gossip => complete %v\"", ",", "complete", ".", "(", "*", "state", ")", ".", "set", ")", "\n", "return", "complete", "\n", "}" ]
// Return a copy of our complete state.
[ "Return", "a", "copy", "of", "our", "complete", "state", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L86-L90
test
weaveworks/mesh
examples/increment-only-counter/peer.go
OnGossipUnicast
func (p *peer) OnGossipUnicast(src mesh.PeerName, buf []byte) error { var set map[mesh.PeerName]int if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil { return err } complete := p.st.mergeComplete(set) p.logger.Printf("OnGossipUnicast %s %v => complete %v", src, set, complete) return nil }
go
func (p *peer) OnGossipUnicast(src mesh.PeerName, buf []byte) error { var set map[mesh.PeerName]int if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil { return err } complete := p.st.mergeComplete(set) p.logger.Printf("OnGossipUnicast %s %v => complete %v", src, set, complete) return nil }
[ "func", "(", "p", "*", "peer", ")", "OnGossipUnicast", "(", "src", "mesh", ".", "PeerName", ",", "buf", "[", "]", "byte", ")", "error", "{", "var", "set", "map", "[", "mesh", ".", "PeerName", "]", "int", "\n", "if", "err", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "buf", ")", ")", ".", "Decode", "(", "&", "set", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "complete", ":=", "p", ".", "st", ".", "mergeComplete", "(", "set", ")", "\n", "p", ".", "logger", ".", "Printf", "(", "\"OnGossipUnicast %s %v => complete %v\"", ",", "src", ",", "set", ",", "complete", ")", "\n", "return", "nil", "\n", "}" ]
// Merge the gossiped data represented by buf into our state.
[ "Merge", "the", "gossiped", "data", "represented", "by", "buf", "into", "our", "state", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L127-L136
test
weaveworks/mesh
_metcd/ctrl.go
makeRaftPeer
func makeRaftPeer(addr net.Addr) raft.Peer { return raft.Peer{ ID: uint64(addr.(meshconn.MeshAddr).PeerUID), Context: nil, // TODO(pb): ?? } }
go
func makeRaftPeer(addr net.Addr) raft.Peer { return raft.Peer{ ID: uint64(addr.(meshconn.MeshAddr).PeerUID), Context: nil, // TODO(pb): ?? } }
[ "func", "makeRaftPeer", "(", "addr", "net", ".", "Addr", ")", "raft", ".", "Peer", "{", "return", "raft", ".", "Peer", "{", "ID", ":", "uint64", "(", "addr", ".", "(", "meshconn", ".", "MeshAddr", ")", ".", "PeerUID", ")", ",", "Context", ":", "nil", ",", "}", "\n", "}" ]
// makeRaftPeer converts a net.Addr into a raft.Peer. // All peers must perform the Addr-to-Peer mapping in the same way. // // The etcd Raft implementation tracks the committed entry for each node ID, // and panics if it discovers a node has lost previously committed entries. // In effect, it assumes commitment implies durability. But our storage is // explicitly non-durable. So, whenever a node restarts, we need to give it // a brand new ID. That is the peer UID.
[ "makeRaftPeer", "converts", "a", "net", ".", "Addr", "into", "a", "raft", ".", "Peer", ".", "All", "peers", "must", "perform", "the", "Addr", "-", "to", "-", "Peer", "mapping", "in", "the", "same", "way", ".", "The", "etcd", "Raft", "implementation", "tracks", "the", "committed", "entry", "for", "each", "node", "ID", "and", "panics", "if", "it", "discovers", "a", "node", "has", "lost", "previously", "committed", "entries", ".", "In", "effect", "it", "assumes", "commitment", "implies", "durability", ".", "But", "our", "storage", "is", "explicitly", "non", "-", "durable", ".", "So", "whenever", "a", "node", "restarts", "we", "need", "to", "give", "it", "a", "brand", "new", "ID", ".", "That", "is", "the", "peer", "UID", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/ctrl.go#L314-L319
test
weaveworks/mesh
peer.go
String
func (peer *Peer) String() string { return fmt.Sprint(peer.Name, "(", peer.NickName, ")") }
go
func (peer *Peer) String() string { return fmt.Sprint(peer.Name, "(", peer.NickName, ")") }
[ "func", "(", "peer", "*", "Peer", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprint", "(", "peer", ".", "Name", ",", "\"(\"", ",", "peer", ".", "NickName", ",", "\")\"", ")", "\n", "}" ]
// String returns the peer name and nickname.
[ "String", "returns", "the", "peer", "name", "and", "nickname", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L64-L66
test
weaveworks/mesh
peer.go
forEachConnectedPeer
func (peer *Peer) forEachConnectedPeer(establishedAndSymmetric bool, exclude map[PeerName]PeerName, f func(*Peer)) { for remoteName, conn := range peer.connections { if establishedAndSymmetric && !conn.isEstablished() { continue } if _, found := exclude[remoteName]; found { continue } remotePeer := conn.Remote() if remoteConn, found := remotePeer.connections[peer.Name]; !establishedAndSymmetric || (found && remoteConn.isEstablished()) { f(remotePeer) } } }
go
func (peer *Peer) forEachConnectedPeer(establishedAndSymmetric bool, exclude map[PeerName]PeerName, f func(*Peer)) { for remoteName, conn := range peer.connections { if establishedAndSymmetric && !conn.isEstablished() { continue } if _, found := exclude[remoteName]; found { continue } remotePeer := conn.Remote() if remoteConn, found := remotePeer.connections[peer.Name]; !establishedAndSymmetric || (found && remoteConn.isEstablished()) { f(remotePeer) } } }
[ "func", "(", "peer", "*", "Peer", ")", "forEachConnectedPeer", "(", "establishedAndSymmetric", "bool", ",", "exclude", "map", "[", "PeerName", "]", "PeerName", ",", "f", "func", "(", "*", "Peer", ")", ")", "{", "for", "remoteName", ",", "conn", ":=", "range", "peer", ".", "connections", "{", "if", "establishedAndSymmetric", "&&", "!", "conn", ".", "isEstablished", "(", ")", "{", "continue", "\n", "}", "\n", "if", "_", ",", "found", ":=", "exclude", "[", "remoteName", "]", ";", "found", "{", "continue", "\n", "}", "\n", "remotePeer", ":=", "conn", ".", "Remote", "(", ")", "\n", "if", "remoteConn", ",", "found", ":=", "remotePeer", ".", "connections", "[", "peer", ".", "Name", "]", ";", "!", "establishedAndSymmetric", "||", "(", "found", "&&", "remoteConn", ".", "isEstablished", "(", ")", ")", "{", "f", "(", "remotePeer", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Apply f to all peers reachable by peer. If establishedAndSymmetric is true, // only peers with established bidirectional connections will be selected. The // exclude maps is treated as a set of remote peers to blacklist.
[ "Apply", "f", "to", "all", "peers", "reachable", "by", "peer", ".", "If", "establishedAndSymmetric", "is", "true", "only", "peers", "with", "established", "bidirectional", "connections", "will", "be", "selected", ".", "The", "exclude", "maps", "is", "treated", "as", "a", "set", "of", "remote", "peers", "to", "blacklist", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L123-L136
test
weaveworks/mesh
peer.go
parsePeerUID
func parsePeerUID(s string) (PeerUID, error) { uid, err := strconv.ParseUint(s, 10, 64) return PeerUID(uid), err }
go
func parsePeerUID(s string) (PeerUID, error) { uid, err := strconv.ParseUint(s, 10, 64) return PeerUID(uid), err }
[ "func", "parsePeerUID", "(", "s", "string", ")", "(", "PeerUID", ",", "error", ")", "{", "uid", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "return", "PeerUID", "(", "uid", ")", ",", "err", "\n", "}" ]
// ParsePeerUID parses a decimal peer UID from a string.
[ "ParsePeerUID", "parses", "a", "decimal", "peer", "UID", "from", "a", "string", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L142-L145
test
weaveworks/mesh
peer.go
Swap
func (lop listOfPeers) Swap(i, j int) { lop[i], lop[j] = lop[j], lop[i] }
go
func (lop listOfPeers) Swap(i, j int) { lop[i], lop[j] = lop[j], lop[i] }
[ "func", "(", "lop", "listOfPeers", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "lop", "[", "i", "]", ",", "lop", "[", "j", "]", "=", "lop", "[", "j", "]", ",", "lop", "[", "i", "]", "\n", "}" ]
// Swap implements sort.Interface.
[ "Swap", "implements", "sort", ".", "Interface", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L193-L195
test
weaveworks/mesh
peer.go
Less
func (lop listOfPeers) Less(i, j int) bool { return lop[i].Name < lop[j].Name }
go
func (lop listOfPeers) Less(i, j int) bool { return lop[i].Name < lop[j].Name }
[ "func", "(", "lop", "listOfPeers", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "lop", "[", "i", "]", ".", "Name", "<", "lop", "[", "j", "]", ".", "Name", "\n", "}" ]
// Less implements sort.Interface.
[ "Less", "implements", "sort", ".", "Interface", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L198-L200
test
weaveworks/mesh
protocol.go
doIntro
func (params protocolIntroParams) doIntro() (res protocolIntroResults, err error) { if err = params.Conn.SetDeadline(time.Now().Add(headerTimeout)); err != nil { return } if res.Version, err = params.exchangeProtocolHeader(); err != nil { return } var pubKey, privKey *[32]byte if params.Password != nil { if pubKey, privKey, err = generateKeyPair(); err != nil { return } } if err = params.Conn.SetWriteDeadline(time.Time{}); err != nil { return } if err = params.Conn.SetReadDeadline(time.Now().Add(tcpHeartbeat * 2)); err != nil { return } switch res.Version { case 1: err = res.doIntroV1(params, pubKey, privKey) case 2: err = res.doIntroV2(params, pubKey, privKey) default: panic("unhandled protocol version") } return }
go
func (params protocolIntroParams) doIntro() (res protocolIntroResults, err error) { if err = params.Conn.SetDeadline(time.Now().Add(headerTimeout)); err != nil { return } if res.Version, err = params.exchangeProtocolHeader(); err != nil { return } var pubKey, privKey *[32]byte if params.Password != nil { if pubKey, privKey, err = generateKeyPair(); err != nil { return } } if err = params.Conn.SetWriteDeadline(time.Time{}); err != nil { return } if err = params.Conn.SetReadDeadline(time.Now().Add(tcpHeartbeat * 2)); err != nil { return } switch res.Version { case 1: err = res.doIntroV1(params, pubKey, privKey) case 2: err = res.doIntroV2(params, pubKey, privKey) default: panic("unhandled protocol version") } return }
[ "func", "(", "params", "protocolIntroParams", ")", "doIntro", "(", ")", "(", "res", "protocolIntroResults", ",", "err", "error", ")", "{", "if", "err", "=", "params", ".", "Conn", ".", "SetDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "headerTimeout", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "res", ".", "Version", ",", "err", "=", "params", ".", "exchangeProtocolHeader", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "pubKey", ",", "privKey", "*", "[", "32", "]", "byte", "\n", "if", "params", ".", "Password", "!=", "nil", "{", "if", "pubKey", ",", "privKey", ",", "err", "=", "generateKeyPair", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "if", "err", "=", "params", ".", "Conn", ".", "SetWriteDeadline", "(", "time", ".", "Time", "{", "}", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "params", ".", "Conn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "tcpHeartbeat", "*", "2", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "switch", "res", ".", "Version", "{", "case", "1", ":", "err", "=", "res", ".", "doIntroV1", "(", "params", ",", "pubKey", ",", "privKey", ")", "\n", "case", "2", ":", "err", "=", "res", ".", "doIntroV2", "(", "params", ",", "pubKey", ",", "privKey", ")", "\n", "default", ":", "panic", "(", "\"unhandled protocol version\"", ")", "\n", "}", "\n", "return", "\n", "}" ]
// DoIntro executes the protocol introduction.
[ "DoIntro", "executes", "the", "protocol", "introduction", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol.go#L73-L106
test
weaveworks/mesh
protocol.go
filterV1Features
func filterV1Features(intro map[string]string) map[string]string { safe := make(map[string]string) for _, k := range protocolV1Features { if val, ok := intro[k]; ok { safe[k] = val } } return safe }
go
func filterV1Features(intro map[string]string) map[string]string { safe := make(map[string]string) for _, k := range protocolV1Features { if val, ok := intro[k]; ok { safe[k] = val } } return safe }
[ "func", "filterV1Features", "(", "intro", "map", "[", "string", "]", "string", ")", "map", "[", "string", "]", "string", "{", "safe", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "k", ":=", "range", "protocolV1Features", "{", "if", "val", ",", "ok", ":=", "intro", "[", "k", "]", ";", "ok", "{", "safe", "[", "k", "]", "=", "val", "\n", "}", "\n", "}", "\n", "return", "safe", "\n", "}" ]
// In the V1 protocol, the intro fields are sent unencrypted. So we // restrict them to an established subset of fields that are assumed // to be safe.
[ "In", "the", "V1", "protocol", "the", "intro", "fields", "are", "sent", "unencrypted", ".", "So", "we", "restrict", "them", "to", "an", "established", "subset", "of", "fields", "that", "are", "assumed", "to", "be", "safe", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol.go#L217-L226
test
weaveworks/mesh
connection_maker.go
newConnectionMaker
func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool, logger Logger) *connectionMaker { actionChan := make(chan connectionMakerAction, ChannelSize) cm := &connectionMaker{ ourself: ourself, peers: peers, localAddr: localAddr, port: port, discovery: discovery, directPeers: peerAddrs{}, targets: make(map[string]*target), connections: make(map[Connection]struct{}), actionChan: actionChan, logger: logger, } go cm.queryLoop(actionChan) return cm }
go
func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool, logger Logger) *connectionMaker { actionChan := make(chan connectionMakerAction, ChannelSize) cm := &connectionMaker{ ourself: ourself, peers: peers, localAddr: localAddr, port: port, discovery: discovery, directPeers: peerAddrs{}, targets: make(map[string]*target), connections: make(map[Connection]struct{}), actionChan: actionChan, logger: logger, } go cm.queryLoop(actionChan) return cm }
[ "func", "newConnectionMaker", "(", "ourself", "*", "localPeer", ",", "peers", "*", "Peers", ",", "localAddr", "string", ",", "port", "int", ",", "discovery", "bool", ",", "logger", "Logger", ")", "*", "connectionMaker", "{", "actionChan", ":=", "make", "(", "chan", "connectionMakerAction", ",", "ChannelSize", ")", "\n", "cm", ":=", "&", "connectionMaker", "{", "ourself", ":", "ourself", ",", "peers", ":", "peers", ",", "localAddr", ":", "localAddr", ",", "port", ":", "port", ",", "discovery", ":", "discovery", ",", "directPeers", ":", "peerAddrs", "{", "}", ",", "targets", ":", "make", "(", "map", "[", "string", "]", "*", "target", ")", ",", "connections", ":", "make", "(", "map", "[", "Connection", "]", "struct", "{", "}", ")", ",", "actionChan", ":", "actionChan", ",", "logger", ":", "logger", ",", "}", "\n", "go", "cm", ".", "queryLoop", "(", "actionChan", ")", "\n", "return", "cm", "\n", "}" ]
// newConnectionMaker returns a usable ConnectionMaker, seeded with // peers, making outbound connections from localAddr, and listening on // port. If discovery is true, ConnectionMaker will attempt to // initiate new connections with peers it's not directly connected to.
[ "newConnectionMaker", "returns", "a", "usable", "ConnectionMaker", "seeded", "with", "peers", "making", "outbound", "connections", "from", "localAddr", "and", "listening", "on", "port", ".", "If", "discovery", "is", "true", "ConnectionMaker", "will", "attempt", "to", "initiate", "new", "connections", "with", "peers", "it", "s", "not", "directly", "connected", "to", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L61-L77
test
weaveworks/mesh
connection_maker.go
connectionAborted
func (cm *connectionMaker) connectionAborted(address string, err error) { cm.actionChan <- func() bool { target := cm.targets[address] target.state = targetWaiting target.lastError = err target.nextTryLater() return true } }
go
func (cm *connectionMaker) connectionAborted(address string, err error) { cm.actionChan <- func() bool { target := cm.targets[address] target.state = targetWaiting target.lastError = err target.nextTryLater() return true } }
[ "func", "(", "cm", "*", "connectionMaker", ")", "connectionAborted", "(", "address", "string", ",", "err", "error", ")", "{", "cm", ".", "actionChan", "<-", "func", "(", ")", "bool", "{", "target", ":=", "cm", ".", "targets", "[", "address", "]", "\n", "target", ".", "state", "=", "targetWaiting", "\n", "target", ".", "lastError", "=", "err", "\n", "target", ".", "nextTryLater", "(", ")", "\n", "return", "true", "\n", "}", "\n", "}" ]
// connectionAborted marks the target identified by address as broken, and // puts it in the TargetWaiting state.
[ "connectionAborted", "marks", "the", "target", "identified", "by", "address", "as", "broken", "and", "puts", "it", "in", "the", "TargetWaiting", "state", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection_maker.go#L165-L173
test
weaveworks/mesh
gossip.go
newGossipSender
func newGossipSender( makeMsg func(msg []byte) protocolMsg, makeBroadcastMsg func(srcName PeerName, msg []byte) protocolMsg, sender protocolSender, stop <-chan struct{}, ) *gossipSender { more := make(chan struct{}, 1) flush := make(chan chan<- bool) s := &gossipSender{ makeMsg: makeMsg, makeBroadcastMsg: makeBroadcastMsg, sender: sender, broadcasts: make(map[PeerName]GossipData), more: more, flush: flush, } go s.run(stop, more, flush) return s }
go
func newGossipSender( makeMsg func(msg []byte) protocolMsg, makeBroadcastMsg func(srcName PeerName, msg []byte) protocolMsg, sender protocolSender, stop <-chan struct{}, ) *gossipSender { more := make(chan struct{}, 1) flush := make(chan chan<- bool) s := &gossipSender{ makeMsg: makeMsg, makeBroadcastMsg: makeBroadcastMsg, sender: sender, broadcasts: make(map[PeerName]GossipData), more: more, flush: flush, } go s.run(stop, more, flush) return s }
[ "func", "newGossipSender", "(", "makeMsg", "func", "(", "msg", "[", "]", "byte", ")", "protocolMsg", ",", "makeBroadcastMsg", "func", "(", "srcName", "PeerName", ",", "msg", "[", "]", "byte", ")", "protocolMsg", ",", "sender", "protocolSender", ",", "stop", "<-", "chan", "struct", "{", "}", ",", ")", "*", "gossipSender", "{", "more", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "flush", ":=", "make", "(", "chan", "chan", "<-", "bool", ")", "\n", "s", ":=", "&", "gossipSender", "{", "makeMsg", ":", "makeMsg", ",", "makeBroadcastMsg", ":", "makeBroadcastMsg", ",", "sender", ":", "sender", ",", "broadcasts", ":", "make", "(", "map", "[", "PeerName", "]", "GossipData", ")", ",", "more", ":", "more", ",", "flush", ":", "flush", ",", "}", "\n", "go", "s", ".", "run", "(", "stop", ",", "more", ",", "flush", ")", "\n", "return", "s", "\n", "}" ]
// NewGossipSender constructs a usable GossipSender.
[ "NewGossipSender", "constructs", "a", "usable", "GossipSender", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L78-L96
test
weaveworks/mesh
gossip.go
Send
func (s *gossipSender) Send(data GossipData) { s.Lock() defer s.Unlock() if s.empty() { defer s.prod() } if s.gossip == nil { s.gossip = data } else { s.gossip = s.gossip.Merge(data) } }
go
func (s *gossipSender) Send(data GossipData) { s.Lock() defer s.Unlock() if s.empty() { defer s.prod() } if s.gossip == nil { s.gossip = data } else { s.gossip = s.gossip.Merge(data) } }
[ "func", "(", "s", "*", "gossipSender", ")", "Send", "(", "data", "GossipData", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "empty", "(", ")", "{", "defer", "s", ".", "prod", "(", ")", "\n", "}", "\n", "if", "s", ".", "gossip", "==", "nil", "{", "s", ".", "gossip", "=", "data", "\n", "}", "else", "{", "s", ".", "gossip", "=", "s", ".", "gossip", ".", "Merge", "(", "data", ")", "\n", "}", "\n", "}" ]
// Send accumulates the GossipData and will send it eventually. // Send and Broadcast accumulate into different buckets.
[ "Send", "accumulates", "the", "GossipData", "and", "will", "send", "it", "eventually", ".", "Send", "and", "Broadcast", "accumulate", "into", "different", "buckets", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L174-L185
test
weaveworks/mesh
gossip.go
Broadcast
func (s *gossipSender) Broadcast(srcName PeerName, data GossipData) { s.Lock() defer s.Unlock() if s.empty() { defer s.prod() } d, found := s.broadcasts[srcName] if !found { s.broadcasts[srcName] = data } else { s.broadcasts[srcName] = d.Merge(data) } }
go
func (s *gossipSender) Broadcast(srcName PeerName, data GossipData) { s.Lock() defer s.Unlock() if s.empty() { defer s.prod() } d, found := s.broadcasts[srcName] if !found { s.broadcasts[srcName] = data } else { s.broadcasts[srcName] = d.Merge(data) } }
[ "func", "(", "s", "*", "gossipSender", ")", "Broadcast", "(", "srcName", "PeerName", ",", "data", "GossipData", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "empty", "(", ")", "{", "defer", "s", ".", "prod", "(", ")", "\n", "}", "\n", "d", ",", "found", ":=", "s", ".", "broadcasts", "[", "srcName", "]", "\n", "if", "!", "found", "{", "s", ".", "broadcasts", "[", "srcName", "]", "=", "data", "\n", "}", "else", "{", "s", ".", "broadcasts", "[", "srcName", "]", "=", "d", ".", "Merge", "(", "data", ")", "\n", "}", "\n", "}" ]
// Broadcast accumulates the GossipData under the given srcName and will send // it eventually. Send and Broadcast accumulate into different buckets.
[ "Broadcast", "accumulates", "the", "GossipData", "under", "the", "given", "srcName", "and", "will", "send", "it", "eventually", ".", "Send", "and", "Broadcast", "accumulate", "into", "different", "buckets", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L189-L201
test
weaveworks/mesh
gossip.go
Flush
func (s *gossipSender) Flush() bool { ch := make(chan bool) s.flush <- ch return <-ch }
go
func (s *gossipSender) Flush() bool { ch := make(chan bool) s.flush <- ch return <-ch }
[ "func", "(", "s", "*", "gossipSender", ")", "Flush", "(", ")", "bool", "{", "ch", ":=", "make", "(", "chan", "bool", ")", "\n", "s", ".", "flush", "<-", "ch", "\n", "return", "<-", "ch", "\n", "}" ]
// Flush sends all pending data, and returns true if anything was sent since // the previous flush. For testing.
[ "Flush", "sends", "all", "pending", "data", "and", "returns", "true", "if", "anything", "was", "sent", "since", "the", "previous", "flush", ".", "For", "testing", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L214-L218
test
weaveworks/mesh
gossip.go
Sender
func (gs *gossipSenders) Sender(channelName string, makeGossipSender func(sender protocolSender, stop <-chan struct{}) *gossipSender) *gossipSender { gs.Lock() defer gs.Unlock() s, found := gs.senders[channelName] if !found { s = makeGossipSender(gs.sender, gs.stop) gs.senders[channelName] = s } return s }
go
func (gs *gossipSenders) Sender(channelName string, makeGossipSender func(sender protocolSender, stop <-chan struct{}) *gossipSender) *gossipSender { gs.Lock() defer gs.Unlock() s, found := gs.senders[channelName] if !found { s = makeGossipSender(gs.sender, gs.stop) gs.senders[channelName] = s } return s }
[ "func", "(", "gs", "*", "gossipSenders", ")", "Sender", "(", "channelName", "string", ",", "makeGossipSender", "func", "(", "sender", "protocolSender", ",", "stop", "<-", "chan", "struct", "{", "}", ")", "*", "gossipSender", ")", "*", "gossipSender", "{", "gs", ".", "Lock", "(", ")", "\n", "defer", "gs", ".", "Unlock", "(", ")", "\n", "s", ",", "found", ":=", "gs", ".", "senders", "[", "channelName", "]", "\n", "if", "!", "found", "{", "s", "=", "makeGossipSender", "(", "gs", ".", "sender", ",", "gs", ".", "stop", ")", "\n", "gs", ".", "senders", "[", "channelName", "]", "=", "s", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Sender yields the GossipSender for the named channel. // It will use the factory function if no sender yet exists.
[ "Sender", "yields", "the", "GossipSender", "for", "the", "named", "channel", ".", "It", "will", "use", "the", "factory", "function", "if", "no", "sender", "yet", "exists", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L242-L251
test
weaveworks/mesh
gossip.go
Flush
func (gs *gossipSenders) Flush() bool { sent := false gs.Lock() defer gs.Unlock() for _, sender := range gs.senders { sent = sender.Flush() || sent } return sent }
go
func (gs *gossipSenders) Flush() bool { sent := false gs.Lock() defer gs.Unlock() for _, sender := range gs.senders { sent = sender.Flush() || sent } return sent }
[ "func", "(", "gs", "*", "gossipSenders", ")", "Flush", "(", ")", "bool", "{", "sent", ":=", "false", "\n", "gs", ".", "Lock", "(", ")", "\n", "defer", "gs", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "sender", ":=", "range", "gs", ".", "senders", "{", "sent", "=", "sender", ".", "Flush", "(", ")", "||", "sent", "\n", "}", "\n", "return", "sent", "\n", "}" ]
// Flush flushes all managed senders. Used for testing.
[ "Flush", "flushes", "all", "managed", "senders", ".", "Used", "for", "testing", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L254-L262
test
golang/appengine
internal/main_vm.go
findMainPath
func findMainPath() string { pc := make([]uintptr, 100) n := runtime.Callers(2, pc) frames := runtime.CallersFrames(pc[:n]) for { frame, more := frames.Next() // Tests won't have package main, instead they have testing.tRunner if frame.Function == "main.main" || frame.Function == "testing.tRunner" { return frame.File } if !more { break } } return "" }
go
func findMainPath() string { pc := make([]uintptr, 100) n := runtime.Callers(2, pc) frames := runtime.CallersFrames(pc[:n]) for { frame, more := frames.Next() // Tests won't have package main, instead they have testing.tRunner if frame.Function == "main.main" || frame.Function == "testing.tRunner" { return frame.File } if !more { break } } return "" }
[ "func", "findMainPath", "(", ")", "string", "{", "pc", ":=", "make", "(", "[", "]", "uintptr", ",", "100", ")", "\n", "n", ":=", "runtime", ".", "Callers", "(", "2", ",", "pc", ")", "\n", "frames", ":=", "runtime", ".", "CallersFrames", "(", "pc", "[", ":", "n", "]", ")", "\n", "for", "{", "frame", ",", "more", ":=", "frames", ".", "Next", "(", ")", "\n", "if", "frame", ".", "Function", "==", "\"main.main\"", "||", "frame", ".", "Function", "==", "\"testing.tRunner\"", "{", "return", "frame", ".", "File", "\n", "}", "\n", "if", "!", "more", "{", "break", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// Find the path to package main by looking at the root Caller.
[ "Find", "the", "path", "to", "package", "main", "by", "looking", "at", "the", "root", "Caller", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/main_vm.go#L38-L53
test
golang/appengine
channel/channel.go
Create
func Create(c context.Context, clientID string) (token string, err error) { req := &pb.CreateChannelRequest{ ApplicationKey: &clientID, } resp := &pb.CreateChannelResponse{} err = internal.Call(c, service, "CreateChannel", req, resp) token = resp.GetToken() return token, remapError(err) }
go
func Create(c context.Context, clientID string) (token string, err error) { req := &pb.CreateChannelRequest{ ApplicationKey: &clientID, } resp := &pb.CreateChannelResponse{} err = internal.Call(c, service, "CreateChannel", req, resp) token = resp.GetToken() return token, remapError(err) }
[ "func", "Create", "(", "c", "context", ".", "Context", ",", "clientID", "string", ")", "(", "token", "string", ",", "err", "error", ")", "{", "req", ":=", "&", "pb", ".", "CreateChannelRequest", "{", "ApplicationKey", ":", "&", "clientID", ",", "}", "\n", "resp", ":=", "&", "pb", ".", "CreateChannelResponse", "{", "}", "\n", "err", "=", "internal", ".", "Call", "(", "c", ",", "service", ",", "\"CreateChannel\"", ",", "req", ",", "resp", ")", "\n", "token", "=", "resp", ".", "GetToken", "(", ")", "\n", "return", "token", ",", "remapError", "(", "err", ")", "\n", "}" ]
// Create creates a channel and returns a token for use by the client. // The clientID is an application-provided string used to identify the client.
[ "Create", "creates", "a", "channel", "and", "returns", "a", "token", "for", "use", "by", "the", "client", ".", "The", "clientID", "is", "an", "application", "-", "provided", "string", "used", "to", "identify", "the", "client", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L40-L48
test
golang/appengine
channel/channel.go
Send
func Send(c context.Context, clientID, message string) error { req := &pb.SendMessageRequest{ ApplicationKey: &clientID, Message: &message, } resp := &basepb.VoidProto{} return remapError(internal.Call(c, service, "SendChannelMessage", req, resp)) }
go
func Send(c context.Context, clientID, message string) error { req := &pb.SendMessageRequest{ ApplicationKey: &clientID, Message: &message, } resp := &basepb.VoidProto{} return remapError(internal.Call(c, service, "SendChannelMessage", req, resp)) }
[ "func", "Send", "(", "c", "context", ".", "Context", ",", "clientID", ",", "message", "string", ")", "error", "{", "req", ":=", "&", "pb", ".", "SendMessageRequest", "{", "ApplicationKey", ":", "&", "clientID", ",", "Message", ":", "&", "message", ",", "}", "\n", "resp", ":=", "&", "basepb", ".", "VoidProto", "{", "}", "\n", "return", "remapError", "(", "internal", ".", "Call", "(", "c", ",", "service", ",", "\"SendChannelMessage\"", ",", "req", ",", "resp", ")", ")", "\n", "}" ]
// Send sends a message on the channel associated with clientID.
[ "Send", "sends", "a", "message", "on", "the", "channel", "associated", "with", "clientID", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L51-L58
test
golang/appengine
channel/channel.go
SendJSON
func SendJSON(c context.Context, clientID string, value interface{}) error { m, err := json.Marshal(value) if err != nil { return err } return Send(c, clientID, string(m)) }
go
func SendJSON(c context.Context, clientID string, value interface{}) error { m, err := json.Marshal(value) if err != nil { return err } return Send(c, clientID, string(m)) }
[ "func", "SendJSON", "(", "c", "context", ".", "Context", ",", "clientID", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "m", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "Send", "(", "c", ",", "clientID", ",", "string", "(", "m", ")", ")", "\n", "}" ]
// SendJSON is a helper function that sends a JSON-encoded value // on the channel associated with clientID.
[ "SendJSON", "is", "a", "helper", "function", "that", "sends", "a", "JSON", "-", "encoded", "value", "on", "the", "channel", "associated", "with", "clientID", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L62-L68
test
golang/appengine
channel/channel.go
remapError
func remapError(err error) error { if e, ok := err.(*internal.APIError); ok { if e.Service == "xmpp" { e.Service = "channel" } } return err }
go
func remapError(err error) error { if e, ok := err.(*internal.APIError); ok { if e.Service == "xmpp" { e.Service = "channel" } } return err }
[ "func", "remapError", "(", "err", "error", ")", "error", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "internal", ".", "APIError", ")", ";", "ok", "{", "if", "e", ".", "Service", "==", "\"xmpp\"", "{", "e", ".", "Service", "=", "\"channel\"", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// remapError fixes any APIError referencing "xmpp" into one referencing "channel".
[ "remapError", "fixes", "any", "APIError", "referencing", "xmpp", "into", "one", "referencing", "channel", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L71-L78
test
golang/appengine
internal/api_common.go
NamespacedContext
func NamespacedContext(ctx netcontext.Context, namespace string) netcontext.Context { return withNamespace(ctx, namespace) }
go
func NamespacedContext(ctx netcontext.Context, namespace string) netcontext.Context { return withNamespace(ctx, namespace) }
[ "func", "NamespacedContext", "(", "ctx", "netcontext", ".", "Context", ",", "namespace", "string", ")", "netcontext", ".", "Context", "{", "return", "withNamespace", "(", "ctx", ",", "namespace", ")", "\n", "}" ]
// NamespacedContext wraps a Context to support namespaces.
[ "NamespacedContext", "wraps", "a", "Context", "to", "support", "namespaces", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api_common.go#L93-L95
test
golang/appengine
memcache/memcache.go
protoToItem
func protoToItem(p *pb.MemcacheGetResponse_Item) *Item { return &Item{ Key: string(p.Key), Value: p.Value, Flags: p.GetFlags(), casID: p.GetCasId(), } }
go
func protoToItem(p *pb.MemcacheGetResponse_Item) *Item { return &Item{ Key: string(p.Key), Value: p.Value, Flags: p.GetFlags(), casID: p.GetCasId(), } }
[ "func", "protoToItem", "(", "p", "*", "pb", ".", "MemcacheGetResponse_Item", ")", "*", "Item", "{", "return", "&", "Item", "{", "Key", ":", "string", "(", "p", ".", "Key", ")", ",", "Value", ":", "p", ".", "Value", ",", "Flags", ":", "p", ".", "GetFlags", "(", ")", ",", "casID", ":", "p", ".", "GetCasId", "(", ")", ",", "}", "\n", "}" ]
// protoToItem converts a protocol buffer item to a Go struct.
[ "protoToItem", "converts", "a", "protocol", "buffer", "item", "to", "a", "Go", "struct", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L92-L99
test
golang/appengine
memcache/memcache.go
singleError
func singleError(err error) error { if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
go
func singleError(err error) error { if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
[ "func", "singleError", "(", "err", "error", ")", "error", "{", "if", "me", ",", "ok", ":=", "err", ".", "(", "appengine", ".", "MultiError", ")", ";", "ok", "{", "return", "me", "[", "0", "]", "\n", "}", "\n", "return", "err", "\n", "}" ]
// If err is an appengine.MultiError, return its first element. Otherwise, return err.
[ "If", "err", "is", "an", "appengine", ".", "MultiError", "return", "its", "first", "element", ".", "Otherwise", "return", "err", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L102-L107
test
golang/appengine
memcache/memcache.go
Get
func Get(c context.Context, key string) (*Item, error) { m, err := GetMulti(c, []string{key}) if err != nil { return nil, err } if _, ok := m[key]; !ok { return nil, ErrCacheMiss } return m[key], nil }
go
func Get(c context.Context, key string) (*Item, error) { m, err := GetMulti(c, []string{key}) if err != nil { return nil, err } if _, ok := m[key]; !ok { return nil, ErrCacheMiss } return m[key], nil }
[ "func", "Get", "(", "c", "context", ".", "Context", ",", "key", "string", ")", "(", "*", "Item", ",", "error", ")", "{", "m", ",", "err", ":=", "GetMulti", "(", "c", ",", "[", "]", "string", "{", "key", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", "[", "key", "]", ";", "!", "ok", "{", "return", "nil", ",", "ErrCacheMiss", "\n", "}", "\n", "return", "m", "[", "key", "]", ",", "nil", "\n", "}" ]
// Get gets the item for the given key. ErrCacheMiss is returned for a memcache // cache miss. The key must be at most 250 bytes in length.
[ "Get", "gets", "the", "item", "for", "the", "given", "key", ".", "ErrCacheMiss", "is", "returned", "for", "a", "memcache", "cache", "miss", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L111-L120
test
golang/appengine
memcache/memcache.go
GetMulti
func GetMulti(c context.Context, key []string) (map[string]*Item, error) { if len(key) == 0 { return nil, nil } keyAsBytes := make([][]byte, len(key)) for i, k := range key { keyAsBytes[i] = []byte(k) } req := &pb.MemcacheGetRequest{ Key: keyAsBytes, ForCas: proto.Bool(true), } res := &pb.MemcacheGetResponse{} if err := internal.Call(c, "memcache", "Get", req, res); err != nil { return nil, err } m := make(map[string]*Item, len(res.Item)) for _, p := range res.Item { t := protoToItem(p) m[t.Key] = t } return m, nil }
go
func GetMulti(c context.Context, key []string) (map[string]*Item, error) { if len(key) == 0 { return nil, nil } keyAsBytes := make([][]byte, len(key)) for i, k := range key { keyAsBytes[i] = []byte(k) } req := &pb.MemcacheGetRequest{ Key: keyAsBytes, ForCas: proto.Bool(true), } res := &pb.MemcacheGetResponse{} if err := internal.Call(c, "memcache", "Get", req, res); err != nil { return nil, err } m := make(map[string]*Item, len(res.Item)) for _, p := range res.Item { t := protoToItem(p) m[t.Key] = t } return m, nil }
[ "func", "GetMulti", "(", "c", "context", ".", "Context", ",", "key", "[", "]", "string", ")", "(", "map", "[", "string", "]", "*", "Item", ",", "error", ")", "{", "if", "len", "(", "key", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "keyAsBytes", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "key", ")", ")", "\n", "for", "i", ",", "k", ":=", "range", "key", "{", "keyAsBytes", "[", "i", "]", "=", "[", "]", "byte", "(", "k", ")", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "MemcacheGetRequest", "{", "Key", ":", "keyAsBytes", ",", "ForCas", ":", "proto", ".", "Bool", "(", "true", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "MemcacheGetResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"memcache\"", ",", "\"Get\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "*", "Item", ",", "len", "(", "res", ".", "Item", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "res", ".", "Item", "{", "t", ":=", "protoToItem", "(", "p", ")", "\n", "m", "[", "t", ".", "Key", "]", "=", "t", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// GetMulti is a batch version of Get. The returned map from keys to items may // have fewer elements than the input slice, due to memcache cache misses. // Each key must be at most 250 bytes in length.
[ "GetMulti", "is", "a", "batch", "version", "of", "Get", ".", "The", "returned", "map", "from", "keys", "to", "items", "may", "have", "fewer", "elements", "than", "the", "input", "slice", "due", "to", "memcache", "cache", "misses", ".", "Each", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L125-L147
test
golang/appengine
memcache/memcache.go
Delete
func Delete(c context.Context, key string) error { return singleError(DeleteMulti(c, []string{key})) }
go
func Delete(c context.Context, key string) error { return singleError(DeleteMulti(c, []string{key})) }
[ "func", "Delete", "(", "c", "context", ".", "Context", ",", "key", "string", ")", "error", "{", "return", "singleError", "(", "DeleteMulti", "(", "c", ",", "[", "]", "string", "{", "key", "}", ")", ")", "\n", "}" ]
// Delete deletes the item for the given key. // ErrCacheMiss is returned if the specified item can not be found. // The key must be at most 250 bytes in length.
[ "Delete", "deletes", "the", "item", "for", "the", "given", "key", ".", "ErrCacheMiss", "is", "returned", "if", "the", "specified", "item", "can", "not", "be", "found", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L152-L154
test
golang/appengine
memcache/memcache.go
DeleteMulti
func DeleteMulti(c context.Context, key []string) error { if len(key) == 0 { return nil } req := &pb.MemcacheDeleteRequest{ Item: make([]*pb.MemcacheDeleteRequest_Item, len(key)), } for i, k := range key { req.Item[i] = &pb.MemcacheDeleteRequest_Item{Key: []byte(k)} } res := &pb.MemcacheDeleteResponse{} if err := internal.Call(c, "memcache", "Delete", req, res); err != nil { return err } if len(res.DeleteStatus) != len(key) { return ErrServerError } me, any := make(appengine.MultiError, len(key)), false for i, s := range res.DeleteStatus { switch s { case pb.MemcacheDeleteResponse_DELETED: // OK case pb.MemcacheDeleteResponse_NOT_FOUND: me[i] = ErrCacheMiss any = true default: me[i] = ErrServerError any = true } } if any { return me } return nil }
go
func DeleteMulti(c context.Context, key []string) error { if len(key) == 0 { return nil } req := &pb.MemcacheDeleteRequest{ Item: make([]*pb.MemcacheDeleteRequest_Item, len(key)), } for i, k := range key { req.Item[i] = &pb.MemcacheDeleteRequest_Item{Key: []byte(k)} } res := &pb.MemcacheDeleteResponse{} if err := internal.Call(c, "memcache", "Delete", req, res); err != nil { return err } if len(res.DeleteStatus) != len(key) { return ErrServerError } me, any := make(appengine.MultiError, len(key)), false for i, s := range res.DeleteStatus { switch s { case pb.MemcacheDeleteResponse_DELETED: // OK case pb.MemcacheDeleteResponse_NOT_FOUND: me[i] = ErrCacheMiss any = true default: me[i] = ErrServerError any = true } } if any { return me } return nil }
[ "func", "DeleteMulti", "(", "c", "context", ".", "Context", ",", "key", "[", "]", "string", ")", "error", "{", "if", "len", "(", "key", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "MemcacheDeleteRequest", "{", "Item", ":", "make", "(", "[", "]", "*", "pb", ".", "MemcacheDeleteRequest_Item", ",", "len", "(", "key", ")", ")", ",", "}", "\n", "for", "i", ",", "k", ":=", "range", "key", "{", "req", ".", "Item", "[", "i", "]", "=", "&", "pb", ".", "MemcacheDeleteRequest_Item", "{", "Key", ":", "[", "]", "byte", "(", "k", ")", "}", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "MemcacheDeleteResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"memcache\"", ",", "\"Delete\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "DeleteStatus", ")", "!=", "len", "(", "key", ")", "{", "return", "ErrServerError", "\n", "}", "\n", "me", ",", "any", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "key", ")", ")", ",", "false", "\n", "for", "i", ",", "s", ":=", "range", "res", ".", "DeleteStatus", "{", "switch", "s", "{", "case", "pb", ".", "MemcacheDeleteResponse_DELETED", ":", "case", "pb", ".", "MemcacheDeleteResponse_NOT_FOUND", ":", "me", "[", "i", "]", "=", "ErrCacheMiss", "\n", "any", "=", "true", "\n", "default", ":", "me", "[", "i", "]", "=", "ErrServerError", "\n", "any", "=", "true", "\n", "}", "\n", "}", "\n", "if", "any", "{", "return", "me", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteMulti is a batch version of Delete. // If any keys cannot be found, an appengine.MultiError is returned. // Each key must be at most 250 bytes in length.
[ "DeleteMulti", "is", "a", "batch", "version", "of", "Delete", ".", "If", "any", "keys", "cannot", "be", "found", "an", "appengine", ".", "MultiError", "is", "returned", ".", "Each", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L159-L193
test
golang/appengine
memcache/memcache.go
Increment
func Increment(c context.Context, key string, delta int64, initialValue uint64) (newValue uint64, err error) { return incr(c, key, delta, &initialValue) }
go
func Increment(c context.Context, key string, delta int64, initialValue uint64) (newValue uint64, err error) { return incr(c, key, delta, &initialValue) }
[ "func", "Increment", "(", "c", "context", ".", "Context", ",", "key", "string", ",", "delta", "int64", ",", "initialValue", "uint64", ")", "(", "newValue", "uint64", ",", "err", "error", ")", "{", "return", "incr", "(", "c", ",", "key", ",", "delta", ",", "&", "initialValue", ")", "\n", "}" ]
// Increment atomically increments the decimal value in the given key // by delta and returns the new value. The value must fit in a uint64. // Overflow wraps around, and underflow is capped to zero. The // provided delta may be negative. If the key doesn't exist in // memcache, the provided initial value is used to atomically // populate it before the delta is applied. // The key must be at most 250 bytes in length.
[ "Increment", "atomically", "increments", "the", "decimal", "value", "in", "the", "given", "key", "by", "delta", "and", "returns", "the", "new", "value", ".", "The", "value", "must", "fit", "in", "a", "uint64", ".", "Overflow", "wraps", "around", "and", "underflow", "is", "capped", "to", "zero", ".", "The", "provided", "delta", "may", "be", "negative", ".", "If", "the", "key", "doesn", "t", "exist", "in", "memcache", "the", "provided", "initial", "value", "is", "used", "to", "atomically", "populate", "it", "before", "the", "delta", "is", "applied", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L202-L204
test
golang/appengine
memcache/memcache.go
IncrementExisting
func IncrementExisting(c context.Context, key string, delta int64) (newValue uint64, err error) { return incr(c, key, delta, nil) }
go
func IncrementExisting(c context.Context, key string, delta int64) (newValue uint64, err error) { return incr(c, key, delta, nil) }
[ "func", "IncrementExisting", "(", "c", "context", ".", "Context", ",", "key", "string", ",", "delta", "int64", ")", "(", "newValue", "uint64", ",", "err", "error", ")", "{", "return", "incr", "(", "c", ",", "key", ",", "delta", ",", "nil", ")", "\n", "}" ]
// IncrementExisting works like Increment but assumes that the key // already exists in memcache and doesn't take an initial value. // IncrementExisting can save work if calculating the initial value is // expensive. // An error is returned if the specified item can not be found.
[ "IncrementExisting", "works", "like", "Increment", "but", "assumes", "that", "the", "key", "already", "exists", "in", "memcache", "and", "doesn", "t", "take", "an", "initial", "value", ".", "IncrementExisting", "can", "save", "work", "if", "calculating", "the", "initial", "value", "is", "expensive", ".", "An", "error", "is", "returned", "if", "the", "specified", "item", "can", "not", "be", "found", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L211-L213
test
golang/appengine
memcache/memcache.go
set
func set(c context.Context, item []*Item, value [][]byte, policy pb.MemcacheSetRequest_SetPolicy) error { if len(item) == 0 { return nil } req := &pb.MemcacheSetRequest{ Item: make([]*pb.MemcacheSetRequest_Item, len(item)), } for i, t := range item { p := &pb.MemcacheSetRequest_Item{ Key: []byte(t.Key), } if value == nil { p.Value = t.Value } else { p.Value = value[i] } if t.Flags != 0 { p.Flags = proto.Uint32(t.Flags) } if t.Expiration != 0 { // In the .proto file, MemcacheSetRequest_Item uses a fixed32 (i.e. unsigned) // for expiration time, while MemcacheGetRequest_Item uses int32 (i.e. signed). // Throughout this .go file, we use int32. // Also, in the proto, the expiration value is either a duration (in seconds) // or an absolute Unix timestamp (in seconds), depending on whether the // value is less than or greater than or equal to 30 years, respectively. if t.Expiration < time.Second { // Because an Expiration of 0 means no expiration, we take // care here to translate an item with an expiration // Duration between 0-1 seconds as immediately expiring // (saying it expired a few seconds ago), rather than // rounding it down to 0 and making it live forever. p.ExpirationTime = proto.Uint32(uint32(time.Now().Unix()) - 5) } else if t.Expiration >= thirtyYears { p.ExpirationTime = proto.Uint32(uint32(time.Now().Unix()) + uint32(t.Expiration/time.Second)) } else { p.ExpirationTime = proto.Uint32(uint32(t.Expiration / time.Second)) } } if t.casID != 0 { p.CasId = proto.Uint64(t.casID) p.ForCas = proto.Bool(true) } p.SetPolicy = policy.Enum() req.Item[i] = p } res := &pb.MemcacheSetResponse{} if err := internal.Call(c, "memcache", "Set", req, res); err != nil { return err } if len(res.SetStatus) != len(item) { return ErrServerError } me, any := make(appengine.MultiError, len(item)), false for i, st := range res.SetStatus { var err error switch st { case pb.MemcacheSetResponse_STORED: // OK case pb.MemcacheSetResponse_NOT_STORED: err = ErrNotStored case pb.MemcacheSetResponse_EXISTS: err = ErrCASConflict default: err = ErrServerError } if err != nil { me[i] = err any = true } } if any { return me } return nil }
go
func set(c context.Context, item []*Item, value [][]byte, policy pb.MemcacheSetRequest_SetPolicy) error { if len(item) == 0 { return nil } req := &pb.MemcacheSetRequest{ Item: make([]*pb.MemcacheSetRequest_Item, len(item)), } for i, t := range item { p := &pb.MemcacheSetRequest_Item{ Key: []byte(t.Key), } if value == nil { p.Value = t.Value } else { p.Value = value[i] } if t.Flags != 0 { p.Flags = proto.Uint32(t.Flags) } if t.Expiration != 0 { // In the .proto file, MemcacheSetRequest_Item uses a fixed32 (i.e. unsigned) // for expiration time, while MemcacheGetRequest_Item uses int32 (i.e. signed). // Throughout this .go file, we use int32. // Also, in the proto, the expiration value is either a duration (in seconds) // or an absolute Unix timestamp (in seconds), depending on whether the // value is less than or greater than or equal to 30 years, respectively. if t.Expiration < time.Second { // Because an Expiration of 0 means no expiration, we take // care here to translate an item with an expiration // Duration between 0-1 seconds as immediately expiring // (saying it expired a few seconds ago), rather than // rounding it down to 0 and making it live forever. p.ExpirationTime = proto.Uint32(uint32(time.Now().Unix()) - 5) } else if t.Expiration >= thirtyYears { p.ExpirationTime = proto.Uint32(uint32(time.Now().Unix()) + uint32(t.Expiration/time.Second)) } else { p.ExpirationTime = proto.Uint32(uint32(t.Expiration / time.Second)) } } if t.casID != 0 { p.CasId = proto.Uint64(t.casID) p.ForCas = proto.Bool(true) } p.SetPolicy = policy.Enum() req.Item[i] = p } res := &pb.MemcacheSetResponse{} if err := internal.Call(c, "memcache", "Set", req, res); err != nil { return err } if len(res.SetStatus) != len(item) { return ErrServerError } me, any := make(appengine.MultiError, len(item)), false for i, st := range res.SetStatus { var err error switch st { case pb.MemcacheSetResponse_STORED: // OK case pb.MemcacheSetResponse_NOT_STORED: err = ErrNotStored case pb.MemcacheSetResponse_EXISTS: err = ErrCASConflict default: err = ErrServerError } if err != nil { me[i] = err any = true } } if any { return me } return nil }
[ "func", "set", "(", "c", "context", ".", "Context", ",", "item", "[", "]", "*", "Item", ",", "value", "[", "]", "[", "]", "byte", ",", "policy", "pb", ".", "MemcacheSetRequest_SetPolicy", ")", "error", "{", "if", "len", "(", "item", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "MemcacheSetRequest", "{", "Item", ":", "make", "(", "[", "]", "*", "pb", ".", "MemcacheSetRequest_Item", ",", "len", "(", "item", ")", ")", ",", "}", "\n", "for", "i", ",", "t", ":=", "range", "item", "{", "p", ":=", "&", "pb", ".", "MemcacheSetRequest_Item", "{", "Key", ":", "[", "]", "byte", "(", "t", ".", "Key", ")", ",", "}", "\n", "if", "value", "==", "nil", "{", "p", ".", "Value", "=", "t", ".", "Value", "\n", "}", "else", "{", "p", ".", "Value", "=", "value", "[", "i", "]", "\n", "}", "\n", "if", "t", ".", "Flags", "!=", "0", "{", "p", ".", "Flags", "=", "proto", ".", "Uint32", "(", "t", ".", "Flags", ")", "\n", "}", "\n", "if", "t", ".", "Expiration", "!=", "0", "{", "if", "t", ".", "Expiration", "<", "time", ".", "Second", "{", "p", ".", "ExpirationTime", "=", "proto", ".", "Uint32", "(", "uint32", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "-", "5", ")", "\n", "}", "else", "if", "t", ".", "Expiration", ">=", "thirtyYears", "{", "p", ".", "ExpirationTime", "=", "proto", ".", "Uint32", "(", "uint32", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "+", "uint32", "(", "t", ".", "Expiration", "/", "time", ".", "Second", ")", ")", "\n", "}", "else", "{", "p", ".", "ExpirationTime", "=", "proto", ".", "Uint32", "(", "uint32", "(", "t", ".", "Expiration", "/", "time", ".", "Second", ")", ")", "\n", "}", "\n", "}", "\n", "if", "t", ".", "casID", "!=", "0", "{", "p", ".", "CasId", "=", "proto", ".", "Uint64", "(", "t", ".", "casID", ")", "\n", "p", ".", "ForCas", "=", "proto", ".", "Bool", "(", "true", ")", "\n", "}", "\n", "p", ".", "SetPolicy", "=", "policy", ".", "Enum", "(", ")", "\n", "req", ".", "Item", "[", "i", "]", "=", "p", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "MemcacheSetResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"memcache\"", ",", "\"Set\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "SetStatus", ")", "!=", "len", "(", "item", ")", "{", "return", "ErrServerError", "\n", "}", "\n", "me", ",", "any", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "item", ")", ")", ",", "false", "\n", "for", "i", ",", "st", ":=", "range", "res", ".", "SetStatus", "{", "var", "err", "error", "\n", "switch", "st", "{", "case", "pb", ".", "MemcacheSetResponse_STORED", ":", "case", "pb", ".", "MemcacheSetResponse_NOT_STORED", ":", "err", "=", "ErrNotStored", "\n", "case", "pb", ".", "MemcacheSetResponse_EXISTS", ":", "err", "=", "ErrCASConflict", "\n", "default", ":", "err", "=", "ErrServerError", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "me", "[", "i", "]", "=", "err", "\n", "any", "=", "true", "\n", "}", "\n", "}", "\n", "if", "any", "{", "return", "me", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// set sets the given items using the given conflict resolution policy. // appengine.MultiError may be returned.
[ "set", "sets", "the", "given", "items", "using", "the", "given", "conflict", "resolution", "policy", ".", "appengine", ".", "MultiError", "may", "be", "returned", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L239-L314
test
golang/appengine
memcache/memcache.go
Get
func (cd Codec) Get(c context.Context, key string, v interface{}) (*Item, error) { i, err := Get(c, key) if err != nil { return nil, err } if err := cd.Unmarshal(i.Value, v); err != nil { return nil, err } return i, nil }
go
func (cd Codec) Get(c context.Context, key string, v interface{}) (*Item, error) { i, err := Get(c, key) if err != nil { return nil, err } if err := cd.Unmarshal(i.Value, v); err != nil { return nil, err } return i, nil }
[ "func", "(", "cd", "Codec", ")", "Get", "(", "c", "context", ".", "Context", ",", "key", "string", ",", "v", "interface", "{", "}", ")", "(", "*", "Item", ",", "error", ")", "{", "i", ",", "err", ":=", "Get", "(", "c", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "cd", ".", "Unmarshal", "(", "i", ".", "Value", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "i", ",", "nil", "\n", "}" ]
// Get gets the item for the given key and decodes the obtained value into v. // ErrCacheMiss is returned for a memcache cache miss. // The key must be at most 250 bytes in length.
[ "Get", "gets", "the", "item", "for", "the", "given", "key", "and", "decodes", "the", "obtained", "value", "into", "v", ".", "ErrCacheMiss", "is", "returned", "for", "a", "memcache", "cache", "miss", ".", "The", "key", "must", "be", "at", "most", "250", "bytes", "in", "length", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L369-L378
test
golang/appengine
memcache/memcache.go
Stats
func Stats(c context.Context) (*Statistics, error) { req := &pb.MemcacheStatsRequest{} res := &pb.MemcacheStatsResponse{} if err := internal.Call(c, "memcache", "Stats", req, res); err != nil { return nil, err } if res.Stats == nil { return nil, ErrNoStats } return &Statistics{ Hits: *res.Stats.Hits, Misses: *res.Stats.Misses, ByteHits: *res.Stats.ByteHits, Items: *res.Stats.Items, Bytes: *res.Stats.Bytes, Oldest: int64(*res.Stats.OldestItemAge), }, nil }
go
func Stats(c context.Context) (*Statistics, error) { req := &pb.MemcacheStatsRequest{} res := &pb.MemcacheStatsResponse{} if err := internal.Call(c, "memcache", "Stats", req, res); err != nil { return nil, err } if res.Stats == nil { return nil, ErrNoStats } return &Statistics{ Hits: *res.Stats.Hits, Misses: *res.Stats.Misses, ByteHits: *res.Stats.ByteHits, Items: *res.Stats.Items, Bytes: *res.Stats.Bytes, Oldest: int64(*res.Stats.OldestItemAge), }, nil }
[ "func", "Stats", "(", "c", "context", ".", "Context", ")", "(", "*", "Statistics", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "MemcacheStatsRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "MemcacheStatsResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"memcache\"", ",", "\"Stats\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "res", ".", "Stats", "==", "nil", "{", "return", "nil", ",", "ErrNoStats", "\n", "}", "\n", "return", "&", "Statistics", "{", "Hits", ":", "*", "res", ".", "Stats", ".", "Hits", ",", "Misses", ":", "*", "res", ".", "Stats", ".", "Misses", ",", "ByteHits", ":", "*", "res", ".", "Stats", ".", "ByteHits", ",", "Items", ":", "*", "res", ".", "Stats", ".", "Items", ",", "Bytes", ":", "*", "res", ".", "Stats", ".", "Bytes", ",", "Oldest", ":", "int64", "(", "*", "res", ".", "Stats", ".", "OldestItemAge", ")", ",", "}", ",", "nil", "\n", "}" ]
// Stats retrieves the current memcache statistics.
[ "Stats", "retrieves", "the", "current", "memcache", "statistics", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L475-L492
test
golang/appengine
memcache/memcache.go
Flush
func Flush(c context.Context) error { req := &pb.MemcacheFlushRequest{} res := &pb.MemcacheFlushResponse{} return internal.Call(c, "memcache", "FlushAll", req, res) }
go
func Flush(c context.Context) error { req := &pb.MemcacheFlushRequest{} res := &pb.MemcacheFlushResponse{} return internal.Call(c, "memcache", "FlushAll", req, res) }
[ "func", "Flush", "(", "c", "context", ".", "Context", ")", "error", "{", "req", ":=", "&", "pb", ".", "MemcacheFlushRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "MemcacheFlushResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"memcache\"", ",", "\"FlushAll\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Flush flushes all items from memcache.
[ "Flush", "flushes", "all", "items", "from", "memcache", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L495-L499
test
golang/appengine
runtime/runtime.go
RunInBackground
func RunInBackground(c context.Context, f func(c context.Context)) error { req := &pb.StartBackgroundRequestRequest{} res := &pb.StartBackgroundRequestResponse{} if err := internal.Call(c, "system", "StartBackgroundRequest", req, res); err != nil { return err } sendc <- send{res.GetRequestId(), f} return nil }
go
func RunInBackground(c context.Context, f func(c context.Context)) error { req := &pb.StartBackgroundRequestRequest{} res := &pb.StartBackgroundRequestResponse{} if err := internal.Call(c, "system", "StartBackgroundRequest", req, res); err != nil { return err } sendc <- send{res.GetRequestId(), f} return nil }
[ "func", "RunInBackground", "(", "c", "context", ".", "Context", ",", "f", "func", "(", "c", "context", ".", "Context", ")", ")", "error", "{", "req", ":=", "&", "pb", ".", "StartBackgroundRequestRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "StartBackgroundRequestResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"system\"", ",", "\"StartBackgroundRequest\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sendc", "<-", "send", "{", "res", ".", "GetRequestId", "(", ")", ",", "f", "}", "\n", "return", "nil", "\n", "}" ]
// RunInBackground runs f in a background goroutine in this process. // f is provided a context that may outlast the context provided to RunInBackground. // This is only valid to invoke from a service set to basic or manual scaling.
[ "RunInBackground", "runs", "f", "in", "a", "background", "goroutine", "in", "this", "process", ".", "f", "is", "provided", "a", "context", "that", "may", "outlast", "the", "context", "provided", "to", "RunInBackground", ".", "This", "is", "only", "valid", "to", "invoke", "from", "a", "service", "set", "to", "basic", "or", "manual", "scaling", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/runtime/runtime.go#L136-L144
test
golang/appengine
module/module.go
List
func List(c context.Context) ([]string, error) { req := &pb.GetModulesRequest{} res := &pb.GetModulesResponse{} err := internal.Call(c, "modules", "GetModules", req, res) return res.Module, err }
go
func List(c context.Context) ([]string, error) { req := &pb.GetModulesRequest{} res := &pb.GetModulesResponse{} err := internal.Call(c, "modules", "GetModules", req, res) return res.Module, err }
[ "func", "List", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetModulesRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "GetModulesResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"GetModules\"", ",", "req", ",", "res", ")", "\n", "return", "res", ".", "Module", ",", "err", "\n", "}" ]
// List returns the names of modules belonging to this application.
[ "List", "returns", "the", "names", "of", "modules", "belonging", "to", "this", "application", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L22-L27
test
golang/appengine
module/module.go
SetNumInstances
func SetNumInstances(c context.Context, module, version string, instances int) error { req := &pb.SetNumInstancesRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } req.Instances = proto.Int64(int64(instances)) res := &pb.SetNumInstancesResponse{} return internal.Call(c, "modules", "SetNumInstances", req, res) }
go
func SetNumInstances(c context.Context, module, version string, instances int) error { req := &pb.SetNumInstancesRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } req.Instances = proto.Int64(int64(instances)) res := &pb.SetNumInstancesResponse{} return internal.Call(c, "modules", "SetNumInstances", req, res) }
[ "func", "SetNumInstances", "(", "c", "context", ".", "Context", ",", "module", ",", "version", "string", ",", "instances", "int", ")", "error", "{", "req", ":=", "&", "pb", ".", "SetNumInstancesRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "if", "version", "!=", "\"\"", "{", "req", ".", "Version", "=", "&", "version", "\n", "}", "\n", "req", ".", "Instances", "=", "proto", ".", "Int64", "(", "int64", "(", "instances", ")", ")", "\n", "res", ":=", "&", "pb", ".", "SetNumInstancesResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"SetNumInstances\"", ",", "req", ",", "res", ")", "\n", "}" ]
// SetNumInstances sets the number of instances of the given module.version to the // specified value. If either module or version are the empty string it means the // default.
[ "SetNumInstances", "sets", "the", "number", "of", "instances", "of", "the", "given", "module", ".", "version", "to", "the", "specified", "value", ".", "If", "either", "module", "or", "version", "are", "the", "empty", "string", "it", "means", "the", "default", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L50-L61
test
golang/appengine
module/module.go
Versions
func Versions(c context.Context, module string) ([]string, error) { req := &pb.GetVersionsRequest{} if module != "" { req.Module = &module } res := &pb.GetVersionsResponse{} err := internal.Call(c, "modules", "GetVersions", req, res) return res.GetVersion(), err }
go
func Versions(c context.Context, module string) ([]string, error) { req := &pb.GetVersionsRequest{} if module != "" { req.Module = &module } res := &pb.GetVersionsResponse{} err := internal.Call(c, "modules", "GetVersions", req, res) return res.GetVersion(), err }
[ "func", "Versions", "(", "c", "context", ".", "Context", ",", "module", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetVersionsRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "GetVersionsResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"GetVersions\"", ",", "req", ",", "res", ")", "\n", "return", "res", ".", "GetVersion", "(", ")", ",", "err", "\n", "}" ]
// Versions returns the names of the versions that belong to the specified module. // If module is the empty string, it means the default module.
[ "Versions", "returns", "the", "names", "of", "the", "versions", "that", "belong", "to", "the", "specified", "module", ".", "If", "module", "is", "the", "empty", "string", "it", "means", "the", "default", "module", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L65-L73
test
golang/appengine
module/module.go
DefaultVersion
func DefaultVersion(c context.Context, module string) (string, error) { req := &pb.GetDefaultVersionRequest{} if module != "" { req.Module = &module } res := &pb.GetDefaultVersionResponse{} err := internal.Call(c, "modules", "GetDefaultVersion", req, res) return res.GetVersion(), err }
go
func DefaultVersion(c context.Context, module string) (string, error) { req := &pb.GetDefaultVersionRequest{} if module != "" { req.Module = &module } res := &pb.GetDefaultVersionResponse{} err := internal.Call(c, "modules", "GetDefaultVersion", req, res) return res.GetVersion(), err }
[ "func", "DefaultVersion", "(", "c", "context", ".", "Context", ",", "module", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetDefaultVersionRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "GetDefaultVersionResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"GetDefaultVersion\"", ",", "req", ",", "res", ")", "\n", "return", "res", ".", "GetVersion", "(", ")", ",", "err", "\n", "}" ]
// DefaultVersion returns the default version of the specified module. // If module is the empty string, it means the default module.
[ "DefaultVersion", "returns", "the", "default", "version", "of", "the", "specified", "module", ".", "If", "module", "is", "the", "empty", "string", "it", "means", "the", "default", "module", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L77-L85
test
golang/appengine
module/module.go
Start
func Start(c context.Context, module, version string) error { req := &pb.StartModuleRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } res := &pb.StartModuleResponse{} return internal.Call(c, "modules", "StartModule", req, res) }
go
func Start(c context.Context, module, version string) error { req := &pb.StartModuleRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } res := &pb.StartModuleResponse{} return internal.Call(c, "modules", "StartModule", req, res) }
[ "func", "Start", "(", "c", "context", ".", "Context", ",", "module", ",", "version", "string", ")", "error", "{", "req", ":=", "&", "pb", ".", "StartModuleRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "if", "version", "!=", "\"\"", "{", "req", ".", "Version", "=", "&", "version", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "StartModuleResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"StartModule\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Start starts the specified version of the specified module. // If either module or version are the empty string, it means the default.
[ "Start", "starts", "the", "specified", "version", "of", "the", "specified", "module", ".", "If", "either", "module", "or", "version", "are", "the", "empty", "string", "it", "means", "the", "default", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L89-L99
test
golang/appengine
module/module.go
Stop
func Stop(c context.Context, module, version string) error { req := &pb.StopModuleRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } res := &pb.StopModuleResponse{} return internal.Call(c, "modules", "StopModule", req, res) }
go
func Stop(c context.Context, module, version string) error { req := &pb.StopModuleRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } res := &pb.StopModuleResponse{} return internal.Call(c, "modules", "StopModule", req, res) }
[ "func", "Stop", "(", "c", "context", ".", "Context", ",", "module", ",", "version", "string", ")", "error", "{", "req", ":=", "&", "pb", ".", "StopModuleRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "if", "version", "!=", "\"\"", "{", "req", ".", "Version", "=", "&", "version", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "StopModuleResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"StopModule\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Stop stops the specified version of the specified module. // If either module or version are the empty string, it means the default.
[ "Stop", "stops", "the", "specified", "version", "of", "the", "specified", "module", ".", "If", "either", "module", "or", "version", "are", "the", "empty", "string", "it", "means", "the", "default", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L103-L113
test
golang/appengine
datastore/query.go
Ancestor
func (q *Query) Ancestor(ancestor *Key) *Query { q = q.clone() if ancestor == nil { q.err = errors.New("datastore: nil query ancestor") return q } q.ancestor = ancestor return q }
go
func (q *Query) Ancestor(ancestor *Key) *Query { q = q.clone() if ancestor == nil { q.err = errors.New("datastore: nil query ancestor") return q } q.ancestor = ancestor return q }
[ "func", "(", "q", "*", "Query", ")", "Ancestor", "(", "ancestor", "*", "Key", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "ancestor", "==", "nil", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: nil query ancestor\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "ancestor", "=", "ancestor", "\n", "return", "q", "\n", "}" ]
// Ancestor returns a derivative query with an ancestor filter. // The ancestor should not be nil.
[ "Ancestor", "returns", "a", "derivative", "query", "with", "an", "ancestor", "filter", ".", "The", "ancestor", "should", "not", "be", "nil", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L114-L122
test
golang/appengine
datastore/query.go
EventualConsistency
func (q *Query) EventualConsistency() *Query { q = q.clone() q.eventual = true return q }
go
func (q *Query) EventualConsistency() *Query { q = q.clone() q.eventual = true return q }
[ "func", "(", "q", "*", "Query", ")", "EventualConsistency", "(", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "q", ".", "eventual", "=", "true", "\n", "return", "q", "\n", "}" ]
// EventualConsistency returns a derivative query that returns eventually // consistent results. // It only has an effect on ancestor queries.
[ "EventualConsistency", "returns", "a", "derivative", "query", "that", "returns", "eventually", "consistent", "results", ".", "It", "only", "has", "an", "effect", "on", "ancestor", "queries", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L127-L131
test
golang/appengine
datastore/query.go
Project
func (q *Query) Project(fieldNames ...string) *Query { q = q.clone() q.projection = append([]string(nil), fieldNames...) return q }
go
func (q *Query) Project(fieldNames ...string) *Query { q = q.clone() q.projection = append([]string(nil), fieldNames...) return q }
[ "func", "(", "q", "*", "Query", ")", "Project", "(", "fieldNames", "...", "string", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "q", ".", "projection", "=", "append", "(", "[", "]", "string", "(", "nil", ")", ",", "fieldNames", "...", ")", "\n", "return", "q", "\n", "}" ]
// Project returns a derivative query that yields only the given fields. It // cannot be used with KeysOnly.
[ "Project", "returns", "a", "derivative", "query", "that", "yields", "only", "the", "given", "fields", ".", "It", "cannot", "be", "used", "with", "KeysOnly", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L195-L199
test
golang/appengine
datastore/query.go
Distinct
func (q *Query) Distinct() *Query { q = q.clone() q.distinct = true return q }
go
func (q *Query) Distinct() *Query { q = q.clone() q.distinct = true return q }
[ "func", "(", "q", "*", "Query", ")", "Distinct", "(", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "q", ".", "distinct", "=", "true", "\n", "return", "q", "\n", "}" ]
// Distinct returns a derivative query that yields de-duplicated entities with // respect to the set of projected fields. It is only used for projection // queries. Distinct cannot be used with DistinctOn.
[ "Distinct", "returns", "a", "derivative", "query", "that", "yields", "de", "-", "duplicated", "entities", "with", "respect", "to", "the", "set", "of", "projected", "fields", ".", "It", "is", "only", "used", "for", "projection", "queries", ".", "Distinct", "cannot", "be", "used", "with", "DistinctOn", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L204-L208
test
golang/appengine
datastore/query.go
DistinctOn
func (q *Query) DistinctOn(fieldNames ...string) *Query { q = q.clone() q.distinctOn = fieldNames return q }
go
func (q *Query) DistinctOn(fieldNames ...string) *Query { q = q.clone() q.distinctOn = fieldNames return q }
[ "func", "(", "q", "*", "Query", ")", "DistinctOn", "(", "fieldNames", "...", "string", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "q", ".", "distinctOn", "=", "fieldNames", "\n", "return", "q", "\n", "}" ]
// DistinctOn returns a derivative query that yields de-duplicated entities with // respect to the set of the specified fields. It is only used for projection // queries. The field list should be a subset of the projected field list. // DistinctOn cannot be used with Distinct.
[ "DistinctOn", "returns", "a", "derivative", "query", "that", "yields", "de", "-", "duplicated", "entities", "with", "respect", "to", "the", "set", "of", "the", "specified", "fields", ".", "It", "is", "only", "used", "for", "projection", "queries", ".", "The", "field", "list", "should", "be", "a", "subset", "of", "the", "projected", "field", "list", ".", "DistinctOn", "cannot", "be", "used", "with", "Distinct", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L214-L218
test
golang/appengine
datastore/query.go
KeysOnly
func (q *Query) KeysOnly() *Query { q = q.clone() q.keysOnly = true return q }
go
func (q *Query) KeysOnly() *Query { q = q.clone() q.keysOnly = true return q }
[ "func", "(", "q", "*", "Query", ")", "KeysOnly", "(", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "q", ".", "keysOnly", "=", "true", "\n", "return", "q", "\n", "}" ]
// KeysOnly returns a derivative query that yields only keys, not keys and // entities. It cannot be used with projection queries.
[ "KeysOnly", "returns", "a", "derivative", "query", "that", "yields", "only", "keys", "not", "keys", "and", "entities", ".", "It", "cannot", "be", "used", "with", "projection", "queries", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L222-L226
test
golang/appengine
datastore/query.go
Limit
func (q *Query) Limit(limit int) *Query { q = q.clone() if limit < math.MinInt32 || limit > math.MaxInt32 { q.err = errors.New("datastore: query limit overflow") return q } q.limit = int32(limit) return q }
go
func (q *Query) Limit(limit int) *Query { q = q.clone() if limit < math.MinInt32 || limit > math.MaxInt32 { q.err = errors.New("datastore: query limit overflow") return q } q.limit = int32(limit) return q }
[ "func", "(", "q", "*", "Query", ")", "Limit", "(", "limit", "int", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "limit", "<", "math", ".", "MinInt32", "||", "limit", ">", "math", ".", "MaxInt32", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: query limit overflow\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "limit", "=", "int32", "(", "limit", ")", "\n", "return", "q", "\n", "}" ]
// Limit returns a derivative query that has a limit on the number of results // returned. A negative value means unlimited.
[ "Limit", "returns", "a", "derivative", "query", "that", "has", "a", "limit", "on", "the", "number", "of", "results", "returned", ".", "A", "negative", "value", "means", "unlimited", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L230-L238
test
golang/appengine
datastore/query.go
Offset
func (q *Query) Offset(offset int) *Query { q = q.clone() if offset < 0 { q.err = errors.New("datastore: negative query offset") return q } if offset > math.MaxInt32 { q.err = errors.New("datastore: query offset overflow") return q } q.offset = int32(offset) return q }
go
func (q *Query) Offset(offset int) *Query { q = q.clone() if offset < 0 { q.err = errors.New("datastore: negative query offset") return q } if offset > math.MaxInt32 { q.err = errors.New("datastore: query offset overflow") return q } q.offset = int32(offset) return q }
[ "func", "(", "q", "*", "Query", ")", "Offset", "(", "offset", "int", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "offset", "<", "0", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: negative query offset\"", ")", "\n", "return", "q", "\n", "}", "\n", "if", "offset", ">", "math", ".", "MaxInt32", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: query offset overflow\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "offset", "=", "int32", "(", "offset", ")", "\n", "return", "q", "\n", "}" ]
// Offset returns a derivative query that has an offset of how many keys to // skip over before returning results. A negative value is invalid.
[ "Offset", "returns", "a", "derivative", "query", "that", "has", "an", "offset", "of", "how", "many", "keys", "to", "skip", "over", "before", "returning", "results", ".", "A", "negative", "value", "is", "invalid", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L242-L254
test
golang/appengine
datastore/query.go
BatchSize
func (q *Query) BatchSize(size int) *Query { q = q.clone() if size <= 0 || size > math.MaxInt32 { q.err = errors.New("datastore: query batch size overflow") return q } q.count = int32(size) return q }
go
func (q *Query) BatchSize(size int) *Query { q = q.clone() if size <= 0 || size > math.MaxInt32 { q.err = errors.New("datastore: query batch size overflow") return q } q.count = int32(size) return q }
[ "func", "(", "q", "*", "Query", ")", "BatchSize", "(", "size", "int", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "size", "<=", "0", "||", "size", ">", "math", ".", "MaxInt32", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: query batch size overflow\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "count", "=", "int32", "(", "size", ")", "\n", "return", "q", "\n", "}" ]
// BatchSize returns a derivative query to fetch the supplied number of results // at once. This value should be greater than zero, and equal to or less than // the Limit.
[ "BatchSize", "returns", "a", "derivative", "query", "to", "fetch", "the", "supplied", "number", "of", "results", "at", "once", ".", "This", "value", "should", "be", "greater", "than", "zero", "and", "equal", "to", "or", "less", "than", "the", "Limit", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L259-L267
test
golang/appengine
datastore/query.go
Start
func (q *Query) Start(c Cursor) *Query { q = q.clone() if c.cc == nil { q.err = errors.New("datastore: invalid cursor") return q } q.start = c.cc return q }
go
func (q *Query) Start(c Cursor) *Query { q = q.clone() if c.cc == nil { q.err = errors.New("datastore: invalid cursor") return q } q.start = c.cc return q }
[ "func", "(", "q", "*", "Query", ")", "Start", "(", "c", "Cursor", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "c", ".", "cc", "==", "nil", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: invalid cursor\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "start", "=", "c", ".", "cc", "\n", "return", "q", "\n", "}" ]
// Start returns a derivative query with the given start point.
[ "Start", "returns", "a", "derivative", "query", "with", "the", "given", "start", "point", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L270-L278
test
golang/appengine
datastore/query.go
End
func (q *Query) End(c Cursor) *Query { q = q.clone() if c.cc == nil { q.err = errors.New("datastore: invalid cursor") return q } q.end = c.cc return q }
go
func (q *Query) End(c Cursor) *Query { q = q.clone() if c.cc == nil { q.err = errors.New("datastore: invalid cursor") return q } q.end = c.cc return q }
[ "func", "(", "q", "*", "Query", ")", "End", "(", "c", "Cursor", ")", "*", "Query", "{", "q", "=", "q", ".", "clone", "(", ")", "\n", "if", "c", ".", "cc", "==", "nil", "{", "q", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: invalid cursor\"", ")", "\n", "return", "q", "\n", "}", "\n", "q", ".", "end", "=", "c", ".", "cc", "\n", "return", "q", "\n", "}" ]
// End returns a derivative query with the given end point.
[ "End", "returns", "a", "derivative", "query", "with", "the", "given", "end", "point", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L281-L289
test
golang/appengine
datastore/query.go
Count
func (q *Query) Count(c context.Context) (int, error) { // Check that the query is well-formed. if q.err != nil { return 0, q.err } // Run a copy of the query, with keysOnly true (if we're not a projection, // since the two are incompatible), and an adjusted offset. We also set the // limit to zero, as we don't want any actual entity data, just the number // of skipped results. newQ := q.clone() newQ.keysOnly = len(newQ.projection) == 0 newQ.limit = 0 if q.limit < 0 { // If the original query was unlimited, set the new query's offset to maximum. newQ.offset = math.MaxInt32 } else { newQ.offset = q.offset + q.limit if newQ.offset < 0 { // Do the best we can, in the presence of overflow. newQ.offset = math.MaxInt32 } } req := &pb.Query{} if err := newQ.toProto(req, internal.FullyQualifiedAppID(c)); err != nil { return 0, err } res := &pb.QueryResult{} if err := internal.Call(c, "datastore_v3", "RunQuery", req, res); err != nil { return 0, err } // n is the count we will return. For example, suppose that our original // query had an offset of 4 and a limit of 2008: the count will be 2008, // provided that there are at least 2012 matching entities. However, the // RPCs will only skip 1000 results at a time. The RPC sequence is: // call RunQuery with (offset, limit) = (2012, 0) // 2012 == newQ.offset // response has (skippedResults, moreResults) = (1000, true) // n += 1000 // n == 1000 // call Next with (offset, limit) = (1012, 0) // 1012 == newQ.offset - n // response has (skippedResults, moreResults) = (1000, true) // n += 1000 // n == 2000 // call Next with (offset, limit) = (12, 0) // 12 == newQ.offset - n // response has (skippedResults, moreResults) = (12, false) // n += 12 // n == 2012 // // exit the loop // n -= 4 // n == 2008 var n int32 for { // The QueryResult should have no actual entity data, just skipped results. if len(res.Result) != 0 { return 0, errors.New("datastore: internal error: Count request returned too much data") } n += res.GetSkippedResults() if !res.GetMoreResults() { break } if err := callNext(c, res, newQ.offset-n, q.count); err != nil { return 0, err } } n -= q.offset if n < 0 { // If the offset was greater than the number of matching entities, // return 0 instead of negative. n = 0 } return int(n), nil }
go
func (q *Query) Count(c context.Context) (int, error) { // Check that the query is well-formed. if q.err != nil { return 0, q.err } // Run a copy of the query, with keysOnly true (if we're not a projection, // since the two are incompatible), and an adjusted offset. We also set the // limit to zero, as we don't want any actual entity data, just the number // of skipped results. newQ := q.clone() newQ.keysOnly = len(newQ.projection) == 0 newQ.limit = 0 if q.limit < 0 { // If the original query was unlimited, set the new query's offset to maximum. newQ.offset = math.MaxInt32 } else { newQ.offset = q.offset + q.limit if newQ.offset < 0 { // Do the best we can, in the presence of overflow. newQ.offset = math.MaxInt32 } } req := &pb.Query{} if err := newQ.toProto(req, internal.FullyQualifiedAppID(c)); err != nil { return 0, err } res := &pb.QueryResult{} if err := internal.Call(c, "datastore_v3", "RunQuery", req, res); err != nil { return 0, err } // n is the count we will return. For example, suppose that our original // query had an offset of 4 and a limit of 2008: the count will be 2008, // provided that there are at least 2012 matching entities. However, the // RPCs will only skip 1000 results at a time. The RPC sequence is: // call RunQuery with (offset, limit) = (2012, 0) // 2012 == newQ.offset // response has (skippedResults, moreResults) = (1000, true) // n += 1000 // n == 1000 // call Next with (offset, limit) = (1012, 0) // 1012 == newQ.offset - n // response has (skippedResults, moreResults) = (1000, true) // n += 1000 // n == 2000 // call Next with (offset, limit) = (12, 0) // 12 == newQ.offset - n // response has (skippedResults, moreResults) = (12, false) // n += 12 // n == 2012 // // exit the loop // n -= 4 // n == 2008 var n int32 for { // The QueryResult should have no actual entity data, just skipped results. if len(res.Result) != 0 { return 0, errors.New("datastore: internal error: Count request returned too much data") } n += res.GetSkippedResults() if !res.GetMoreResults() { break } if err := callNext(c, res, newQ.offset-n, q.count); err != nil { return 0, err } } n -= q.offset if n < 0 { // If the offset was greater than the number of matching entities, // return 0 instead of negative. n = 0 } return int(n), nil }
[ "func", "(", "q", "*", "Query", ")", "Count", "(", "c", "context", ".", "Context", ")", "(", "int", ",", "error", ")", "{", "if", "q", ".", "err", "!=", "nil", "{", "return", "0", ",", "q", ".", "err", "\n", "}", "\n", "newQ", ":=", "q", ".", "clone", "(", ")", "\n", "newQ", ".", "keysOnly", "=", "len", "(", "newQ", ".", "projection", ")", "==", "0", "\n", "newQ", ".", "limit", "=", "0", "\n", "if", "q", ".", "limit", "<", "0", "{", "newQ", ".", "offset", "=", "math", ".", "MaxInt32", "\n", "}", "else", "{", "newQ", ".", "offset", "=", "q", ".", "offset", "+", "q", ".", "limit", "\n", "if", "newQ", ".", "offset", "<", "0", "{", "newQ", ".", "offset", "=", "math", ".", "MaxInt32", "\n", "}", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "Query", "{", "}", "\n", "if", "err", ":=", "newQ", ".", "toProto", "(", "req", ",", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "QueryResult", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"datastore_v3\"", ",", "\"RunQuery\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "var", "n", "int32", "\n", "for", "{", "if", "len", "(", "res", ".", "Result", ")", "!=", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"datastore: internal error: Count request returned too much data\"", ")", "\n", "}", "\n", "n", "+=", "res", ".", "GetSkippedResults", "(", ")", "\n", "if", "!", "res", ".", "GetMoreResults", "(", ")", "{", "break", "\n", "}", "\n", "if", "err", ":=", "callNext", "(", "c", ",", "res", ",", "newQ", ".", "offset", "-", "n", ",", "q", ".", "count", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "n", "-=", "q", ".", "offset", "\n", "if", "n", "<", "0", "{", "n", "=", "0", "\n", "}", "\n", "return", "int", "(", "n", ")", ",", "nil", "\n", "}" ]
// Count returns the number of results for the query. // // The running time and number of API calls made by Count scale linearly with // the sum of the query's offset and limit. Unless the result count is // expected to be small, it is best to specify a limit; otherwise Count will // continue until it finishes counting or the provided context expires.
[ "Count", "returns", "the", "number", "of", "results", "for", "the", "query", ".", "The", "running", "time", "and", "number", "of", "API", "calls", "made", "by", "Count", "scale", "linearly", "with", "the", "sum", "of", "the", "query", "s", "offset", "and", "limit", ".", "Unless", "the", "result", "count", "is", "expected", "to", "be", "small", "it", "is", "best", "to", "specify", "a", "limit", ";", "otherwise", "Count", "will", "continue", "until", "it", "finishes", "counting", "or", "the", "provided", "context", "expires", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L374-L442
test
golang/appengine
datastore/query.go
Run
func (q *Query) Run(c context.Context) *Iterator { if q.err != nil { return &Iterator{err: q.err} } t := &Iterator{ c: c, limit: q.limit, count: q.count, q: q, prevCC: q.start, } var req pb.Query if err := q.toProto(&req, internal.FullyQualifiedAppID(c)); err != nil { t.err = err return t } if err := internal.Call(c, "datastore_v3", "RunQuery", &req, &t.res); err != nil { t.err = err return t } offset := q.offset - t.res.GetSkippedResults() var count int32 if t.count > 0 && (t.limit < 0 || t.count < t.limit) { count = t.count } else { count = t.limit } for offset > 0 && t.res.GetMoreResults() { t.prevCC = t.res.CompiledCursor if err := callNext(t.c, &t.res, offset, count); err != nil { t.err = err break } skip := t.res.GetSkippedResults() if skip < 0 { t.err = errors.New("datastore: internal error: negative number of skipped_results") break } offset -= skip } if offset < 0 { t.err = errors.New("datastore: internal error: query offset was overshot") } return t }
go
func (q *Query) Run(c context.Context) *Iterator { if q.err != nil { return &Iterator{err: q.err} } t := &Iterator{ c: c, limit: q.limit, count: q.count, q: q, prevCC: q.start, } var req pb.Query if err := q.toProto(&req, internal.FullyQualifiedAppID(c)); err != nil { t.err = err return t } if err := internal.Call(c, "datastore_v3", "RunQuery", &req, &t.res); err != nil { t.err = err return t } offset := q.offset - t.res.GetSkippedResults() var count int32 if t.count > 0 && (t.limit < 0 || t.count < t.limit) { count = t.count } else { count = t.limit } for offset > 0 && t.res.GetMoreResults() { t.prevCC = t.res.CompiledCursor if err := callNext(t.c, &t.res, offset, count); err != nil { t.err = err break } skip := t.res.GetSkippedResults() if skip < 0 { t.err = errors.New("datastore: internal error: negative number of skipped_results") break } offset -= skip } if offset < 0 { t.err = errors.New("datastore: internal error: query offset was overshot") } return t }
[ "func", "(", "q", "*", "Query", ")", "Run", "(", "c", "context", ".", "Context", ")", "*", "Iterator", "{", "if", "q", ".", "err", "!=", "nil", "{", "return", "&", "Iterator", "{", "err", ":", "q", ".", "err", "}", "\n", "}", "\n", "t", ":=", "&", "Iterator", "{", "c", ":", "c", ",", "limit", ":", "q", ".", "limit", ",", "count", ":", "q", ".", "count", ",", "q", ":", "q", ",", "prevCC", ":", "q", ".", "start", ",", "}", "\n", "var", "req", "pb", ".", "Query", "\n", "if", "err", ":=", "q", ".", "toProto", "(", "&", "req", ",", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", ")", ";", "err", "!=", "nil", "{", "t", ".", "err", "=", "err", "\n", "return", "t", "\n", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"datastore_v3\"", ",", "\"RunQuery\"", ",", "&", "req", ",", "&", "t", ".", "res", ")", ";", "err", "!=", "nil", "{", "t", ".", "err", "=", "err", "\n", "return", "t", "\n", "}", "\n", "offset", ":=", "q", ".", "offset", "-", "t", ".", "res", ".", "GetSkippedResults", "(", ")", "\n", "var", "count", "int32", "\n", "if", "t", ".", "count", ">", "0", "&&", "(", "t", ".", "limit", "<", "0", "||", "t", ".", "count", "<", "t", ".", "limit", ")", "{", "count", "=", "t", ".", "count", "\n", "}", "else", "{", "count", "=", "t", ".", "limit", "\n", "}", "\n", "for", "offset", ">", "0", "&&", "t", ".", "res", ".", "GetMoreResults", "(", ")", "{", "t", ".", "prevCC", "=", "t", ".", "res", ".", "CompiledCursor", "\n", "if", "err", ":=", "callNext", "(", "t", ".", "c", ",", "&", "t", ".", "res", ",", "offset", ",", "count", ")", ";", "err", "!=", "nil", "{", "t", ".", "err", "=", "err", "\n", "break", "\n", "}", "\n", "skip", ":=", "t", ".", "res", ".", "GetSkippedResults", "(", ")", "\n", "if", "skip", "<", "0", "{", "t", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: internal error: negative number of skipped_results\"", ")", "\n", "break", "\n", "}", "\n", "offset", "-=", "skip", "\n", "}", "\n", "if", "offset", "<", "0", "{", "t", ".", "err", "=", "errors", ".", "New", "(", "\"datastore: internal error: query offset was overshot\"", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// Run runs the query in the given context.
[ "Run", "runs", "the", "query", "in", "the", "given", "context", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L553-L597
test
golang/appengine
datastore/query.go
Next
func (t *Iterator) Next(dst interface{}) (*Key, error) { k, e, err := t.next() if err != nil { return nil, err } if dst != nil && !t.q.keysOnly { err = loadEntity(dst, e) } return k, err }
go
func (t *Iterator) Next(dst interface{}) (*Key, error) { k, e, err := t.next() if err != nil { return nil, err } if dst != nil && !t.q.keysOnly { err = loadEntity(dst, e) } return k, err }
[ "func", "(", "t", "*", "Iterator", ")", "Next", "(", "dst", "interface", "{", "}", ")", "(", "*", "Key", ",", "error", ")", "{", "k", ",", "e", ",", "err", ":=", "t", ".", "next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "dst", "!=", "nil", "&&", "!", "t", ".", "q", ".", "keysOnly", "{", "err", "=", "loadEntity", "(", "dst", ",", "e", ")", "\n", "}", "\n", "return", "k", ",", "err", "\n", "}" ]
// Next returns the key of the next result. When there are no more results, // Done is returned as the error. // // If the query is not keys only and dst is non-nil, it also loads the entity // stored for that key into the struct pointer or PropertyLoadSaver dst, with // the same semantics and possible errors as for the Get function.
[ "Next", "returns", "the", "key", "of", "the", "next", "result", ".", "When", "there", "are", "no", "more", "results", "Done", "is", "returned", "as", "the", "error", ".", "If", "the", "query", "is", "not", "keys", "only", "and", "dst", "is", "non", "-", "nil", "it", "also", "loads", "the", "entity", "stored", "for", "that", "key", "into", "the", "struct", "pointer", "or", "PropertyLoadSaver", "dst", "with", "the", "same", "semantics", "and", "possible", "errors", "as", "for", "the", "Get", "function", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L629-L638
test
golang/appengine
datastore/query.go
Cursor
func (t *Iterator) Cursor() (Cursor, error) { if t.err != nil && t.err != Done { return Cursor{}, t.err } // If we are at either end of the current batch of results, // return the compiled cursor at that end. skipped := t.res.GetSkippedResults() if t.i == 0 && skipped == 0 { if t.prevCC == nil { // A nil pointer (of type *pb.CompiledCursor) means no constraint: // passing it as the end cursor of a new query means unlimited results // (glossing over the integer limit parameter for now). // A non-nil pointer to an empty pb.CompiledCursor means the start: // passing it as the end cursor of a new query means 0 results. // If prevCC was nil, then the original query had no start cursor, but // Iterator.Cursor should return "the start" instead of unlimited. return Cursor{&zeroCC}, nil } return Cursor{t.prevCC}, nil } if t.i == len(t.res.Result) { return Cursor{t.res.CompiledCursor}, nil } // Otherwise, re-run the query offset to this iterator's position, starting from // the most recent compiled cursor. This is done on a best-effort basis, as it // is racy; if a concurrent process has added or removed entities, then the // cursor returned may be inconsistent. q := t.q.clone() q.start = t.prevCC q.offset = skipped + int32(t.i) q.limit = 0 q.keysOnly = len(q.projection) == 0 t1 := q.Run(t.c) _, _, err := t1.next() if err != Done { if err == nil { err = fmt.Errorf("datastore: internal error: zero-limit query did not have zero results") } return Cursor{}, err } return Cursor{t1.res.CompiledCursor}, nil }
go
func (t *Iterator) Cursor() (Cursor, error) { if t.err != nil && t.err != Done { return Cursor{}, t.err } // If we are at either end of the current batch of results, // return the compiled cursor at that end. skipped := t.res.GetSkippedResults() if t.i == 0 && skipped == 0 { if t.prevCC == nil { // A nil pointer (of type *pb.CompiledCursor) means no constraint: // passing it as the end cursor of a new query means unlimited results // (glossing over the integer limit parameter for now). // A non-nil pointer to an empty pb.CompiledCursor means the start: // passing it as the end cursor of a new query means 0 results. // If prevCC was nil, then the original query had no start cursor, but // Iterator.Cursor should return "the start" instead of unlimited. return Cursor{&zeroCC}, nil } return Cursor{t.prevCC}, nil } if t.i == len(t.res.Result) { return Cursor{t.res.CompiledCursor}, nil } // Otherwise, re-run the query offset to this iterator's position, starting from // the most recent compiled cursor. This is done on a best-effort basis, as it // is racy; if a concurrent process has added or removed entities, then the // cursor returned may be inconsistent. q := t.q.clone() q.start = t.prevCC q.offset = skipped + int32(t.i) q.limit = 0 q.keysOnly = len(q.projection) == 0 t1 := q.Run(t.c) _, _, err := t1.next() if err != Done { if err == nil { err = fmt.Errorf("datastore: internal error: zero-limit query did not have zero results") } return Cursor{}, err } return Cursor{t1.res.CompiledCursor}, nil }
[ "func", "(", "t", "*", "Iterator", ")", "Cursor", "(", ")", "(", "Cursor", ",", "error", ")", "{", "if", "t", ".", "err", "!=", "nil", "&&", "t", ".", "err", "!=", "Done", "{", "return", "Cursor", "{", "}", ",", "t", ".", "err", "\n", "}", "\n", "skipped", ":=", "t", ".", "res", ".", "GetSkippedResults", "(", ")", "\n", "if", "t", ".", "i", "==", "0", "&&", "skipped", "==", "0", "{", "if", "t", ".", "prevCC", "==", "nil", "{", "return", "Cursor", "{", "&", "zeroCC", "}", ",", "nil", "\n", "}", "\n", "return", "Cursor", "{", "t", ".", "prevCC", "}", ",", "nil", "\n", "}", "\n", "if", "t", ".", "i", "==", "len", "(", "t", ".", "res", ".", "Result", ")", "{", "return", "Cursor", "{", "t", ".", "res", ".", "CompiledCursor", "}", ",", "nil", "\n", "}", "\n", "q", ":=", "t", ".", "q", ".", "clone", "(", ")", "\n", "q", ".", "start", "=", "t", ".", "prevCC", "\n", "q", ".", "offset", "=", "skipped", "+", "int32", "(", "t", ".", "i", ")", "\n", "q", ".", "limit", "=", "0", "\n", "q", ".", "keysOnly", "=", "len", "(", "q", ".", "projection", ")", "==", "0", "\n", "t1", ":=", "q", ".", "Run", "(", "t", ".", "c", ")", "\n", "_", ",", "_", ",", "err", ":=", "t1", ".", "next", "(", ")", "\n", "if", "err", "!=", "Done", "{", "if", "err", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"datastore: internal error: zero-limit query did not have zero results\"", ")", "\n", "}", "\n", "return", "Cursor", "{", "}", ",", "err", "\n", "}", "\n", "return", "Cursor", "{", "t1", ".", "res", ".", "CompiledCursor", "}", ",", "nil", "\n", "}" ]
// Cursor returns a cursor for the iterator's current location.
[ "Cursor", "returns", "a", "cursor", "for", "the", "iterator", "s", "current", "location", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L690-L731
test
golang/appengine
datastore/query.go
String
func (c Cursor) String() string { if c.cc == nil { return "" } b, err := proto.Marshal(c.cc) if err != nil { // The only way to construct a Cursor with a non-nil cc field is to // unmarshal from the byte representation. We panic if the unmarshal // succeeds but the marshaling of the unchanged protobuf value fails. panic(fmt.Sprintf("datastore: internal error: malformed cursor: %v", err)) } return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") }
go
func (c Cursor) String() string { if c.cc == nil { return "" } b, err := proto.Marshal(c.cc) if err != nil { // The only way to construct a Cursor with a non-nil cc field is to // unmarshal from the byte representation. We panic if the unmarshal // succeeds but the marshaling of the unchanged protobuf value fails. panic(fmt.Sprintf("datastore: internal error: malformed cursor: %v", err)) } return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") }
[ "func", "(", "c", "Cursor", ")", "String", "(", ")", "string", "{", "if", "c", ".", "cc", "==", "nil", "{", "return", "\"\"", "\n", "}", "\n", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "c", ".", "cc", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"datastore: internal error: malformed cursor: %v\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "strings", ".", "TrimRight", "(", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "b", ")", ",", "\"=\"", ")", "\n", "}" ]
// String returns a base-64 string representation of a cursor.
[ "String", "returns", "a", "base", "-", "64", "string", "representation", "of", "a", "cursor", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L743-L755
test
golang/appengine
datastore/query.go
DecodeCursor
func DecodeCursor(s string) (Cursor, error) { if s == "" { return Cursor{&zeroCC}, nil } if n := len(s) % 4; n != 0 { s += strings.Repeat("=", 4-n) } b, err := base64.URLEncoding.DecodeString(s) if err != nil { return Cursor{}, err } cc := &pb.CompiledCursor{} if err := proto.Unmarshal(b, cc); err != nil { return Cursor{}, err } return Cursor{cc}, nil }
go
func DecodeCursor(s string) (Cursor, error) { if s == "" { return Cursor{&zeroCC}, nil } if n := len(s) % 4; n != 0 { s += strings.Repeat("=", 4-n) } b, err := base64.URLEncoding.DecodeString(s) if err != nil { return Cursor{}, err } cc := &pb.CompiledCursor{} if err := proto.Unmarshal(b, cc); err != nil { return Cursor{}, err } return Cursor{cc}, nil }
[ "func", "DecodeCursor", "(", "s", "string", ")", "(", "Cursor", ",", "error", ")", "{", "if", "s", "==", "\"\"", "{", "return", "Cursor", "{", "&", "zeroCC", "}", ",", "nil", "\n", "}", "\n", "if", "n", ":=", "len", "(", "s", ")", "%", "4", ";", "n", "!=", "0", "{", "s", "+=", "strings", ".", "Repeat", "(", "\"=\"", ",", "4", "-", "n", ")", "\n", "}", "\n", "b", ",", "err", ":=", "base64", ".", "URLEncoding", ".", "DecodeString", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Cursor", "{", "}", ",", "err", "\n", "}", "\n", "cc", ":=", "&", "pb", ".", "CompiledCursor", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "b", ",", "cc", ")", ";", "err", "!=", "nil", "{", "return", "Cursor", "{", "}", ",", "err", "\n", "}", "\n", "return", "Cursor", "{", "cc", "}", ",", "nil", "\n", "}" ]
// Decode decodes a cursor from its base-64 string representation.
[ "Decode", "decodes", "a", "cursor", "from", "its", "base", "-", "64", "string", "representation", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L758-L774
test
golang/appengine
datastore/save.go
saveEntity
func saveEntity(defaultAppID string, key *Key, src interface{}) (*pb.EntityProto, error) { var err error var props []Property if e, ok := src.(PropertyLoadSaver); ok { props, err = e.Save() } else { props, err = SaveStruct(src) } if err != nil { return nil, err } return propertiesToProto(defaultAppID, key, props) }
go
func saveEntity(defaultAppID string, key *Key, src interface{}) (*pb.EntityProto, error) { var err error var props []Property if e, ok := src.(PropertyLoadSaver); ok { props, err = e.Save() } else { props, err = SaveStruct(src) } if err != nil { return nil, err } return propertiesToProto(defaultAppID, key, props) }
[ "func", "saveEntity", "(", "defaultAppID", "string", ",", "key", "*", "Key", ",", "src", "interface", "{", "}", ")", "(", "*", "pb", ".", "EntityProto", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "props", "[", "]", "Property", "\n", "if", "e", ",", "ok", ":=", "src", ".", "(", "PropertyLoadSaver", ")", ";", "ok", "{", "props", ",", "err", "=", "e", ".", "Save", "(", ")", "\n", "}", "else", "{", "props", ",", "err", "=", "SaveStruct", "(", "src", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "propertiesToProto", "(", "defaultAppID", ",", "key", ",", "props", ")", "\n", "}" ]
// saveEntity saves an EntityProto into a PropertyLoadSaver or struct pointer.
[ "saveEntity", "saves", "an", "EntityProto", "into", "a", "PropertyLoadSaver", "or", "struct", "pointer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/save.go#L121-L133
test
golang/appengine
namespace.go
Namespace
func Namespace(c context.Context, namespace string) (context.Context, error) { if !validNamespace.MatchString(namespace) { return nil, fmt.Errorf("appengine: namespace %q does not match /%s/", namespace, validNamespace) } return internal.NamespacedContext(c, namespace), nil }
go
func Namespace(c context.Context, namespace string) (context.Context, error) { if !validNamespace.MatchString(namespace) { return nil, fmt.Errorf("appengine: namespace %q does not match /%s/", namespace, validNamespace) } return internal.NamespacedContext(c, namespace), nil }
[ "func", "Namespace", "(", "c", "context", ".", "Context", ",", "namespace", "string", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "if", "!", "validNamespace", ".", "MatchString", "(", "namespace", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"appengine: namespace %q does not match /%s/\"", ",", "namespace", ",", "validNamespace", ")", "\n", "}", "\n", "return", "internal", ".", "NamespacedContext", "(", "c", ",", "namespace", ")", ",", "nil", "\n", "}" ]
// Namespace returns a replacement context that operates within the given namespace.
[ "Namespace", "returns", "a", "replacement", "context", "that", "operates", "within", "the", "given", "namespace", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/namespace.go#L17-L22
test
golang/appengine
cmd/aefix/typecheck.go
typeof
func (cfg *TypeConfig) typeof(name string) string { if cfg.Var != nil { if t := cfg.Var[name]; t != "" { return t } } if cfg.Func != nil { if t := cfg.Func[name]; t != "" { return "func()" + t } } return "" }
go
func (cfg *TypeConfig) typeof(name string) string { if cfg.Var != nil { if t := cfg.Var[name]; t != "" { return t } } if cfg.Func != nil { if t := cfg.Func[name]; t != "" { return "func()" + t } } return "" }
[ "func", "(", "cfg", "*", "TypeConfig", ")", "typeof", "(", "name", "string", ")", "string", "{", "if", "cfg", ".", "Var", "!=", "nil", "{", "if", "t", ":=", "cfg", ".", "Var", "[", "name", "]", ";", "t", "!=", "\"\"", "{", "return", "t", "\n", "}", "\n", "}", "\n", "if", "cfg", ".", "Func", "!=", "nil", "{", "if", "t", ":=", "cfg", ".", "Func", "[", "name", "]", ";", "t", "!=", "\"\"", "{", "return", "\"func()\"", "+", "t", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// typeof returns the type of the given name, which may be of // the form "x" or "p.X".
[ "typeof", "returns", "the", "type", "of", "the", "given", "name", "which", "may", "be", "of", "the", "form", "x", "or", "p", ".", "X", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L81-L93
test
golang/appengine
cmd/aefix/typecheck.go
dot
func (typ *Type) dot(cfg *TypeConfig, name string) string { if typ.Field != nil { if t := typ.Field[name]; t != "" { return t } } if typ.Method != nil { if t := typ.Method[name]; t != "" { return t } } for _, e := range typ.Embed { etyp := cfg.Type[e] if etyp != nil { if t := etyp.dot(cfg, name); t != "" { return t } } } return "" }
go
func (typ *Type) dot(cfg *TypeConfig, name string) string { if typ.Field != nil { if t := typ.Field[name]; t != "" { return t } } if typ.Method != nil { if t := typ.Method[name]; t != "" { return t } } for _, e := range typ.Embed { etyp := cfg.Type[e] if etyp != nil { if t := etyp.dot(cfg, name); t != "" { return t } } } return "" }
[ "func", "(", "typ", "*", "Type", ")", "dot", "(", "cfg", "*", "TypeConfig", ",", "name", "string", ")", "string", "{", "if", "typ", ".", "Field", "!=", "nil", "{", "if", "t", ":=", "typ", ".", "Field", "[", "name", "]", ";", "t", "!=", "\"\"", "{", "return", "t", "\n", "}", "\n", "}", "\n", "if", "typ", ".", "Method", "!=", "nil", "{", "if", "t", ":=", "typ", ".", "Method", "[", "name", "]", ";", "t", "!=", "\"\"", "{", "return", "t", "\n", "}", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "typ", ".", "Embed", "{", "etyp", ":=", "cfg", ".", "Type", "[", "e", "]", "\n", "if", "etyp", "!=", "nil", "{", "if", "t", ":=", "etyp", ".", "dot", "(", "cfg", ",", "name", ")", ";", "t", "!=", "\"\"", "{", "return", "t", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// dot returns the type of "typ.name", making its decision // using the type information in cfg.
[ "dot", "returns", "the", "type", "of", "typ", ".", "name", "making", "its", "decision", "using", "the", "type", "information", "in", "cfg", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L107-L129
test
golang/appengine
cmd/aefix/typecheck.go
joinFunc
func joinFunc(in, out []string) string { outs := "" if len(out) == 1 { outs = " " + out[0] } else if len(out) > 1 { outs = " (" + join(out) + ")" } return "func(" + join(in) + ")" + outs }
go
func joinFunc(in, out []string) string { outs := "" if len(out) == 1 { outs = " " + out[0] } else if len(out) > 1 { outs = " (" + join(out) + ")" } return "func(" + join(in) + ")" + outs }
[ "func", "joinFunc", "(", "in", ",", "out", "[", "]", "string", ")", "string", "{", "outs", ":=", "\"\"", "\n", "if", "len", "(", "out", ")", "==", "1", "{", "outs", "=", "\" \"", "+", "out", "[", "0", "]", "\n", "}", "else", "if", "len", "(", "out", ")", ">", "1", "{", "outs", "=", "\" (\"", "+", "join", "(", "out", ")", "+", "\")\"", "\n", "}", "\n", "return", "\"func(\"", "+", "join", "(", "in", ")", "+", "\")\"", "+", "outs", "\n", "}" ]
// joinFunc is the inverse of splitFunc.
[ "joinFunc", "is", "the", "inverse", "of", "splitFunc", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L622-L630
test
golang/appengine
datastore/prop.go
validPropertyName
func validPropertyName(name string) bool { if name == "" { return false } for _, s := range strings.Split(name, ".") { if s == "" { return false } first := true for _, c := range s { if first { first = false if c != '_' && !unicode.IsLetter(c) { return false } } else { if c != '_' && !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } } return true }
go
func validPropertyName(name string) bool { if name == "" { return false } for _, s := range strings.Split(name, ".") { if s == "" { return false } first := true for _, c := range s { if first { first = false if c != '_' && !unicode.IsLetter(c) { return false } } else { if c != '_' && !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } } return true }
[ "func", "validPropertyName", "(", "name", "string", ")", "bool", "{", "if", "name", "==", "\"\"", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "name", ",", "\".\"", ")", "{", "if", "s", "==", "\"\"", "{", "return", "false", "\n", "}", "\n", "first", ":=", "true", "\n", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "first", "{", "first", "=", "false", "\n", "if", "c", "!=", "'_'", "&&", "!", "unicode", ".", "IsLetter", "(", "c", ")", "{", "return", "false", "\n", "}", "\n", "}", "else", "{", "if", "c", "!=", "'_'", "&&", "!", "unicode", ".", "IsLetter", "(", "c", ")", "&&", "!", "unicode", ".", "IsDigit", "(", "c", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// validPropertyName returns whether name consists of one or more valid Go // identifiers joined by ".".
[ "validPropertyName", "returns", "whether", "name", "consists", "of", "one", "or", "more", "valid", "Go", "identifiers", "joined", "by", ".", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L105-L128
test
golang/appengine
datastore/prop.go
getStructCodec
func getStructCodec(t reflect.Type) (*structCodec, error) { structCodecsMutex.Lock() defer structCodecsMutex.Unlock() return getStructCodecLocked(t) }
go
func getStructCodec(t reflect.Type) (*structCodec, error) { structCodecsMutex.Lock() defer structCodecsMutex.Unlock() return getStructCodecLocked(t) }
[ "func", "getStructCodec", "(", "t", "reflect", ".", "Type", ")", "(", "*", "structCodec", ",", "error", ")", "{", "structCodecsMutex", ".", "Lock", "(", ")", "\n", "defer", "structCodecsMutex", ".", "Unlock", "(", ")", "\n", "return", "getStructCodecLocked", "(", "t", ")", "\n", "}" ]
// getStructCodec returns the structCodec for the given struct type.
[ "getStructCodec", "returns", "the", "structCodec", "for", "the", "given", "struct", "type", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L168-L172
test
golang/appengine
datastore/prop.go
LoadStruct
func LoadStruct(dst interface{}, p []Property) error { x, err := newStructPLS(dst) if err != nil { return err } return x.Load(p) }
go
func LoadStruct(dst interface{}, p []Property) error { x, err := newStructPLS(dst) if err != nil { return err } return x.Load(p) }
[ "func", "LoadStruct", "(", "dst", "interface", "{", "}", ",", "p", "[", "]", "Property", ")", "error", "{", "x", ",", "err", ":=", "newStructPLS", "(", "dst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "x", ".", "Load", "(", "p", ")", "\n", "}" ]
// LoadStruct loads the properties from p to dst. // dst must be a struct pointer.
[ "LoadStruct", "loads", "the", "properties", "from", "p", "to", "dst", ".", "dst", "must", "be", "a", "struct", "pointer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L314-L320
test
golang/appengine
datastore/prop.go
SaveStruct
func SaveStruct(src interface{}) ([]Property, error) { x, err := newStructPLS(src) if err != nil { return nil, err } return x.Save() }
go
func SaveStruct(src interface{}) ([]Property, error) { x, err := newStructPLS(src) if err != nil { return nil, err } return x.Save() }
[ "func", "SaveStruct", "(", "src", "interface", "{", "}", ")", "(", "[", "]", "Property", ",", "error", ")", "{", "x", ",", "err", ":=", "newStructPLS", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "x", ".", "Save", "(", ")", "\n", "}" ]
// SaveStruct returns the properties from src as a slice of Properties. // src must be a struct pointer.
[ "SaveStruct", "returns", "the", "properties", "from", "src", "as", "a", "slice", "of", "Properties", ".", "src", "must", "be", "a", "struct", "pointer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L324-L330
test
golang/appengine
image/image.go
ServingURL
func ServingURL(c context.Context, key appengine.BlobKey, opts *ServingURLOptions) (*url.URL, error) { req := &pb.ImagesGetUrlBaseRequest{ BlobKey: (*string)(&key), } if opts != nil && opts.Secure { req.CreateSecureUrl = &opts.Secure } res := &pb.ImagesGetUrlBaseResponse{} if err := internal.Call(c, "images", "GetUrlBase", req, res); err != nil { return nil, err } // The URL may have suffixes added to dynamically resize or crop: // - adding "=s32" will serve the image resized to 32 pixels, preserving the aspect ratio. // - adding "=s32-c" is the same as "=s32" except it will be cropped. u := *res.Url if opts != nil && opts.Size > 0 { u += fmt.Sprintf("=s%d", opts.Size) if opts.Crop { u += "-c" } } return url.Parse(u) }
go
func ServingURL(c context.Context, key appengine.BlobKey, opts *ServingURLOptions) (*url.URL, error) { req := &pb.ImagesGetUrlBaseRequest{ BlobKey: (*string)(&key), } if opts != nil && opts.Secure { req.CreateSecureUrl = &opts.Secure } res := &pb.ImagesGetUrlBaseResponse{} if err := internal.Call(c, "images", "GetUrlBase", req, res); err != nil { return nil, err } // The URL may have suffixes added to dynamically resize or crop: // - adding "=s32" will serve the image resized to 32 pixels, preserving the aspect ratio. // - adding "=s32-c" is the same as "=s32" except it will be cropped. u := *res.Url if opts != nil && opts.Size > 0 { u += fmt.Sprintf("=s%d", opts.Size) if opts.Crop { u += "-c" } } return url.Parse(u) }
[ "func", "ServingURL", "(", "c", "context", ".", "Context", ",", "key", "appengine", ".", "BlobKey", ",", "opts", "*", "ServingURLOptions", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "ImagesGetUrlBaseRequest", "{", "BlobKey", ":", "(", "*", "string", ")", "(", "&", "key", ")", ",", "}", "\n", "if", "opts", "!=", "nil", "&&", "opts", ".", "Secure", "{", "req", ".", "CreateSecureUrl", "=", "&", "opts", ".", "Secure", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "ImagesGetUrlBaseResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"images\"", ",", "\"GetUrlBase\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "u", ":=", "*", "res", ".", "Url", "\n", "if", "opts", "!=", "nil", "&&", "opts", ".", "Size", ">", "0", "{", "u", "+=", "fmt", ".", "Sprintf", "(", "\"=s%d\"", ",", "opts", ".", "Size", ")", "\n", "if", "opts", ".", "Crop", "{", "u", "+=", "\"-c\"", "\n", "}", "\n", "}", "\n", "return", "url", ".", "Parse", "(", "u", ")", "\n", "}" ]
// ServingURL returns a URL that will serve an image from Blobstore.
[ "ServingURL", "returns", "a", "URL", "that", "will", "serve", "an", "image", "from", "Blobstore", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/image/image.go#L31-L54
test
golang/appengine
image/image.go
DeleteServingURL
func DeleteServingURL(c context.Context, key appengine.BlobKey) error { req := &pb.ImagesDeleteUrlBaseRequest{ BlobKey: (*string)(&key), } res := &pb.ImagesDeleteUrlBaseResponse{} return internal.Call(c, "images", "DeleteUrlBase", req, res) }
go
func DeleteServingURL(c context.Context, key appengine.BlobKey) error { req := &pb.ImagesDeleteUrlBaseRequest{ BlobKey: (*string)(&key), } res := &pb.ImagesDeleteUrlBaseResponse{} return internal.Call(c, "images", "DeleteUrlBase", req, res) }
[ "func", "DeleteServingURL", "(", "c", "context", ".", "Context", ",", "key", "appengine", ".", "BlobKey", ")", "error", "{", "req", ":=", "&", "pb", ".", "ImagesDeleteUrlBaseRequest", "{", "BlobKey", ":", "(", "*", "string", ")", "(", "&", "key", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "ImagesDeleteUrlBaseResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"images\"", ",", "\"DeleteUrlBase\"", ",", "req", ",", "res", ")", "\n", "}" ]
// DeleteServingURL deletes the serving URL for an image.
[ "DeleteServingURL", "deletes", "the", "serving", "URL", "for", "an", "image", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/image/image.go#L57-L63
test
golang/appengine
user/oauth.go
CurrentOAuth
func CurrentOAuth(c context.Context, scopes ...string) (*User, error) { req := &pb.GetOAuthUserRequest{} if len(scopes) != 1 || scopes[0] != "" { // The signature for this function used to be CurrentOAuth(Context, string). // Ignore the singular "" scope to preserve existing behavior. req.Scopes = scopes } res := &pb.GetOAuthUserResponse{} err := internal.Call(c, "user", "GetOAuthUser", req, res) if err != nil { return nil, err } return &User{ Email: *res.Email, AuthDomain: *res.AuthDomain, Admin: res.GetIsAdmin(), ID: *res.UserId, ClientID: res.GetClientId(), }, nil }
go
func CurrentOAuth(c context.Context, scopes ...string) (*User, error) { req := &pb.GetOAuthUserRequest{} if len(scopes) != 1 || scopes[0] != "" { // The signature for this function used to be CurrentOAuth(Context, string). // Ignore the singular "" scope to preserve existing behavior. req.Scopes = scopes } res := &pb.GetOAuthUserResponse{} err := internal.Call(c, "user", "GetOAuthUser", req, res) if err != nil { return nil, err } return &User{ Email: *res.Email, AuthDomain: *res.AuthDomain, Admin: res.GetIsAdmin(), ID: *res.UserId, ClientID: res.GetClientId(), }, nil }
[ "func", "CurrentOAuth", "(", "c", "context", ".", "Context", ",", "scopes", "...", "string", ")", "(", "*", "User", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetOAuthUserRequest", "{", "}", "\n", "if", "len", "(", "scopes", ")", "!=", "1", "||", "scopes", "[", "0", "]", "!=", "\"\"", "{", "req", ".", "Scopes", "=", "scopes", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "GetOAuthUserResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"user\"", ",", "\"GetOAuthUser\"", ",", "req", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "User", "{", "Email", ":", "*", "res", ".", "Email", ",", "AuthDomain", ":", "*", "res", ".", "AuthDomain", ",", "Admin", ":", "res", ".", "GetIsAdmin", "(", ")", ",", "ID", ":", "*", "res", ".", "UserId", ",", "ClientID", ":", "res", ".", "GetClientId", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// CurrentOAuth returns the user associated with the OAuth consumer making this // request. If the OAuth consumer did not make a valid OAuth request, or the // scopes is non-empty and the current user does not have at least one of the // scopes, this method will return an error.
[ "CurrentOAuth", "returns", "the", "user", "associated", "with", "the", "OAuth", "consumer", "making", "this", "request", ".", "If", "the", "OAuth", "consumer", "did", "not", "make", "a", "valid", "OAuth", "request", "or", "the", "scopes", "is", "non", "-", "empty", "and", "the", "current", "user", "does", "not", "have", "at", "least", "one", "of", "the", "scopes", "this", "method", "will", "return", "an", "error", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/oauth.go#L18-L39
test
golang/appengine
user/oauth.go
OAuthConsumerKey
func OAuthConsumerKey(c context.Context) (string, error) { req := &pb.CheckOAuthSignatureRequest{} res := &pb.CheckOAuthSignatureResponse{} err := internal.Call(c, "user", "CheckOAuthSignature", req, res) if err != nil { return "", err } return *res.OauthConsumerKey, err }
go
func OAuthConsumerKey(c context.Context) (string, error) { req := &pb.CheckOAuthSignatureRequest{} res := &pb.CheckOAuthSignatureResponse{} err := internal.Call(c, "user", "CheckOAuthSignature", req, res) if err != nil { return "", err } return *res.OauthConsumerKey, err }
[ "func", "OAuthConsumerKey", "(", "c", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "CheckOAuthSignatureRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "CheckOAuthSignatureResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"user\"", ",", "\"CheckOAuthSignature\"", ",", "req", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "*", "res", ".", "OauthConsumerKey", ",", "err", "\n", "}" ]
// OAuthConsumerKey returns the OAuth consumer key provided with the current // request. This method will return an error if the OAuth request was invalid.
[ "OAuthConsumerKey", "returns", "the", "OAuth", "consumer", "key", "provided", "with", "the", "current", "request", ".", "This", "method", "will", "return", "an", "error", "if", "the", "OAuth", "request", "was", "invalid", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/oauth.go#L43-L52
test
golang/appengine
user/user.go
String
func (u *User) String() string { if u.AuthDomain != "" && strings.HasSuffix(u.Email, "@"+u.AuthDomain) { return u.Email[:len(u.Email)-len("@"+u.AuthDomain)] } if u.FederatedIdentity != "" { return u.FederatedIdentity } return u.Email }
go
func (u *User) String() string { if u.AuthDomain != "" && strings.HasSuffix(u.Email, "@"+u.AuthDomain) { return u.Email[:len(u.Email)-len("@"+u.AuthDomain)] } if u.FederatedIdentity != "" { return u.FederatedIdentity } return u.Email }
[ "func", "(", "u", "*", "User", ")", "String", "(", ")", "string", "{", "if", "u", ".", "AuthDomain", "!=", "\"\"", "&&", "strings", ".", "HasSuffix", "(", "u", ".", "Email", ",", "\"@\"", "+", "u", ".", "AuthDomain", ")", "{", "return", "u", ".", "Email", "[", ":", "len", "(", "u", ".", "Email", ")", "-", "len", "(", "\"@\"", "+", "u", ".", "AuthDomain", ")", "]", "\n", "}", "\n", "if", "u", ".", "FederatedIdentity", "!=", "\"\"", "{", "return", "u", ".", "FederatedIdentity", "\n", "}", "\n", "return", "u", ".", "Email", "\n", "}" ]
// String returns a displayable name for the user.
[ "String", "returns", "a", "displayable", "name", "for", "the", "user", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L38-L46
test
golang/appengine
user/user.go
LoginURL
func LoginURL(c context.Context, dest string) (string, error) { return LoginURLFederated(c, dest, "") }
go
func LoginURL(c context.Context, dest string) (string, error) { return LoginURLFederated(c, dest, "") }
[ "func", "LoginURL", "(", "c", "context", ".", "Context", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "return", "LoginURLFederated", "(", "c", ",", "dest", ",", "\"\"", ")", "\n", "}" ]
// LoginURL returns a URL that, when visited, prompts the user to sign in, // then redirects the user to the URL specified by dest.
[ "LoginURL", "returns", "a", "URL", "that", "when", "visited", "prompts", "the", "user", "to", "sign", "in", "then", "redirects", "the", "user", "to", "the", "URL", "specified", "by", "dest", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L50-L52
test
golang/appengine
user/user.go
LoginURLFederated
func LoginURLFederated(c context.Context, dest, identity string) (string, error) { req := &pb.CreateLoginURLRequest{ DestinationUrl: proto.String(dest), } if identity != "" { req.FederatedIdentity = proto.String(identity) } res := &pb.CreateLoginURLResponse{} if err := internal.Call(c, "user", "CreateLoginURL", req, res); err != nil { return "", err } return *res.LoginUrl, nil }
go
func LoginURLFederated(c context.Context, dest, identity string) (string, error) { req := &pb.CreateLoginURLRequest{ DestinationUrl: proto.String(dest), } if identity != "" { req.FederatedIdentity = proto.String(identity) } res := &pb.CreateLoginURLResponse{} if err := internal.Call(c, "user", "CreateLoginURL", req, res); err != nil { return "", err } return *res.LoginUrl, nil }
[ "func", "LoginURLFederated", "(", "c", "context", ".", "Context", ",", "dest", ",", "identity", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "CreateLoginURLRequest", "{", "DestinationUrl", ":", "proto", ".", "String", "(", "dest", ")", ",", "}", "\n", "if", "identity", "!=", "\"\"", "{", "req", ".", "FederatedIdentity", "=", "proto", ".", "String", "(", "identity", ")", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "CreateLoginURLResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"user\"", ",", "\"CreateLoginURL\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "*", "res", ".", "LoginUrl", ",", "nil", "\n", "}" ]
// LoginURLFederated is like LoginURL but accepts a user's OpenID identifier.
[ "LoginURLFederated", "is", "like", "LoginURL", "but", "accepts", "a", "user", "s", "OpenID", "identifier", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L55-L67
test
golang/appengine
user/user.go
LogoutURL
func LogoutURL(c context.Context, dest string) (string, error) { req := &pb.CreateLogoutURLRequest{ DestinationUrl: proto.String(dest), } res := &pb.CreateLogoutURLResponse{} if err := internal.Call(c, "user", "CreateLogoutURL", req, res); err != nil { return "", err } return *res.LogoutUrl, nil }
go
func LogoutURL(c context.Context, dest string) (string, error) { req := &pb.CreateLogoutURLRequest{ DestinationUrl: proto.String(dest), } res := &pb.CreateLogoutURLResponse{} if err := internal.Call(c, "user", "CreateLogoutURL", req, res); err != nil { return "", err } return *res.LogoutUrl, nil }
[ "func", "LogoutURL", "(", "c", "context", ".", "Context", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "CreateLogoutURLRequest", "{", "DestinationUrl", ":", "proto", ".", "String", "(", "dest", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "CreateLogoutURLResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"user\"", ",", "\"CreateLogoutURL\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "*", "res", ".", "LogoutUrl", ",", "nil", "\n", "}" ]
// LogoutURL returns a URL that, when visited, signs the user out, // then redirects the user to the URL specified by dest.
[ "LogoutURL", "returns", "a", "URL", "that", "when", "visited", "signs", "the", "user", "out", "then", "redirects", "the", "user", "to", "the", "URL", "specified", "by", "dest", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L71-L80
test
golang/appengine
cmd/aefix/ae.go
insertContext
func insertContext(f *ast.File, call *ast.CallExpr, ctx *ast.Ident) { if ctx == nil { // context is unknown, so use a plain "ctx". ctx = ast.NewIdent("ctx") } else { // Create a fresh *ast.Ident so we drop the position information. ctx = ast.NewIdent(ctx.Name) } call.Args = append([]ast.Expr{ctx}, call.Args...) }
go
func insertContext(f *ast.File, call *ast.CallExpr, ctx *ast.Ident) { if ctx == nil { // context is unknown, so use a plain "ctx". ctx = ast.NewIdent("ctx") } else { // Create a fresh *ast.Ident so we drop the position information. ctx = ast.NewIdent(ctx.Name) } call.Args = append([]ast.Expr{ctx}, call.Args...) }
[ "func", "insertContext", "(", "f", "*", "ast", ".", "File", ",", "call", "*", "ast", ".", "CallExpr", ",", "ctx", "*", "ast", ".", "Ident", ")", "{", "if", "ctx", "==", "nil", "{", "ctx", "=", "ast", ".", "NewIdent", "(", "\"ctx\"", ")", "\n", "}", "else", "{", "ctx", "=", "ast", ".", "NewIdent", "(", "ctx", ".", "Name", ")", "\n", "}", "\n", "call", ".", "Args", "=", "append", "(", "[", "]", "ast", ".", "Expr", "{", "ctx", "}", ",", "call", ".", "Args", "...", ")", "\n", "}" ]
// ctx may be nil.
[ "ctx", "may", "be", "nil", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/ae.go#L175-L185
test
golang/appengine
remote_api/client.go
NewClient
func NewClient(host string, client *http.Client) (*Client, error) { // Add an appcfg header to outgoing requests. wrapClient := new(http.Client) *wrapClient = *client t := client.Transport if t == nil { t = http.DefaultTransport } wrapClient.Transport = &headerAddingRoundTripper{t} url := url.URL{ Scheme: "https", Host: host, Path: "/_ah/remote_api", } if host == "localhost" || strings.HasPrefix(host, "localhost:") { url.Scheme = "http" } u := url.String() appID, err := getAppID(wrapClient, u) if err != nil { return nil, fmt.Errorf("unable to contact server: %v", err) } return &Client{ hc: wrapClient, url: u, appID: appID, }, nil }
go
func NewClient(host string, client *http.Client) (*Client, error) { // Add an appcfg header to outgoing requests. wrapClient := new(http.Client) *wrapClient = *client t := client.Transport if t == nil { t = http.DefaultTransport } wrapClient.Transport = &headerAddingRoundTripper{t} url := url.URL{ Scheme: "https", Host: host, Path: "/_ah/remote_api", } if host == "localhost" || strings.HasPrefix(host, "localhost:") { url.Scheme = "http" } u := url.String() appID, err := getAppID(wrapClient, u) if err != nil { return nil, fmt.Errorf("unable to contact server: %v", err) } return &Client{ hc: wrapClient, url: u, appID: appID, }, nil }
[ "func", "NewClient", "(", "host", "string", ",", "client", "*", "http", ".", "Client", ")", "(", "*", "Client", ",", "error", ")", "{", "wrapClient", ":=", "new", "(", "http", ".", "Client", ")", "\n", "*", "wrapClient", "=", "*", "client", "\n", "t", ":=", "client", ".", "Transport", "\n", "if", "t", "==", "nil", "{", "t", "=", "http", ".", "DefaultTransport", "\n", "}", "\n", "wrapClient", ".", "Transport", "=", "&", "headerAddingRoundTripper", "{", "t", "}", "\n", "url", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"https\"", ",", "Host", ":", "host", ",", "Path", ":", "\"/_ah/remote_api\"", ",", "}", "\n", "if", "host", "==", "\"localhost\"", "||", "strings", ".", "HasPrefix", "(", "host", ",", "\"localhost:\"", ")", "{", "url", ".", "Scheme", "=", "\"http\"", "\n", "}", "\n", "u", ":=", "url", ".", "String", "(", ")", "\n", "appID", ",", "err", ":=", "getAppID", "(", "wrapClient", ",", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unable to contact server: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "Client", "{", "hc", ":", "wrapClient", ",", "url", ":", "u", ",", "appID", ":", "appID", ",", "}", ",", "nil", "\n", "}" ]
// NewClient returns a client for the given host. All communication will // be performed over SSL unless the host is localhost.
[ "NewClient", "returns", "a", "client", "for", "the", "given", "host", ".", "All", "communication", "will", "be", "performed", "over", "SSL", "unless", "the", "host", "is", "localhost", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/remote_api/client.go#L39-L67
test
golang/appengine
remote_api/client.go
NewContext
func (c *Client) NewContext(parent context.Context) context.Context { ctx := internal.WithCallOverride(parent, c.call) ctx = internal.WithLogOverride(ctx, c.logf) ctx = internal.WithAppIDOverride(ctx, c.appID) return ctx }
go
func (c *Client) NewContext(parent context.Context) context.Context { ctx := internal.WithCallOverride(parent, c.call) ctx = internal.WithLogOverride(ctx, c.logf) ctx = internal.WithAppIDOverride(ctx, c.appID) return ctx }
[ "func", "(", "c", "*", "Client", ")", "NewContext", "(", "parent", "context", ".", "Context", ")", "context", ".", "Context", "{", "ctx", ":=", "internal", ".", "WithCallOverride", "(", "parent", ",", "c", ".", "call", ")", "\n", "ctx", "=", "internal", ".", "WithLogOverride", "(", "ctx", ",", "c", ".", "logf", ")", "\n", "ctx", "=", "internal", ".", "WithAppIDOverride", "(", "ctx", ",", "c", ".", "appID", ")", "\n", "return", "ctx", "\n", "}" ]
// NewContext returns a copy of parent that will cause App Engine API // calls to be sent to the client's remote host.
[ "NewContext", "returns", "a", "copy", "of", "parent", "that", "will", "cause", "App", "Engine", "API", "calls", "to", "be", "sent", "to", "the", "client", "s", "remote", "host", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/remote_api/client.go#L71-L76
test
golang/appengine
remote_api/client.go
NewRemoteContext
func NewRemoteContext(host string, client *http.Client) (context.Context, error) { c, err := NewClient(host, client) if err != nil { return nil, err } return c.NewContext(context.Background()), nil }
go
func NewRemoteContext(host string, client *http.Client) (context.Context, error) { c, err := NewClient(host, client) if err != nil { return nil, err } return c.NewContext(context.Background()), nil }
[ "func", "NewRemoteContext", "(", "host", "string", ",", "client", "*", "http", ".", "Client", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "c", ",", "err", ":=", "NewClient", "(", "host", ",", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "c", ".", "NewContext", "(", "context", ".", "Background", "(", ")", ")", ",", "nil", "\n", "}" ]
// NewRemoteContext returns a context that gives access to the production // APIs for the application at the given host. All communication will be // performed over SSL unless the host is localhost.
[ "NewRemoteContext", "returns", "a", "context", "that", "gives", "access", "to", "the", "production", "APIs", "for", "the", "application", "at", "the", "given", "host", ".", "All", "communication", "will", "be", "performed", "over", "SSL", "unless", "the", "host", "is", "localhost", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/remote_api/client.go#L81-L87
test
golang/appengine
log/api.go
Debugf
func Debugf(ctx context.Context, format string, args ...interface{}) { internal.Logf(ctx, 0, format, args...) }
go
func Debugf(ctx context.Context, format string, args ...interface{}) { internal.Logf(ctx, 0, format, args...) }
[ "func", "Debugf", "(", "ctx", "context", ".", "Context", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "internal", ".", "Logf", "(", "ctx", ",", "0", ",", "format", ",", "args", "...", ")", "\n", "}" ]
// Debugf formats its arguments according to the format, analogous to fmt.Printf, // and records the text as a log message at Debug level. The message will be associated // with the request linked with the provided context.
[ "Debugf", "formats", "its", "arguments", "according", "to", "the", "format", "analogous", "to", "fmt", ".", "Printf", "and", "records", "the", "text", "as", "a", "log", "message", "at", "Debug", "level", ".", "The", "message", "will", "be", "associated", "with", "the", "request", "linked", "with", "the", "provided", "context", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/api.go#L18-L20
test
golang/appengine
demos/guestbook/guestbook.go
guestbookKey
func guestbookKey(ctx context.Context) *datastore.Key { // The string "default_guestbook" here could be varied to have multiple guestbooks. return datastore.NewKey(ctx, "Guestbook", "default_guestbook", 0, nil) }
go
func guestbookKey(ctx context.Context) *datastore.Key { // The string "default_guestbook" here could be varied to have multiple guestbooks. return datastore.NewKey(ctx, "Guestbook", "default_guestbook", 0, nil) }
[ "func", "guestbookKey", "(", "ctx", "context", ".", "Context", ")", "*", "datastore", ".", "Key", "{", "return", "datastore", ".", "NewKey", "(", "ctx", ",", "\"Guestbook\"", ",", "\"default_guestbook\"", ",", "0", ",", "nil", ")", "\n", "}" ]
// guestbookKey returns the key used for all guestbook entries.
[ "guestbookKey", "returns", "the", "key", "used", "for", "all", "guestbook", "entries", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/demos/guestbook/guestbook.go#L38-L41
test
golang/appengine
taskqueue/taskqueue.go
toRetryParameters
func (opt *RetryOptions) toRetryParameters() *pb.TaskQueueRetryParameters { params := &pb.TaskQueueRetryParameters{} if opt.RetryLimit > 0 { params.RetryLimit = proto.Int32(opt.RetryLimit) } if opt.AgeLimit > 0 { params.AgeLimitSec = proto.Int64(int64(opt.AgeLimit.Seconds())) } if opt.MinBackoff > 0 { params.MinBackoffSec = proto.Float64(opt.MinBackoff.Seconds()) } if opt.MaxBackoff > 0 { params.MaxBackoffSec = proto.Float64(opt.MaxBackoff.Seconds()) } if opt.MaxDoublings > 0 || (opt.MaxDoublings == 0 && opt.ApplyZeroMaxDoublings) { params.MaxDoublings = proto.Int32(opt.MaxDoublings) } return params }
go
func (opt *RetryOptions) toRetryParameters() *pb.TaskQueueRetryParameters { params := &pb.TaskQueueRetryParameters{} if opt.RetryLimit > 0 { params.RetryLimit = proto.Int32(opt.RetryLimit) } if opt.AgeLimit > 0 { params.AgeLimitSec = proto.Int64(int64(opt.AgeLimit.Seconds())) } if opt.MinBackoff > 0 { params.MinBackoffSec = proto.Float64(opt.MinBackoff.Seconds()) } if opt.MaxBackoff > 0 { params.MaxBackoffSec = proto.Float64(opt.MaxBackoff.Seconds()) } if opt.MaxDoublings > 0 || (opt.MaxDoublings == 0 && opt.ApplyZeroMaxDoublings) { params.MaxDoublings = proto.Int32(opt.MaxDoublings) } return params }
[ "func", "(", "opt", "*", "RetryOptions", ")", "toRetryParameters", "(", ")", "*", "pb", ".", "TaskQueueRetryParameters", "{", "params", ":=", "&", "pb", ".", "TaskQueueRetryParameters", "{", "}", "\n", "if", "opt", ".", "RetryLimit", ">", "0", "{", "params", ".", "RetryLimit", "=", "proto", ".", "Int32", "(", "opt", ".", "RetryLimit", ")", "\n", "}", "\n", "if", "opt", ".", "AgeLimit", ">", "0", "{", "params", ".", "AgeLimitSec", "=", "proto", ".", "Int64", "(", "int64", "(", "opt", ".", "AgeLimit", ".", "Seconds", "(", ")", ")", ")", "\n", "}", "\n", "if", "opt", ".", "MinBackoff", ">", "0", "{", "params", ".", "MinBackoffSec", "=", "proto", ".", "Float64", "(", "opt", ".", "MinBackoff", ".", "Seconds", "(", ")", ")", "\n", "}", "\n", "if", "opt", ".", "MaxBackoff", ">", "0", "{", "params", ".", "MaxBackoffSec", "=", "proto", ".", "Float64", "(", "opt", ".", "MaxBackoff", ".", "Seconds", "(", ")", ")", "\n", "}", "\n", "if", "opt", ".", "MaxDoublings", ">", "0", "||", "(", "opt", ".", "MaxDoublings", "==", "0", "&&", "opt", ".", "ApplyZeroMaxDoublings", ")", "{", "params", ".", "MaxDoublings", "=", "proto", ".", "Int32", "(", "opt", ".", "MaxDoublings", ")", "\n", "}", "\n", "return", "params", "\n", "}" ]
// toRetryParameter converts RetryOptions to pb.TaskQueueRetryParameters.
[ "toRetryParameter", "converts", "RetryOptions", "to", "pb", ".", "TaskQueueRetryParameters", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L66-L84
test
golang/appengine
taskqueue/taskqueue.go
NewPOSTTask
func NewPOSTTask(path string, params url.Values) *Task { h := make(http.Header) h.Set("Content-Type", "application/x-www-form-urlencoded") return &Task{ Path: path, Payload: []byte(params.Encode()), Header: h, Method: "POST", } }
go
func NewPOSTTask(path string, params url.Values) *Task { h := make(http.Header) h.Set("Content-Type", "application/x-www-form-urlencoded") return &Task{ Path: path, Payload: []byte(params.Encode()), Header: h, Method: "POST", } }
[ "func", "NewPOSTTask", "(", "path", "string", ",", "params", "url", ".", "Values", ")", "*", "Task", "{", "h", ":=", "make", "(", "http", ".", "Header", ")", "\n", "h", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/x-www-form-urlencoded\"", ")", "\n", "return", "&", "Task", "{", "Path", ":", "path", ",", "Payload", ":", "[", "]", "byte", "(", "params", ".", "Encode", "(", ")", ")", ",", "Header", ":", "h", ",", "Method", ":", "\"POST\"", ",", "}", "\n", "}" ]
// NewPOSTTask creates a Task that will POST to a path with the given form data.
[ "NewPOSTTask", "creates", "a", "Task", "that", "will", "POST", "to", "a", "path", "with", "the", "given", "form", "data", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L140-L149
test
golang/appengine
taskqueue/taskqueue.go
ParseRequestHeaders
func ParseRequestHeaders(h http.Header) *RequestHeaders { ret := &RequestHeaders{ QueueName: h.Get("X-AppEngine-QueueName"), TaskName: h.Get("X-AppEngine-TaskName"), } ret.TaskRetryCount, _ = strconv.ParseInt(h.Get("X-AppEngine-TaskRetryCount"), 10, 64) ret.TaskExecutionCount, _ = strconv.ParseInt(h.Get("X-AppEngine-TaskExecutionCount"), 10, 64) etaSecs, _ := strconv.ParseInt(h.Get("X-AppEngine-TaskETA"), 10, 64) if etaSecs != 0 { ret.TaskETA = time.Unix(etaSecs, 0) } ret.TaskPreviousResponse, _ = strconv.Atoi(h.Get("X-AppEngine-TaskPreviousResponse")) ret.TaskRetryReason = h.Get("X-AppEngine-TaskRetryReason") if h.Get("X-AppEngine-FailFast") != "" { ret.FailFast = true } return ret }
go
func ParseRequestHeaders(h http.Header) *RequestHeaders { ret := &RequestHeaders{ QueueName: h.Get("X-AppEngine-QueueName"), TaskName: h.Get("X-AppEngine-TaskName"), } ret.TaskRetryCount, _ = strconv.ParseInt(h.Get("X-AppEngine-TaskRetryCount"), 10, 64) ret.TaskExecutionCount, _ = strconv.ParseInt(h.Get("X-AppEngine-TaskExecutionCount"), 10, 64) etaSecs, _ := strconv.ParseInt(h.Get("X-AppEngine-TaskETA"), 10, 64) if etaSecs != 0 { ret.TaskETA = time.Unix(etaSecs, 0) } ret.TaskPreviousResponse, _ = strconv.Atoi(h.Get("X-AppEngine-TaskPreviousResponse")) ret.TaskRetryReason = h.Get("X-AppEngine-TaskRetryReason") if h.Get("X-AppEngine-FailFast") != "" { ret.FailFast = true } return ret }
[ "func", "ParseRequestHeaders", "(", "h", "http", ".", "Header", ")", "*", "RequestHeaders", "{", "ret", ":=", "&", "RequestHeaders", "{", "QueueName", ":", "h", ".", "Get", "(", "\"X-AppEngine-QueueName\"", ")", ",", "TaskName", ":", "h", ".", "Get", "(", "\"X-AppEngine-TaskName\"", ")", ",", "}", "\n", "ret", ".", "TaskRetryCount", ",", "_", "=", "strconv", ".", "ParseInt", "(", "h", ".", "Get", "(", "\"X-AppEngine-TaskRetryCount\"", ")", ",", "10", ",", "64", ")", "\n", "ret", ".", "TaskExecutionCount", ",", "_", "=", "strconv", ".", "ParseInt", "(", "h", ".", "Get", "(", "\"X-AppEngine-TaskExecutionCount\"", ")", ",", "10", ",", "64", ")", "\n", "etaSecs", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "h", ".", "Get", "(", "\"X-AppEngine-TaskETA\"", ")", ",", "10", ",", "64", ")", "\n", "if", "etaSecs", "!=", "0", "{", "ret", ".", "TaskETA", "=", "time", ".", "Unix", "(", "etaSecs", ",", "0", ")", "\n", "}", "\n", "ret", ".", "TaskPreviousResponse", ",", "_", "=", "strconv", ".", "Atoi", "(", "h", ".", "Get", "(", "\"X-AppEngine-TaskPreviousResponse\"", ")", ")", "\n", "ret", ".", "TaskRetryReason", "=", "h", ".", "Get", "(", "\"X-AppEngine-TaskRetryReason\"", ")", "\n", "if", "h", ".", "Get", "(", "\"X-AppEngine-FailFast\"", ")", "!=", "\"\"", "{", "ret", ".", "FailFast", "=", "true", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ParseRequestHeaders parses the special HTTP request headers available to push // task request handlers. This function silently ignores values of the wrong // format.
[ "ParseRequestHeaders", "parses", "the", "special", "HTTP", "request", "headers", "available", "to", "push", "task", "request", "handlers", ".", "This", "function", "silently", "ignores", "values", "of", "the", "wrong", "format", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L170-L191
test
golang/appengine
taskqueue/taskqueue.go
Add
func Add(c context.Context, task *Task, queueName string) (*Task, error) { req, err := newAddReq(c, task, queueName) if err != nil { return nil, err } res := &pb.TaskQueueAddResponse{} if err := internal.Call(c, "taskqueue", "Add", req, res); err != nil { apiErr, ok := err.(*internal.APIError) if ok && alreadyAddedErrors[pb.TaskQueueServiceError_ErrorCode(apiErr.Code)] { return nil, ErrTaskAlreadyAdded } return nil, err } resultTask := *task resultTask.Method = task.method() if task.Name == "" { resultTask.Name = string(res.ChosenTaskName) } return &resultTask, nil }
go
func Add(c context.Context, task *Task, queueName string) (*Task, error) { req, err := newAddReq(c, task, queueName) if err != nil { return nil, err } res := &pb.TaskQueueAddResponse{} if err := internal.Call(c, "taskqueue", "Add", req, res); err != nil { apiErr, ok := err.(*internal.APIError) if ok && alreadyAddedErrors[pb.TaskQueueServiceError_ErrorCode(apiErr.Code)] { return nil, ErrTaskAlreadyAdded } return nil, err } resultTask := *task resultTask.Method = task.method() if task.Name == "" { resultTask.Name = string(res.ChosenTaskName) } return &resultTask, nil }
[ "func", "Add", "(", "c", "context", ".", "Context", ",", "task", "*", "Task", ",", "queueName", "string", ")", "(", "*", "Task", ",", "error", ")", "{", "req", ",", "err", ":=", "newAddReq", "(", "c", ",", "task", ",", "queueName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueueAddResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"Add\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "apiErr", ",", "ok", ":=", "err", ".", "(", "*", "internal", ".", "APIError", ")", "\n", "if", "ok", "&&", "alreadyAddedErrors", "[", "pb", ".", "TaskQueueServiceError_ErrorCode", "(", "apiErr", ".", "Code", ")", "]", "{", "return", "nil", ",", "ErrTaskAlreadyAdded", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "resultTask", ":=", "*", "task", "\n", "resultTask", ".", "Method", "=", "task", ".", "method", "(", ")", "\n", "if", "task", ".", "Name", "==", "\"\"", "{", "resultTask", ".", "Name", "=", "string", "(", "res", ".", "ChosenTaskName", ")", "\n", "}", "\n", "return", "&", "resultTask", ",", "nil", "\n", "}" ]
// Add adds the task to a named queue. // An empty queue name means that the default queue will be used. // Add returns an equivalent Task with defaults filled in, including setting // the task's Name field to the chosen name if the original was empty.
[ "Add", "adds", "the", "task", "to", "a", "named", "queue", ".", "An", "empty", "queue", "name", "means", "that", "the", "default", "queue", "will", "be", "used", ".", "Add", "returns", "an", "equivalent", "Task", "with", "defaults", "filled", "in", "including", "setting", "the", "task", "s", "Name", "field", "to", "the", "chosen", "name", "if", "the", "original", "was", "empty", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L285-L304
test
golang/appengine
taskqueue/taskqueue.go
AddMulti
func AddMulti(c context.Context, tasks []*Task, queueName string) ([]*Task, error) { req := &pb.TaskQueueBulkAddRequest{ AddRequest: make([]*pb.TaskQueueAddRequest, len(tasks)), } me, any := make(appengine.MultiError, len(tasks)), false for i, t := range tasks { req.AddRequest[i], me[i] = newAddReq(c, t, queueName) any = any || me[i] != nil } if any { return nil, me } res := &pb.TaskQueueBulkAddResponse{} if err := internal.Call(c, "taskqueue", "BulkAdd", req, res); err != nil { return nil, err } if len(res.Taskresult) != len(tasks) { return nil, errors.New("taskqueue: server error") } tasksOut := make([]*Task, len(tasks)) for i, tr := range res.Taskresult { tasksOut[i] = new(Task) *tasksOut[i] = *tasks[i] tasksOut[i].Method = tasksOut[i].method() if tasksOut[i].Name == "" { tasksOut[i].Name = string(tr.ChosenTaskName) } if *tr.Result != pb.TaskQueueServiceError_OK { if alreadyAddedErrors[*tr.Result] { me[i] = ErrTaskAlreadyAdded } else { me[i] = &internal.APIError{ Service: "taskqueue", Code: int32(*tr.Result), } } any = true } } if any { return tasksOut, me } return tasksOut, nil }
go
func AddMulti(c context.Context, tasks []*Task, queueName string) ([]*Task, error) { req := &pb.TaskQueueBulkAddRequest{ AddRequest: make([]*pb.TaskQueueAddRequest, len(tasks)), } me, any := make(appengine.MultiError, len(tasks)), false for i, t := range tasks { req.AddRequest[i], me[i] = newAddReq(c, t, queueName) any = any || me[i] != nil } if any { return nil, me } res := &pb.TaskQueueBulkAddResponse{} if err := internal.Call(c, "taskqueue", "BulkAdd", req, res); err != nil { return nil, err } if len(res.Taskresult) != len(tasks) { return nil, errors.New("taskqueue: server error") } tasksOut := make([]*Task, len(tasks)) for i, tr := range res.Taskresult { tasksOut[i] = new(Task) *tasksOut[i] = *tasks[i] tasksOut[i].Method = tasksOut[i].method() if tasksOut[i].Name == "" { tasksOut[i].Name = string(tr.ChosenTaskName) } if *tr.Result != pb.TaskQueueServiceError_OK { if alreadyAddedErrors[*tr.Result] { me[i] = ErrTaskAlreadyAdded } else { me[i] = &internal.APIError{ Service: "taskqueue", Code: int32(*tr.Result), } } any = true } } if any { return tasksOut, me } return tasksOut, nil }
[ "func", "AddMulti", "(", "c", "context", ".", "Context", ",", "tasks", "[", "]", "*", "Task", ",", "queueName", "string", ")", "(", "[", "]", "*", "Task", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "TaskQueueBulkAddRequest", "{", "AddRequest", ":", "make", "(", "[", "]", "*", "pb", ".", "TaskQueueAddRequest", ",", "len", "(", "tasks", ")", ")", ",", "}", "\n", "me", ",", "any", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "tasks", ")", ")", ",", "false", "\n", "for", "i", ",", "t", ":=", "range", "tasks", "{", "req", ".", "AddRequest", "[", "i", "]", ",", "me", "[", "i", "]", "=", "newAddReq", "(", "c", ",", "t", ",", "queueName", ")", "\n", "any", "=", "any", "||", "me", "[", "i", "]", "!=", "nil", "\n", "}", "\n", "if", "any", "{", "return", "nil", ",", "me", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueueBulkAddResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"BulkAdd\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "Taskresult", ")", "!=", "len", "(", "tasks", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"taskqueue: server error\"", ")", "\n", "}", "\n", "tasksOut", ":=", "make", "(", "[", "]", "*", "Task", ",", "len", "(", "tasks", ")", ")", "\n", "for", "i", ",", "tr", ":=", "range", "res", ".", "Taskresult", "{", "tasksOut", "[", "i", "]", "=", "new", "(", "Task", ")", "\n", "*", "tasksOut", "[", "i", "]", "=", "*", "tasks", "[", "i", "]", "\n", "tasksOut", "[", "i", "]", ".", "Method", "=", "tasksOut", "[", "i", "]", ".", "method", "(", ")", "\n", "if", "tasksOut", "[", "i", "]", ".", "Name", "==", "\"\"", "{", "tasksOut", "[", "i", "]", ".", "Name", "=", "string", "(", "tr", ".", "ChosenTaskName", ")", "\n", "}", "\n", "if", "*", "tr", ".", "Result", "!=", "pb", ".", "TaskQueueServiceError_OK", "{", "if", "alreadyAddedErrors", "[", "*", "tr", ".", "Result", "]", "{", "me", "[", "i", "]", "=", "ErrTaskAlreadyAdded", "\n", "}", "else", "{", "me", "[", "i", "]", "=", "&", "internal", ".", "APIError", "{", "Service", ":", "\"taskqueue\"", ",", "Code", ":", "int32", "(", "*", "tr", ".", "Result", ")", ",", "}", "\n", "}", "\n", "any", "=", "true", "\n", "}", "\n", "}", "\n", "if", "any", "{", "return", "tasksOut", ",", "me", "\n", "}", "\n", "return", "tasksOut", ",", "nil", "\n", "}" ]
// AddMulti adds multiple tasks to a named queue. // An empty queue name means that the default queue will be used. // AddMulti returns a slice of equivalent tasks with defaults filled in, including setting // each task's Name field to the chosen name if the original was empty. // If a given task is badly formed or could not be added, an appengine.MultiError is returned.
[ "AddMulti", "adds", "multiple", "tasks", "to", "a", "named", "queue", ".", "An", "empty", "queue", "name", "means", "that", "the", "default", "queue", "will", "be", "used", ".", "AddMulti", "returns", "a", "slice", "of", "equivalent", "tasks", "with", "defaults", "filled", "in", "including", "setting", "each", "task", "s", "Name", "field", "to", "the", "chosen", "name", "if", "the", "original", "was", "empty", ".", "If", "a", "given", "task", "is", "badly", "formed", "or", "could", "not", "be", "added", "an", "appengine", ".", "MultiError", "is", "returned", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L311-L354
test
golang/appengine
taskqueue/taskqueue.go
Delete
func Delete(c context.Context, task *Task, queueName string) error { err := DeleteMulti(c, []*Task{task}, queueName) if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
go
func Delete(c context.Context, task *Task, queueName string) error { err := DeleteMulti(c, []*Task{task}, queueName) if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
[ "func", "Delete", "(", "c", "context", ".", "Context", ",", "task", "*", "Task", ",", "queueName", "string", ")", "error", "{", "err", ":=", "DeleteMulti", "(", "c", ",", "[", "]", "*", "Task", "{", "task", "}", ",", "queueName", ")", "\n", "if", "me", ",", "ok", ":=", "err", ".", "(", "appengine", ".", "MultiError", ")", ";", "ok", "{", "return", "me", "[", "0", "]", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Delete deletes a task from a named queue.
[ "Delete", "deletes", "a", "task", "from", "a", "named", "queue", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L357-L363
test
golang/appengine
taskqueue/taskqueue.go
DeleteMulti
func DeleteMulti(c context.Context, tasks []*Task, queueName string) error { taskNames := make([][]byte, len(tasks)) for i, t := range tasks { taskNames[i] = []byte(t.Name) } if queueName == "" { queueName = "default" } req := &pb.TaskQueueDeleteRequest{ QueueName: []byte(queueName), TaskName: taskNames, } res := &pb.TaskQueueDeleteResponse{} if err := internal.Call(c, "taskqueue", "Delete", req, res); err != nil { return err } if a, b := len(req.TaskName), len(res.Result); a != b { return fmt.Errorf("taskqueue: internal error: requested deletion of %d tasks, got %d results", a, b) } me, any := make(appengine.MultiError, len(res.Result)), false for i, ec := range res.Result { if ec != pb.TaskQueueServiceError_OK { me[i] = &internal.APIError{ Service: "taskqueue", Code: int32(ec), } any = true } } if any { return me } return nil }
go
func DeleteMulti(c context.Context, tasks []*Task, queueName string) error { taskNames := make([][]byte, len(tasks)) for i, t := range tasks { taskNames[i] = []byte(t.Name) } if queueName == "" { queueName = "default" } req := &pb.TaskQueueDeleteRequest{ QueueName: []byte(queueName), TaskName: taskNames, } res := &pb.TaskQueueDeleteResponse{} if err := internal.Call(c, "taskqueue", "Delete", req, res); err != nil { return err } if a, b := len(req.TaskName), len(res.Result); a != b { return fmt.Errorf("taskqueue: internal error: requested deletion of %d tasks, got %d results", a, b) } me, any := make(appengine.MultiError, len(res.Result)), false for i, ec := range res.Result { if ec != pb.TaskQueueServiceError_OK { me[i] = &internal.APIError{ Service: "taskqueue", Code: int32(ec), } any = true } } if any { return me } return nil }
[ "func", "DeleteMulti", "(", "c", "context", ".", "Context", ",", "tasks", "[", "]", "*", "Task", ",", "queueName", "string", ")", "error", "{", "taskNames", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "tasks", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "tasks", "{", "taskNames", "[", "i", "]", "=", "[", "]", "byte", "(", "t", ".", "Name", ")", "\n", "}", "\n", "if", "queueName", "==", "\"\"", "{", "queueName", "=", "\"default\"", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "TaskQueueDeleteRequest", "{", "QueueName", ":", "[", "]", "byte", "(", "queueName", ")", ",", "TaskName", ":", "taskNames", ",", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueueDeleteResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"Delete\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "a", ",", "b", ":=", "len", "(", "req", ".", "TaskName", ")", ",", "len", "(", "res", ".", "Result", ")", ";", "a", "!=", "b", "{", "return", "fmt", ".", "Errorf", "(", "\"taskqueue: internal error: requested deletion of %d tasks, got %d results\"", ",", "a", ",", "b", ")", "\n", "}", "\n", "me", ",", "any", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "res", ".", "Result", ")", ")", ",", "false", "\n", "for", "i", ",", "ec", ":=", "range", "res", ".", "Result", "{", "if", "ec", "!=", "pb", ".", "TaskQueueServiceError_OK", "{", "me", "[", "i", "]", "=", "&", "internal", ".", "APIError", "{", "Service", ":", "\"taskqueue\"", ",", "Code", ":", "int32", "(", "ec", ")", ",", "}", "\n", "any", "=", "true", "\n", "}", "\n", "}", "\n", "if", "any", "{", "return", "me", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteMulti deletes multiple tasks from a named queue. // If a given task could not be deleted, an appengine.MultiError is returned. // Each task is deleted independently; one may fail to delete while the others // are sucessfully deleted.
[ "DeleteMulti", "deletes", "multiple", "tasks", "from", "a", "named", "queue", ".", "If", "a", "given", "task", "could", "not", "be", "deleted", "an", "appengine", ".", "MultiError", "is", "returned", ".", "Each", "task", "is", "deleted", "independently", ";", "one", "may", "fail", "to", "delete", "while", "the", "others", "are", "sucessfully", "deleted", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L369-L402
test
golang/appengine
taskqueue/taskqueue.go
Lease
func Lease(c context.Context, maxTasks int, queueName string, leaseTime int) ([]*Task, error) { return lease(c, maxTasks, queueName, leaseTime, false, nil) }
go
func Lease(c context.Context, maxTasks int, queueName string, leaseTime int) ([]*Task, error) { return lease(c, maxTasks, queueName, leaseTime, false, nil) }
[ "func", "Lease", "(", "c", "context", ".", "Context", ",", "maxTasks", "int", ",", "queueName", "string", ",", "leaseTime", "int", ")", "(", "[", "]", "*", "Task", ",", "error", ")", "{", "return", "lease", "(", "c", ",", "maxTasks", ",", "queueName", ",", "leaseTime", ",", "false", ",", "nil", ")", "\n", "}" ]
// Lease leases tasks from a queue. // leaseTime is in seconds. // The number of tasks fetched will be at most maxTasks.
[ "Lease", "leases", "tasks", "from", "a", "queue", ".", "leaseTime", "is", "in", "seconds", ".", "The", "number", "of", "tasks", "fetched", "will", "be", "at", "most", "maxTasks", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L436-L438
test
golang/appengine
taskqueue/taskqueue.go
LeaseByTag
func LeaseByTag(c context.Context, maxTasks int, queueName string, leaseTime int, tag string) ([]*Task, error) { return lease(c, maxTasks, queueName, leaseTime, true, []byte(tag)) }
go
func LeaseByTag(c context.Context, maxTasks int, queueName string, leaseTime int, tag string) ([]*Task, error) { return lease(c, maxTasks, queueName, leaseTime, true, []byte(tag)) }
[ "func", "LeaseByTag", "(", "c", "context", ".", "Context", ",", "maxTasks", "int", ",", "queueName", "string", ",", "leaseTime", "int", ",", "tag", "string", ")", "(", "[", "]", "*", "Task", ",", "error", ")", "{", "return", "lease", "(", "c", ",", "maxTasks", ",", "queueName", ",", "leaseTime", ",", "true", ",", "[", "]", "byte", "(", "tag", ")", ")", "\n", "}" ]
// LeaseByTag leases tasks from a queue, grouped by tag. // If tag is empty, then the returned tasks are grouped by the tag of the task with earliest ETA. // leaseTime is in seconds. // The number of tasks fetched will be at most maxTasks.
[ "LeaseByTag", "leases", "tasks", "from", "a", "queue", "grouped", "by", "tag", ".", "If", "tag", "is", "empty", "then", "the", "returned", "tasks", "are", "grouped", "by", "the", "tag", "of", "the", "task", "with", "earliest", "ETA", ".", "leaseTime", "is", "in", "seconds", ".", "The", "number", "of", "tasks", "fetched", "will", "be", "at", "most", "maxTasks", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L444-L446
test
golang/appengine
taskqueue/taskqueue.go
Purge
func Purge(c context.Context, queueName string) error { if queueName == "" { queueName = "default" } req := &pb.TaskQueuePurgeQueueRequest{ QueueName: []byte(queueName), } res := &pb.TaskQueuePurgeQueueResponse{} return internal.Call(c, "taskqueue", "PurgeQueue", req, res) }
go
func Purge(c context.Context, queueName string) error { if queueName == "" { queueName = "default" } req := &pb.TaskQueuePurgeQueueRequest{ QueueName: []byte(queueName), } res := &pb.TaskQueuePurgeQueueResponse{} return internal.Call(c, "taskqueue", "PurgeQueue", req, res) }
[ "func", "Purge", "(", "c", "context", ".", "Context", ",", "queueName", "string", ")", "error", "{", "if", "queueName", "==", "\"\"", "{", "queueName", "=", "\"default\"", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "TaskQueuePurgeQueueRequest", "{", "QueueName", ":", "[", "]", "byte", "(", "queueName", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueuePurgeQueueResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"PurgeQueue\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Purge removes all tasks from a queue.
[ "Purge", "removes", "all", "tasks", "from", "a", "queue", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L449-L458
test
golang/appengine
taskqueue/taskqueue.go
ModifyLease
func ModifyLease(c context.Context, task *Task, queueName string, leaseTime int) error { if queueName == "" { queueName = "default" } req := &pb.TaskQueueModifyTaskLeaseRequest{ QueueName: []byte(queueName), TaskName: []byte(task.Name), EtaUsec: proto.Int64(task.ETA.UnixNano() / 1e3), // Used to verify ownership. LeaseSeconds: proto.Float64(float64(leaseTime)), } res := &pb.TaskQueueModifyTaskLeaseResponse{} if err := internal.Call(c, "taskqueue", "ModifyTaskLease", req, res); err != nil { return err } task.ETA = time.Unix(0, *res.UpdatedEtaUsec*1e3) return nil }
go
func ModifyLease(c context.Context, task *Task, queueName string, leaseTime int) error { if queueName == "" { queueName = "default" } req := &pb.TaskQueueModifyTaskLeaseRequest{ QueueName: []byte(queueName), TaskName: []byte(task.Name), EtaUsec: proto.Int64(task.ETA.UnixNano() / 1e3), // Used to verify ownership. LeaseSeconds: proto.Float64(float64(leaseTime)), } res := &pb.TaskQueueModifyTaskLeaseResponse{} if err := internal.Call(c, "taskqueue", "ModifyTaskLease", req, res); err != nil { return err } task.ETA = time.Unix(0, *res.UpdatedEtaUsec*1e3) return nil }
[ "func", "ModifyLease", "(", "c", "context", ".", "Context", ",", "task", "*", "Task", ",", "queueName", "string", ",", "leaseTime", "int", ")", "error", "{", "if", "queueName", "==", "\"\"", "{", "queueName", "=", "\"default\"", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "TaskQueueModifyTaskLeaseRequest", "{", "QueueName", ":", "[", "]", "byte", "(", "queueName", ")", ",", "TaskName", ":", "[", "]", "byte", "(", "task", ".", "Name", ")", ",", "EtaUsec", ":", "proto", ".", "Int64", "(", "task", ".", "ETA", ".", "UnixNano", "(", ")", "/", "1e3", ")", ",", "LeaseSeconds", ":", "proto", ".", "Float64", "(", "float64", "(", "leaseTime", ")", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueueModifyTaskLeaseResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"ModifyTaskLease\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "task", ".", "ETA", "=", "time", ".", "Unix", "(", "0", ",", "*", "res", ".", "UpdatedEtaUsec", "*", "1e3", ")", "\n", "return", "nil", "\n", "}" ]
// ModifyLease modifies the lease of a task. // Used to request more processing time, or to abandon processing. // leaseTime is in seconds and must not be negative.
[ "ModifyLease", "modifies", "the", "lease", "of", "a", "task", ".", "Used", "to", "request", "more", "processing", "time", "or", "to", "abandon", "processing", ".", "leaseTime", "is", "in", "seconds", "and", "must", "not", "be", "negative", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L463-L479
test
golang/appengine
taskqueue/taskqueue.go
QueueStats
func QueueStats(c context.Context, queueNames []string) ([]QueueStatistics, error) { req := &pb.TaskQueueFetchQueueStatsRequest{ QueueName: make([][]byte, len(queueNames)), } for i, q := range queueNames { if q == "" { q = "default" } req.QueueName[i] = []byte(q) } res := &pb.TaskQueueFetchQueueStatsResponse{} if err := internal.Call(c, "taskqueue", "FetchQueueStats", req, res); err != nil { return nil, err } qs := make([]QueueStatistics, len(res.Queuestats)) for i, qsg := range res.Queuestats { qs[i] = QueueStatistics{ Tasks: int(*qsg.NumTasks), } if eta := *qsg.OldestEtaUsec; eta > -1 { qs[i].OldestETA = time.Unix(0, eta*1e3) } if si := qsg.ScannerInfo; si != nil { qs[i].Executed1Minute = int(*si.ExecutedLastMinute) qs[i].InFlight = int(si.GetRequestsInFlight()) qs[i].EnforcedRate = si.GetEnforcedRate() } } return qs, nil }
go
func QueueStats(c context.Context, queueNames []string) ([]QueueStatistics, error) { req := &pb.TaskQueueFetchQueueStatsRequest{ QueueName: make([][]byte, len(queueNames)), } for i, q := range queueNames { if q == "" { q = "default" } req.QueueName[i] = []byte(q) } res := &pb.TaskQueueFetchQueueStatsResponse{} if err := internal.Call(c, "taskqueue", "FetchQueueStats", req, res); err != nil { return nil, err } qs := make([]QueueStatistics, len(res.Queuestats)) for i, qsg := range res.Queuestats { qs[i] = QueueStatistics{ Tasks: int(*qsg.NumTasks), } if eta := *qsg.OldestEtaUsec; eta > -1 { qs[i].OldestETA = time.Unix(0, eta*1e3) } if si := qsg.ScannerInfo; si != nil { qs[i].Executed1Minute = int(*si.ExecutedLastMinute) qs[i].InFlight = int(si.GetRequestsInFlight()) qs[i].EnforcedRate = si.GetEnforcedRate() } } return qs, nil }
[ "func", "QueueStats", "(", "c", "context", ".", "Context", ",", "queueNames", "[", "]", "string", ")", "(", "[", "]", "QueueStatistics", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "TaskQueueFetchQueueStatsRequest", "{", "QueueName", ":", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "queueNames", ")", ")", ",", "}", "\n", "for", "i", ",", "q", ":=", "range", "queueNames", "{", "if", "q", "==", "\"\"", "{", "q", "=", "\"default\"", "\n", "}", "\n", "req", ".", "QueueName", "[", "i", "]", "=", "[", "]", "byte", "(", "q", ")", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "TaskQueueFetchQueueStatsResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"taskqueue\"", ",", "\"FetchQueueStats\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "qs", ":=", "make", "(", "[", "]", "QueueStatistics", ",", "len", "(", "res", ".", "Queuestats", ")", ")", "\n", "for", "i", ",", "qsg", ":=", "range", "res", ".", "Queuestats", "{", "qs", "[", "i", "]", "=", "QueueStatistics", "{", "Tasks", ":", "int", "(", "*", "qsg", ".", "NumTasks", ")", ",", "}", "\n", "if", "eta", ":=", "*", "qsg", ".", "OldestEtaUsec", ";", "eta", ">", "-", "1", "{", "qs", "[", "i", "]", ".", "OldestETA", "=", "time", ".", "Unix", "(", "0", ",", "eta", "*", "1e3", ")", "\n", "}", "\n", "if", "si", ":=", "qsg", ".", "ScannerInfo", ";", "si", "!=", "nil", "{", "qs", "[", "i", "]", ".", "Executed1Minute", "=", "int", "(", "*", "si", ".", "ExecutedLastMinute", ")", "\n", "qs", "[", "i", "]", ".", "InFlight", "=", "int", "(", "si", ".", "GetRequestsInFlight", "(", ")", ")", "\n", "qs", "[", "i", "]", ".", "EnforcedRate", "=", "si", ".", "GetEnforcedRate", "(", ")", "\n", "}", "\n", "}", "\n", "return", "qs", ",", "nil", "\n", "}" ]
// QueueStats retrieves statistics about queues.
[ "QueueStats", "retrieves", "statistics", "about", "queues", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L492-L521
test
golang/appengine
timeout.go
IsTimeoutError
func IsTimeoutError(err error) bool { if err == context.DeadlineExceeded { return true } if t, ok := err.(interface { IsTimeout() bool }); ok { return t.IsTimeout() } return false }
go
func IsTimeoutError(err error) bool { if err == context.DeadlineExceeded { return true } if t, ok := err.(interface { IsTimeout() bool }); ok { return t.IsTimeout() } return false }
[ "func", "IsTimeoutError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "context", ".", "DeadlineExceeded", "{", "return", "true", "\n", "}", "\n", "if", "t", ",", "ok", ":=", "err", ".", "(", "interface", "{", "IsTimeout", "(", ")", "bool", "\n", "}", ")", ";", "ok", "{", "return", "t", ".", "IsTimeout", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTimeoutError reports whether err is a timeout error.
[ "IsTimeoutError", "reports", "whether", "err", "is", "a", "timeout", "error", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/timeout.go#L10-L20
test