func (sender *lengthPrefixTCPSender) Send(msg []byte) error {
	l := len(msg)
	if l > maxTCPMsgSize {
		return fmt.Errorf("outgoing message exceeds maximum size: %d > %d", l, maxTCPMsgSize)
	}
	// We copy the message so we can send it in a single Write
	// operation, thus making this thread-safe without locking.
	prefixedMsg := make([]byte, 4+l)
	binary.BigEndian.PutUint32(prefixedMsg, uint32(l))
	copy(prefixedMsg[4:], msg)
	_, err := sender.writer.Write(prefixedMsg)
	return err
}

// Send implements TCPSender by writing the size of the msg as a big-endian
// uint32 before the msg. msgs larger than MaxTCPMsgSize are rejected.

Send implements TCPSender by writing the size of the msg as a big - endian uint32 before the msg . msgs larger than MaxTCPMsgSize are rejected .


func (sender *encryptedTCPSender) Send(msg []byte) error {
	sender.Lock()
	defer sender.Unlock()
	encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)
	sender.state.advance()
	return sender.sender.Send(encodedMsg)
}

func ( sender * encryptedTCPSender ) Send ( msg [ ] byte ) error { sender . Lock ( ) defer sender . Unlock ( ) encodedMsg := secretbox . Seal ( nil , msg , & sender . state . nonce , sender . state . sessionKey ) sender . state . advance ( ) return sender . sender . Send ( encodedMsg ) }

// Send implements TCPSender by sealing and sending the msg as-is.

Send implements TCPSender by sealing and sending the msg as - is .


func (receiver *gobTCPReceiver) Receive() ([]byte, error) {
	var msg []byte
	err := receiver.decoder.Decode(&msg)
	return msg, err
}

func ( receiver * gobTCPReceiver ) Receive ( ) ( [ ] byte , error ) { var msg [ ] byte err := receiver . decoder . Decode ( & msg ) return msg , err }

// Receive implements TCPReciever by Gob decoding into a byte slice directly.

Receive implements TCPReciever by Gob decoding into a byte slice directly .


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 ) if _ , err := io . ReadFull ( receiver . reader , lenPrefix ) ; err != nil { return nil , err } l := binary . BigEndian . Uint32 ( lenPrefix ) if l > maxTCPMsgSize { return nil , fmt . Errorf ( " " , l , maxTCPMsgSize ) } msg := make ( [ ] byte , l ) _ , err := io . ReadFull ( receiver . reader , msg ) return msg , err }

// 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 .


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 ( ) if err != nil { return nil , err } decodedMsg , success := secretbox . Open ( nil , msg , & receiver . state . nonce , receiver . state . sessionKey ) if ! success { return nil , fmt . Errorf ( " " ) } receiver . state . advance ( ) return decodedMsg , nil }

// 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 .


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
(
)
)
p
:=
&
peer
{
st
:
newState
(
self
)
,
send
:
,
// must .register() later
actions
:
actions
,
quit
:
make
(
chan
struct
{
}
)
,
logger
:
logger
,
}
go
p
.
loop
(
actions
)
return
p
}

// 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 .


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 { } ) p . actions <- func ( ) { defer close ( c ) st := p . st . incr ( ) if p . send != nil { p . send . GossipBroadcast ( st ) } else { p . logger . Printf ( " " ) } result = st . get ( ) } <- c return result }


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 ( ) p . logger . Printf ( " " , complete . ( * state ) . set ) return complete }


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 if err := gob . NewDecoder ( bytes . NewReader ( buf ) ) . Decode ( & set ) ; err != nil { return err } complete := p . st . mergeComplete ( set ) p . logger . Printf ( " " , src , set , complete ) return nil }

// Merge the gossiped data represented by buf into our state.

Merge the gossiped data represented by buf into our state .


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
:
,
// TODO(pb): ??
}
}

// 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 .


func (peer *Peer) String() string {
	return fmt.Sprint(peer.Name, "(", peer.NickName, ")")
}

func ( peer * Peer ) String ( ) string { return fmt . Sprint ( peer . Name , " " , peer . NickName , " " ) }

// String returns the peer name and nickname.

String returns the peer name and nickname .


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 } if _ , found := exclude [ remoteName ] ; found { continue } remotePeer := conn . Remote ( ) if remoteConn , found := remotePeer . connections [ peer . Name ] ; ! establishedAndSymmetric || ( found && remoteConn . isEstablished ( ) ) { f ( remotePeer ) } } }

// 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 .


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 ) return PeerUID ( uid ) , err }

// ParsePeerUID parses a decimal peer UID from a string.

ParsePeerUID parses a decimal peer UID from a string .


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 ] }


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 }


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 } 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 ( " " ) } return }

// DoIntro executes the protocol introduction.

DoIntro executes the protocol introduction .


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 ) for _ , k := range protocolV1Features { if val , ok := intro [ k ] ; ok { safe [ k ] = val } } return 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.

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 .


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 ) 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 }

// 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 .


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 ] target . state = targetWaiting target . lastError = err target . nextTryLater ( ) return true } }

// 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 .


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 ) 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 }

// NewGossipSender constructs a usable GossipSender.

NewGossipSender constructs a usable GossipSender .


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 ( ) defer s . Unlock ( ) if s . empty ( ) { defer s . prod ( ) } if s . gossip == nil { s . gossip = data } else { s . gossip = s . gossip . Merge ( data ) } }

// 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 .


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 ( ) 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 ) } }

// 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 .


func (s *gossipSender) Flush() bool {
	ch := make(chan bool)
	s.flush <- ch
	return <-ch
}

func ( s * gossipSender ) Flush ( ) bool { ch := make ( chan bool ) s . flush <- ch return <- ch }

// 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 .


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 ( ) defer gs . Unlock ( ) s , found := gs . senders [ channelName ] if ! found { s = makeGossipSender ( gs . sender , gs . stop ) gs . senders [ channelName ] = s } return s }

// 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 .


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 gs . Lock ( ) defer gs . Unlock ( ) for _ , sender := range gs . senders { sent = sender . Flush ( ) || sent } return sent }

// Flush flushes all managed senders. Used for testing.

Flush flushes all managed senders . Used for testing .


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 ""
}

// Find the path to package main by looking at the root Caller.

Find the path to package main by looking at the root Caller .


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 , } resp := & pb . CreateChannelResponse { } err = internal . Call ( c , service , " " , req , resp ) token = resp . GetToken ( ) return token , remapError ( err ) }

// 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 .


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 , } resp := & basepb . VoidProto { } return remapError ( internal . Call ( c , service , " " , req , resp ) ) }

// Send sends a message on the channel associated with clientID.

Send sends a message on the channel associated with clientID .


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 ) if err != nil { return err } return Send ( c , clientID , string ( m ) ) }

// 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 .


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 == " " { e . Service = " " } } return err }

// remapError fixes any APIError referencing "xmpp" into one referencing "channel".

remapError fixes any APIError referencing xmpp into one referencing channel .


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 ) }

// NamespacedContext wraps a Context to support namespaces.

NamespacedContext wraps a Context to support namespaces .


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 ( ) , } }

// protoToItem converts a protocol buffer item to a Go struct.

protoToItem converts a protocol buffer item to a Go struct .


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 ] } return err }

// 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 .


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 } ) if err != nil { return nil , err } if _ , ok := m [ key ] ; ! ok { return nil , ErrCacheMiss } return m [ key ] , nil }

// 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 .


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 } 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 , " " , " " , 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 }

// 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 .


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 } ) ) }

// 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 .


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
}
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
,
"
"
,
"
"
,
req
,
res
)
;
err
!=
{
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
}

// 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 .


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 ) }

// 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 .


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 ) }

// 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 .


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
}

// 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 .


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 ) if err != nil { return nil , err } if err := cd . Unmarshal ( i . Value , v ) ; err != nil { return nil , err } return i , nil }

// 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 .


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 { } res := & pb . MemcacheStatsResponse { } if err := internal . Call ( c , " " , " " , 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 }

// Stats retrieves the current memcache statistics.

Stats retrieves the current memcache statistics .


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 { } res := & pb . MemcacheFlushResponse { } return internal . Call ( c , " " , " " , req , res ) }

// Flush flushes all items from memcache.


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 { } res := & pb . StartBackgroundRequestResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } sendc <- send { res . GetRequestId ( ) , f } return nil }

// 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 .


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 { } res := & pb . GetModulesResponse { } err := internal . Call ( c , " " , " " , req , res ) return res . Module , err }

// List returns the names of modules belonging to this application.

List returns the names of modules belonging to this application .


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 { } if module != " " { req . Module = & module } if version != " " { req . Version = & version } req . Instances = proto . Int64 ( int64 ( instances ) ) res := & pb . SetNumInstancesResponse { } return internal . Call ( c , " " , " " , req , res ) }

// 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 .


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 { } if module != " " { req . Module = & module } res := & pb . GetVersionsResponse { } err := internal . Call ( c , " " , " " , req , res ) return res . GetVersion ( ) , err }

// 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 .


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 { } if module != " " { req . Module = & module } res := & pb . GetDefaultVersionResponse { } err := internal . Call ( c , " " , " " , req , res ) return res . GetVersion ( ) , err }

// 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 .


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 { } if module != " " { req . Module = & module } if version != " " { req . Version = & version } res := & pb . StartModuleResponse { } return internal . Call ( c , " " , " " , req , res ) }

// 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 .


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 { } if module != " " { req . Module = & module } if version != " " { req . Version = & version } res := & pb . StopModuleResponse { } return internal . Call ( c , " " , " " , req , res ) }

// 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 .


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 ( ) if ancestor == nil { q . err = errors . New ( " " ) return q } q . ancestor = ancestor return q }

// 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 .


func (q *Query) EventualConsistency() *Query {
	q = q.clone()
	q.eventual = true
	return q
}

func ( q * Query ) EventualConsistency ( ) * Query { q = q . clone ( ) q . eventual = true return q }

// 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 .


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 ( ) q . projection = append ( [ ] string ( nil ) , fieldNames ... ) return q }

// 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 .


func (q *Query) Distinct() *Query {
	q = q.clone()
	q.distinct = true
	return q
}

func ( q * Query ) Distinct ( ) * Query { q = q . clone ( ) q . distinct = true return q }

// 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 .


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 ( ) q . distinctOn = fieldNames return q }

// 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 .


func (q *Query) KeysOnly() *Query {
	q = q.clone()
	q.keysOnly = true
	return q
}

func ( q * Query ) KeysOnly ( ) * Query { q = q . clone ( ) q . keysOnly = true return q }

// 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 .


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 ( ) if limit < math . MinInt32 || limit > math . MaxInt32 { q . err = errors . New ( " " ) return q } q . limit = int32 ( limit ) return q }

// 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 .


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 ( ) if offset < 0 { q . err = errors . New ( " " ) return q } if offset > math . MaxInt32 { q . err = errors . New ( " " ) return q } q . offset = int32 ( offset ) return q }

// 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 .


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 ( ) if size <= 0 || size > math . MaxInt32 { q . err = errors . New ( " " ) return q } q . count = int32 ( size ) return q }

// 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 .


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 ( ) if c . cc == nil { q . err = errors . New ( " " ) return q } q . start = c . cc return q }

// Start returns a derivative query with the given start point.

Start returns a derivative query with the given start point .


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 ( ) if c . cc == nil { q . err = errors . New ( " " ) return q } q . end = c . cc return q }

// End returns a derivative query with the given end point.

End returns a derivative query with the given end point .


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
}

// 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 .


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 } } 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 , " " , " " , & 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 ( " " ) break } offset -= skip } if offset < 0 { t . err = errors . New ( " " ) } return t }

// Run runs the query in the given context.

Run runs the query in the given context .


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 ( ) if err != nil { return nil , err } if dst != nil && ! t . q . keysOnly { err = loadEntity ( dst , e ) } return k , err }

// 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 .


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
}

// Cursor returns a cursor for the iterator's current location.

Cursor returns a cursor for the iterator s current location .


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), "=")
}

// String returns a base-64 string representation of a cursor.

String returns a base - 64 string representation of a cursor .


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 } 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 }

// Decode decodes a cursor from its base-64 string representation.

Decode decodes a cursor from its base - 64 string representation .


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 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 ) }

// saveEntity saves an EntityProto into a PropertyLoadSaver or struct pointer.

saveEntity saves an EntityProto into a PropertyLoadSaver or struct pointer .


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 ( " " , namespace , validNamespace ) } return internal . NamespacedContext ( c , namespace ) , nil }

// Namespace returns a replacement context that operates within the given namespace.

Namespace returns a replacement context that operates within the given namespace .


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 } } if cfg . Func != nil { if t := cfg . Func [ name ] ; t != " " { return " " + t } } return " " }

// 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 .


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 } } 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 " " }

// 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 .


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 := " " if len ( out ) == 1 { outs = " " + out [ 0 ] } else if len ( out ) > 1 { outs = " " + join ( out ) + " " } return " " + join ( in ) + " " + outs }

// joinFunc is the inverse of splitFunc.


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 } 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 }

// 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 . .


func getStructCodec(t reflect.Type) (*structCodec, error) {
	structCodecsMutex.Lock()
	defer structCodecsMutex.Unlock()
	return getStructCodecLocked(t)
}

func getStructCodec ( t reflect . Type ) ( * structCodec , error ) { structCodecsMutex . Lock ( ) defer structCodecsMutex . Unlock ( ) return getStructCodecLocked ( t ) }

// getStructCodec returns the structCodec for the given struct type.

getStructCodec returns the structCodec for the given struct type .


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 ) if err != nil { return err } return x . Load ( p ) }

// 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 .


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 ) if err != nil { return nil , err } return x . Save ( ) }

// 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 .


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)
}

// ServingURL returns a URL that will serve an image from Blobstore.

ServingURL returns a URL that will serve an image from Blobstore .


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 ) , } res := & pb . ImagesDeleteUrlBaseResponse { } return internal . Call ( c , " " , " " , req , res ) }

// DeleteServingURL deletes the serving URL for an image.

DeleteServingURL deletes the serving URL for an image .


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
}

// 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 .


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 { } res := & pb . CheckOAuthSignatureResponse { } err := internal . Call ( c , " " , " " , req , res ) if err != nil { return " " , err } return * res . OauthConsumerKey , err }

// 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 .


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 ) ] } if u . FederatedIdentity != " " { return u . FederatedIdentity } return u . Email }

// String returns a displayable name for the user.

String returns a displayable name for the user .


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 , " " ) }

// 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 .


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 ) , } if identity != " " { req . FederatedIdentity = proto . String ( identity ) } res := & pb . CreateLoginURLResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return " " , err } return * res . LoginUrl , nil }

// LoginURLFederated is like LoginURL but accepts a user's OpenID identifier.

LoginURLFederated is like LoginURL but accepts a user s OpenID identifier .


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 ) , } res := & pb . CreateLogoutURLResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return " " , err } return * res . LogoutUrl , nil }

// 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 .


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 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
}

// 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 .


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 ) ctx = internal . WithLogOverride ( ctx , c . logf ) ctx = internal . WithAppIDOverride ( ctx , c . appID ) return ctx }

// 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 .


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 ) if err != nil { return nil , err } return c . NewContext ( context . Background ( ) ) , nil }

// 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 .


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 ... ) }

// 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 .


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)
}

// guestbookKey returns the key used for all guestbook entries.

guestbookKey returns the key used for all guestbook entries .


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 { } 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 }

// toRetryParameter converts RetryOptions to pb.TaskQueueRetryParameters.

toRetryParameter converts RetryOptions to pb . TaskQueueRetryParameters .


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 ) h . Set ( " " , " " ) return & Task { Path : path , Payload : [ ] byte ( params . Encode ( ) ) , Header : h , Method : " " , } }

// 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 .


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 ( " " ) , TaskName : h . Get ( " " ) , } ret . TaskRetryCount , _ = strconv . ParseInt ( h . Get ( " " ) , 10 , 64 ) ret . TaskExecutionCount , _ = strconv . ParseInt ( h . Get ( " " ) , 10 , 64 ) etaSecs , _ := strconv . ParseInt ( h . Get ( " " ) , 10 , 64 ) if etaSecs != 0 { ret . TaskETA = time . Unix ( etaSecs , 0 ) } ret . TaskPreviousResponse , _ = strconv . Atoi ( h . Get ( " " ) ) ret . TaskRetryReason = h . Get ( " " ) if h . Get ( " " ) != " " { ret . FailFast = true } return ret }

// 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 .


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 ) if err != nil { return nil , err } res := & pb . TaskQueueAddResponse { } if err := internal . Call ( c , " " , " " , 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 }

// 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 .


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 ) ) , } 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 , " " , " " , req , res ) ; err != nil { return nil , err } if len ( res . Taskresult ) != len ( tasks ) { return nil , errors . New ( " " ) } 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 : " " , Code : int32 ( * tr . Result ) , } } any = true } } if any { return tasksOut , me } return tasksOut , nil }

// 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 .


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 ) if me , ok := err . ( appengine . MultiError ) ; ok { return me [ 0 ] } return err }

// Delete deletes a task from a named queue.

Delete deletes a task from a named queue .


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 ) ) for i , t := range tasks { taskNames [ i ] = [ ] byte ( t . Name ) } if queueName == " " { queueName = " " } req := & pb . TaskQueueDeleteRequest { QueueName : [ ] byte ( queueName ) , TaskName : taskNames , } res := & pb . TaskQueueDeleteResponse { } if err := internal . Call ( c , " " , " " , req , res ) ; err != nil { return err } if a , b := len ( req . TaskName ) , len ( res . Result ) ; a != b { return fmt . Errorf ( " " , 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 : " " , Code : int32 ( ec ) , } any = true } } if any { return me } return nil }

// 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 .


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 ) }

// 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 .


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 ) ) }

// 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 .


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 = " " } req := & pb . TaskQueuePurgeQueueRequest { QueueName : [ ] byte ( queueName ) , } res := & pb . TaskQueuePurgeQueueResponse { } return internal . Call ( c , " " , " " , req , res ) }

// Purge removes all tasks from a queue.


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
=
"
"
}
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
,
"
"
,
"
"
,
req
,
res
)
;
err
!=
{
return
err
}
task
.
ETA
=
time
.
Unix
(
0
,
*
res
.
UpdatedEtaUsec
*
1e3
)
return
}

// 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 .


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 ) ) , } for i , q := range queueNames { if q == " " { q = " " } req . QueueName [ i ] = [ ] byte ( q ) } res := & pb . TaskQueueFetchQueueStatsResponse { } if err := internal . Call ( c , " " , " " , 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 }

// QueueStats retrieves statistics about queues.

QueueStats retrieves statistics about queues .


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 } if t , ok := err . ( interface { IsTimeout ( ) bool } ) ; ok { return t . IsTimeout ( ) } return false }

// IsTimeoutError reports whether err is a timeout error.

IsTimeoutError reports whether err is a timeout error .


func Func(key string, i interface{}) *Function {
	f := &Function{fv: reflect.ValueOf(i)}

	// Derive unique, somewhat stable key for this func.
	_, file, _, _ := runtime.Caller(1)
	fk, err := fileKey(file)
	if err != nil {
		// Not fatal, but log the error
		stdlog.Printf("delay: %v", err)
	}
	f.key = fk + ":" + key

	t := f.fv.Type()
	if t.Kind() != reflect.Func {
		f.err = errors.New("not a function")
		return f
	}
	if t.NumIn() == 0 || !isContext(t.In(0)) {
		f.err = errFirstArg
		return f
	}

	// Register the function's arguments with the gob package.
	// This is required because they are marshaled inside a []interface{}.
	// gob.Register only expects to be called during initialization;
	// that's fine because this function expects the same.
	for i := 0; i < t.NumIn(); i++ {
		// Only concrete types may be registered. If the argument has
		// interface type, the client is resposible for registering the
		// concrete types it will hold.
		if t.In(i).Kind() == reflect.Interface {
			continue
		}
		gob.Register(reflect.Zero(t.In(i)).Interface())
	}

	if old := funcs[f.key]; old != nil {
		old.err = fmt.Errorf("multiple functions registered for %s in %s", key, file)
	}
	funcs[f.key] = f
	return f
}

// Func declares a new Function. The second argument must be a function with a
// first argument of type context.Context.
// This function must be called at program initialization time. That means it
// must be called in a global variable declaration or from an init function.
// This restriction is necessary because the instance that delays a function
// call may not be the one that executes it. Only the code executed at program
// initialization time is guaranteed to have been run by an instance before it
// receives a request.

Func declares a new Function . The second argument must be a function with a first argument of type context . Context . This function must be called at program initialization time . That means it must be called in a global variable declaration or from an init function . This restriction is necessary because the instance that delays a function call may not be the one that executes it . Only the code executed at program initialization time is guaranteed to have been run by an instance before it receives a request .


func (f *Function) Task(args ...interface{}) (*taskqueue.Task, error) {
	if f.err != nil {
		return nil, fmt.Errorf("delay: func is invalid: %v", f.err)
	}

	nArgs := len(args) + 1 // +1 for the context.Context
	ft := f.fv.Type()
	minArgs := ft.NumIn()
	if ft.IsVariadic() {
		minArgs--
	}
	if nArgs < minArgs {
		return nil, fmt.Errorf("delay: too few arguments to func: %d < %d", nArgs, minArgs)
	}
	if !ft.IsVariadic() && nArgs > minArgs {
		return nil, fmt.Errorf("delay: too many arguments to func: %d > %d", nArgs, minArgs)
	}

	// Check arg types.
	for i := 1; i < nArgs; i++ {
		at := reflect.TypeOf(args[i-1])
		var dt reflect.Type
		if i < minArgs {
			// not a variadic arg
			dt = ft.In(i)
		} else {
			// a variadic arg
			dt = ft.In(minArgs).Elem()
		}
		// nil arguments won't have a type, so they need special handling.
		if at == nil {
			// nil interface
			switch dt.Kind() {
			case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
				continue // may be nil
			}
			return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not nilable", i, dt)
		}
		switch at.Kind() {
		case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
			av := reflect.ValueOf(args[i-1])
			if av.IsNil() {
				// nil value in interface; not supported by gob, so we replace it
				// with a nil interface value
				args[i-1] = nil
			}
		}
		if !at.AssignableTo(dt) {
			return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not assignable to %v", i, at, dt)
		}
	}

	inv := invocation{
		Key:  f.key,
		Args: args,
	}

	buf := new(bytes.Buffer)
	if err := gob.NewEncoder(buf).Encode(inv); err != nil {
		return nil, fmt.Errorf("delay: gob encoding failed: %v", err)
	}

	return &taskqueue.Task{
		Path:    path,
		Payload: buf.Bytes(),
	}, nil
}

// Task creates a Task that will invoke the function.
// Its parameters may be tweaked before adding it to a queue.
// Users should not modify the Path or Payload fields of the returned Task.

Task creates a Task that will invoke the function . Its parameters may be tweaked before adding it to a queue . Users should not modify the Path or Payload fields of the returned Task .


func RequestHeaders(c context.Context) (*taskqueue.RequestHeaders, error) {
	if ret, ok := c.Value(headersContextKey).(*taskqueue.RequestHeaders); ok {
		return ret, nil
	}
	return nil, errOutsideDelayFunc
}

func RequestHeaders ( c context . Context ) ( * taskqueue . RequestHeaders , error ) { if ret , ok := c . Value ( headersContextKey ) . ( * taskqueue . RequestHeaders ) ; ok { return ret , nil } return nil , errOutsideDelayFunc }

// Request returns the special task-queue HTTP request headers for the current
// task queue handler. Returns an error if called from outside a delay.Func.

Request returns the special task - queue HTTP request headers for the current task queue handler . Returns an error if called from outside a delay . Func .


func WithContext(parent context.Context, req *http.Request) context.Context {
	return internal.WithContext(parent, req)
}

func WithContext ( parent context . Context , req * http . Request ) context . Context { return internal . WithContext ( parent , req ) }

// WithContext returns a copy of the parent context
// and associates it with an in-flight HTTP request.
// This function is cheap.

WithContext returns a copy of the parent context and associates it with an in - flight HTTP request . This function is cheap .


func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context {
	return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f))
}

func WithAPICallFunc ( ctx context . Context , f APICallFunc ) context . Context { return internal . WithCallOverride ( ctx , internal . CallOverrideFunc ( f ) ) }

// WithAPICallFunc returns a copy of the parent context
// that will cause API calls to invoke f instead of their normal operation.
//
// This is intended for advanced users only.

WithAPICallFunc returns a copy of the parent context that will cause API calls to invoke f instead of their normal operation . This is intended for advanced users only .


func APICall(ctx context.Context, service, method string, in, out proto.Message) error {
	return internal.Call(ctx, service, method, in, out)
}

func APICall ( ctx context . Context , service , method string , in , out proto . Message ) error { return internal . Call ( ctx , service , method , in , out ) }

// APICall performs an API call.
//
// This is not intended for general use; it is exported for use in conjunction
// with WithAPICallFunc.

APICall performs an API call . This is not intended for general use ; it is exported for use in conjunction with WithAPICallFunc .