Home | History | Annotate | Download | only in grpc
      1 /*
      2  *
      3  * Copyright 2014 gRPC authors.
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  *
     17  */
     18 
     19 package grpc
     20 
     21 import (
     22 	"bytes"
     23 	"compress/gzip"
     24 	"encoding/binary"
     25 	"fmt"
     26 	"io"
     27 	"io/ioutil"
     28 	"math"
     29 	"net/url"
     30 	"strings"
     31 	"sync"
     32 	"time"
     33 
     34 	"golang.org/x/net/context"
     35 	"google.golang.org/grpc/codes"
     36 	"google.golang.org/grpc/credentials"
     37 	"google.golang.org/grpc/encoding"
     38 	"google.golang.org/grpc/encoding/proto"
     39 	"google.golang.org/grpc/metadata"
     40 	"google.golang.org/grpc/peer"
     41 	"google.golang.org/grpc/stats"
     42 	"google.golang.org/grpc/status"
     43 	"google.golang.org/grpc/transport"
     44 )
     45 
     46 // Compressor defines the interface gRPC uses to compress a message.
     47 //
     48 // Deprecated: use package encoding.
     49 type Compressor interface {
     50 	// Do compresses p into w.
     51 	Do(w io.Writer, p []byte) error
     52 	// Type returns the compression algorithm the Compressor uses.
     53 	Type() string
     54 }
     55 
     56 type gzipCompressor struct {
     57 	pool sync.Pool
     58 }
     59 
     60 // NewGZIPCompressor creates a Compressor based on GZIP.
     61 //
     62 // Deprecated: use package encoding/gzip.
     63 func NewGZIPCompressor() Compressor {
     64 	c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression)
     65 	return c
     66 }
     67 
     68 // NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
     69 // of assuming DefaultCompression.
     70 //
     71 // The error returned will be nil if the level is valid.
     72 //
     73 // Deprecated: use package encoding/gzip.
     74 func NewGZIPCompressorWithLevel(level int) (Compressor, error) {
     75 	if level < gzip.DefaultCompression || level > gzip.BestCompression {
     76 		return nil, fmt.Errorf("grpc: invalid compression level: %d", level)
     77 	}
     78 	return &gzipCompressor{
     79 		pool: sync.Pool{
     80 			New: func() interface{} {
     81 				w, err := gzip.NewWriterLevel(ioutil.Discard, level)
     82 				if err != nil {
     83 					panic(err)
     84 				}
     85 				return w
     86 			},
     87 		},
     88 	}, nil
     89 }
     90 
     91 func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
     92 	z := c.pool.Get().(*gzip.Writer)
     93 	defer c.pool.Put(z)
     94 	z.Reset(w)
     95 	if _, err := z.Write(p); err != nil {
     96 		return err
     97 	}
     98 	return z.Close()
     99 }
    100 
    101 func (c *gzipCompressor) Type() string {
    102 	return "gzip"
    103 }
    104 
    105 // Decompressor defines the interface gRPC uses to decompress a message.
    106 //
    107 // Deprecated: use package encoding.
    108 type Decompressor interface {
    109 	// Do reads the data from r and uncompress them.
    110 	Do(r io.Reader) ([]byte, error)
    111 	// Type returns the compression algorithm the Decompressor uses.
    112 	Type() string
    113 }
    114 
    115 type gzipDecompressor struct {
    116 	pool sync.Pool
    117 }
    118 
    119 // NewGZIPDecompressor creates a Decompressor based on GZIP.
    120 //
    121 // Deprecated: use package encoding/gzip.
    122 func NewGZIPDecompressor() Decompressor {
    123 	return &gzipDecompressor{}
    124 }
    125 
    126 func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
    127 	var z *gzip.Reader
    128 	switch maybeZ := d.pool.Get().(type) {
    129 	case nil:
    130 		newZ, err := gzip.NewReader(r)
    131 		if err != nil {
    132 			return nil, err
    133 		}
    134 		z = newZ
    135 	case *gzip.Reader:
    136 		z = maybeZ
    137 		if err := z.Reset(r); err != nil {
    138 			d.pool.Put(z)
    139 			return nil, err
    140 		}
    141 	}
    142 
    143 	defer func() {
    144 		z.Close()
    145 		d.pool.Put(z)
    146 	}()
    147 	return ioutil.ReadAll(z)
    148 }
    149 
    150 func (d *gzipDecompressor) Type() string {
    151 	return "gzip"
    152 }
    153 
    154 // callInfo contains all related configuration and information about an RPC.
    155 type callInfo struct {
    156 	compressorType        string
    157 	failFast              bool
    158 	stream                *clientStream
    159 	traceInfo             traceInfo // in trace.go
    160 	maxReceiveMessageSize *int
    161 	maxSendMessageSize    *int
    162 	creds                 credentials.PerRPCCredentials
    163 	contentSubtype        string
    164 	codec                 baseCodec
    165 }
    166 
    167 func defaultCallInfo() *callInfo {
    168 	return &callInfo{failFast: true}
    169 }
    170 
    171 // CallOption configures a Call before it starts or extracts information from
    172 // a Call after it completes.
    173 type CallOption interface {
    174 	// before is called before the call is sent to any server.  If before
    175 	// returns a non-nil error, the RPC fails with that error.
    176 	before(*callInfo) error
    177 
    178 	// after is called after the call has completed.  after cannot return an
    179 	// error, so any failures should be reported via output parameters.
    180 	after(*callInfo)
    181 }
    182 
    183 // EmptyCallOption does not alter the Call configuration.
    184 // It can be embedded in another structure to carry satellite data for use
    185 // by interceptors.
    186 type EmptyCallOption struct{}
    187 
    188 func (EmptyCallOption) before(*callInfo) error { return nil }
    189 func (EmptyCallOption) after(*callInfo)        {}
    190 
    191 // Header returns a CallOptions that retrieves the header metadata
    192 // for a unary RPC.
    193 func Header(md *metadata.MD) CallOption {
    194 	return HeaderCallOption{HeaderAddr: md}
    195 }
    196 
    197 // HeaderCallOption is a CallOption for collecting response header metadata.
    198 // The metadata field will be populated *after* the RPC completes.
    199 // This is an EXPERIMENTAL API.
    200 type HeaderCallOption struct {
    201 	HeaderAddr *metadata.MD
    202 }
    203 
    204 func (o HeaderCallOption) before(c *callInfo) error { return nil }
    205 func (o HeaderCallOption) after(c *callInfo) {
    206 	if c.stream != nil {
    207 		*o.HeaderAddr, _ = c.stream.Header()
    208 	}
    209 }
    210 
    211 // Trailer returns a CallOptions that retrieves the trailer metadata
    212 // for a unary RPC.
    213 func Trailer(md *metadata.MD) CallOption {
    214 	return TrailerCallOption{TrailerAddr: md}
    215 }
    216 
    217 // TrailerCallOption is a CallOption for collecting response trailer metadata.
    218 // The metadata field will be populated *after* the RPC completes.
    219 // This is an EXPERIMENTAL API.
    220 type TrailerCallOption struct {
    221 	TrailerAddr *metadata.MD
    222 }
    223 
    224 func (o TrailerCallOption) before(c *callInfo) error { return nil }
    225 func (o TrailerCallOption) after(c *callInfo) {
    226 	if c.stream != nil {
    227 		*o.TrailerAddr = c.stream.Trailer()
    228 	}
    229 }
    230 
    231 // Peer returns a CallOption that retrieves peer information for a unary RPC.
    232 // The peer field will be populated *after* the RPC completes.
    233 func Peer(p *peer.Peer) CallOption {
    234 	return PeerCallOption{PeerAddr: p}
    235 }
    236 
    237 // PeerCallOption is a CallOption for collecting the identity of the remote
    238 // peer. The peer field will be populated *after* the RPC completes.
    239 // This is an EXPERIMENTAL API.
    240 type PeerCallOption struct {
    241 	PeerAddr *peer.Peer
    242 }
    243 
    244 func (o PeerCallOption) before(c *callInfo) error { return nil }
    245 func (o PeerCallOption) after(c *callInfo) {
    246 	if c.stream != nil {
    247 		if x, ok := peer.FromContext(c.stream.Context()); ok {
    248 			*o.PeerAddr = *x
    249 		}
    250 	}
    251 }
    252 
    253 // FailFast configures the action to take when an RPC is attempted on broken
    254 // connections or unreachable servers.  If failFast is true, the RPC will fail
    255 // immediately. Otherwise, the RPC client will block the call until a
    256 // connection is available (or the call is canceled or times out) and will
    257 // retry the call if it fails due to a transient error.  gRPC will not retry if
    258 // data was written to the wire unless the server indicates it did not process
    259 // the data.  Please refer to
    260 // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
    261 //
    262 // By default, RPCs are "Fail Fast".
    263 func FailFast(failFast bool) CallOption {
    264 	return FailFastCallOption{FailFast: failFast}
    265 }
    266 
    267 // FailFastCallOption is a CallOption for indicating whether an RPC should fail
    268 // fast or not.
    269 // This is an EXPERIMENTAL API.
    270 type FailFastCallOption struct {
    271 	FailFast bool
    272 }
    273 
    274 func (o FailFastCallOption) before(c *callInfo) error {
    275 	c.failFast = o.FailFast
    276 	return nil
    277 }
    278 func (o FailFastCallOption) after(c *callInfo) {}
    279 
    280 // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
    281 func MaxCallRecvMsgSize(s int) CallOption {
    282 	return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s}
    283 }
    284 
    285 // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
    286 // size the client can receive.
    287 // This is an EXPERIMENTAL API.
    288 type MaxRecvMsgSizeCallOption struct {
    289 	MaxRecvMsgSize int
    290 }
    291 
    292 func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
    293 	c.maxReceiveMessageSize = &o.MaxRecvMsgSize
    294 	return nil
    295 }
    296 func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {}
    297 
    298 // MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
    299 func MaxCallSendMsgSize(s int) CallOption {
    300 	return MaxSendMsgSizeCallOption{MaxSendMsgSize: s}
    301 }
    302 
    303 // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
    304 // size the client can send.
    305 // This is an EXPERIMENTAL API.
    306 type MaxSendMsgSizeCallOption struct {
    307 	MaxSendMsgSize int
    308 }
    309 
    310 func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
    311 	c.maxSendMessageSize = &o.MaxSendMsgSize
    312 	return nil
    313 }
    314 func (o MaxSendMsgSizeCallOption) after(c *callInfo) {}
    315 
    316 // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
    317 // for a call.
    318 func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
    319 	return PerRPCCredsCallOption{Creds: creds}
    320 }
    321 
    322 // PerRPCCredsCallOption is a CallOption that indicates the per-RPC
    323 // credentials to use for the call.
    324 // This is an EXPERIMENTAL API.
    325 type PerRPCCredsCallOption struct {
    326 	Creds credentials.PerRPCCredentials
    327 }
    328 
    329 func (o PerRPCCredsCallOption) before(c *callInfo) error {
    330 	c.creds = o.Creds
    331 	return nil
    332 }
    333 func (o PerRPCCredsCallOption) after(c *callInfo) {}
    334 
    335 // UseCompressor returns a CallOption which sets the compressor used when
    336 // sending the request.  If WithCompressor is also set, UseCompressor has
    337 // higher priority.
    338 //
    339 // This API is EXPERIMENTAL.
    340 func UseCompressor(name string) CallOption {
    341 	return CompressorCallOption{CompressorType: name}
    342 }
    343 
    344 // CompressorCallOption is a CallOption that indicates the compressor to use.
    345 // This is an EXPERIMENTAL API.
    346 type CompressorCallOption struct {
    347 	CompressorType string
    348 }
    349 
    350 func (o CompressorCallOption) before(c *callInfo) error {
    351 	c.compressorType = o.CompressorType
    352 	return nil
    353 }
    354 func (o CompressorCallOption) after(c *callInfo) {}
    355 
    356 // CallContentSubtype returns a CallOption that will set the content-subtype
    357 // for a call. For example, if content-subtype is "json", the Content-Type over
    358 // the wire will be "application/grpc+json". The content-subtype is converted
    359 // to lowercase before being included in Content-Type. See Content-Type on
    360 // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
    361 // more details.
    362 //
    363 // If CallCustomCodec is not also used, the content-subtype will be used to
    364 // look up the Codec to use in the registry controlled by RegisterCodec. See
    365 // the documentation on RegisterCodec for details on registration. The lookup
    366 // of content-subtype is case-insensitive. If no such Codec is found, the call
    367 // will result in an error with code codes.Internal.
    368 //
    369 // If CallCustomCodec is also used, that Codec will be used for all request and
    370 // response messages, with the content-subtype set to the given contentSubtype
    371 // here for requests.
    372 func CallContentSubtype(contentSubtype string) CallOption {
    373 	return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
    374 }
    375 
    376 // ContentSubtypeCallOption is a CallOption that indicates the content-subtype
    377 // used for marshaling messages.
    378 // This is an EXPERIMENTAL API.
    379 type ContentSubtypeCallOption struct {
    380 	ContentSubtype string
    381 }
    382 
    383 func (o ContentSubtypeCallOption) before(c *callInfo) error {
    384 	c.contentSubtype = o.ContentSubtype
    385 	return nil
    386 }
    387 func (o ContentSubtypeCallOption) after(c *callInfo) {}
    388 
    389 // CallCustomCodec returns a CallOption that will set the given Codec to be
    390 // used for all request and response messages for a call. The result of calling
    391 // String() will be used as the content-subtype in a case-insensitive manner.
    392 //
    393 // See Content-Type on
    394 // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
    395 // more details. Also see the documentation on RegisterCodec and
    396 // CallContentSubtype for more details on the interaction between Codec and
    397 // content-subtype.
    398 //
    399 // This function is provided for advanced users; prefer to use only
    400 // CallContentSubtype to select a registered codec instead.
    401 func CallCustomCodec(codec Codec) CallOption {
    402 	return CustomCodecCallOption{Codec: codec}
    403 }
    404 
    405 // CustomCodecCallOption is a CallOption that indicates the codec used for
    406 // marshaling messages.
    407 // This is an EXPERIMENTAL API.
    408 type CustomCodecCallOption struct {
    409 	Codec Codec
    410 }
    411 
    412 func (o CustomCodecCallOption) before(c *callInfo) error {
    413 	c.codec = o.Codec
    414 	return nil
    415 }
    416 func (o CustomCodecCallOption) after(c *callInfo) {}
    417 
    418 // The format of the payload: compressed or not?
    419 type payloadFormat uint8
    420 
    421 const (
    422 	compressionNone payloadFormat = 0 // no compression
    423 	compressionMade payloadFormat = 1 // compressed
    424 )
    425 
    426 // parser reads complete gRPC messages from the underlying reader.
    427 type parser struct {
    428 	// r is the underlying reader.
    429 	// See the comment on recvMsg for the permissible
    430 	// error types.
    431 	r io.Reader
    432 
    433 	// The header of a gRPC message. Find more detail at
    434 	// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
    435 	header [5]byte
    436 }
    437 
    438 // recvMsg reads a complete gRPC message from the stream.
    439 //
    440 // It returns the message and its payload (compression/encoding)
    441 // format. The caller owns the returned msg memory.
    442 //
    443 // If there is an error, possible values are:
    444 //   * io.EOF, when no messages remain
    445 //   * io.ErrUnexpectedEOF
    446 //   * of type transport.ConnectionError
    447 //   * of type transport.StreamError
    448 // No other error values or types must be returned, which also means
    449 // that the underlying io.Reader must not return an incompatible
    450 // error.
    451 func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
    452 	if _, err := p.r.Read(p.header[:]); err != nil {
    453 		return 0, nil, err
    454 	}
    455 
    456 	pf = payloadFormat(p.header[0])
    457 	length := binary.BigEndian.Uint32(p.header[1:])
    458 
    459 	if length == 0 {
    460 		return pf, nil, nil
    461 	}
    462 	if int64(length) > int64(maxInt) {
    463 		return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
    464 	}
    465 	if int(length) > maxReceiveMessageSize {
    466 		return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
    467 	}
    468 	// TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
    469 	// of making it for each message:
    470 	msg = make([]byte, int(length))
    471 	if _, err := p.r.Read(msg); err != nil {
    472 		if err == io.EOF {
    473 			err = io.ErrUnexpectedEOF
    474 		}
    475 		return 0, nil, err
    476 	}
    477 	return pf, msg, nil
    478 }
    479 
    480 // encode serializes msg and returns a buffer containing the message, or an
    481 // error if it is too large to be transmitted by grpc.  If msg is nil, it
    482 // generates an empty message.
    483 func encode(c baseCodec, msg interface{}) ([]byte, error) {
    484 	if msg == nil { // NOTE: typed nils will not be caught by this check
    485 		return nil, nil
    486 	}
    487 	b, err := c.Marshal(msg)
    488 	if err != nil {
    489 		return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
    490 	}
    491 	if uint(len(b)) > math.MaxUint32 {
    492 		return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
    493 	}
    494 	return b, nil
    495 }
    496 
    497 // compress returns the input bytes compressed by compressor or cp.  If both
    498 // compressors are nil, returns nil.
    499 //
    500 // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
    501 func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
    502 	if compressor == nil && cp == nil {
    503 		return nil, nil
    504 	}
    505 	wrapErr := func(err error) error {
    506 		return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
    507 	}
    508 	cbuf := &bytes.Buffer{}
    509 	if compressor != nil {
    510 		z, _ := compressor.Compress(cbuf)
    511 		if _, err := z.Write(in); err != nil {
    512 			return nil, wrapErr(err)
    513 		}
    514 		if err := z.Close(); err != nil {
    515 			return nil, wrapErr(err)
    516 		}
    517 	} else {
    518 		if err := cp.Do(cbuf, in); err != nil {
    519 			return nil, wrapErr(err)
    520 		}
    521 	}
    522 	return cbuf.Bytes(), nil
    523 }
    524 
    525 const (
    526 	payloadLen = 1
    527 	sizeLen    = 4
    528 	headerLen  = payloadLen + sizeLen
    529 )
    530 
    531 // msgHeader returns a 5-byte header for the message being transmitted and the
    532 // payload, which is compData if non-nil or data otherwise.
    533 func msgHeader(data, compData []byte) (hdr []byte, payload []byte) {
    534 	hdr = make([]byte, headerLen)
    535 	if compData != nil {
    536 		hdr[0] = byte(compressionMade)
    537 		data = compData
    538 	} else {
    539 		hdr[0] = byte(compressionNone)
    540 	}
    541 
    542 	// Write length of payload into buf
    543 	binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data)))
    544 	return hdr, data
    545 }
    546 
    547 func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload {
    548 	return &stats.OutPayload{
    549 		Client:     client,
    550 		Payload:    msg,
    551 		Data:       data,
    552 		Length:     len(data),
    553 		WireLength: len(payload) + headerLen,
    554 		SentTime:   t,
    555 	}
    556 }
    557 
    558 func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status {
    559 	switch pf {
    560 	case compressionNone:
    561 	case compressionMade:
    562 		if recvCompress == "" || recvCompress == encoding.Identity {
    563 			return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
    564 		}
    565 		if !haveCompressor {
    566 			return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
    567 		}
    568 	default:
    569 		return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
    570 	}
    571 	return nil
    572 }
    573 
    574 // For the two compressor parameters, both should not be set, but if they are,
    575 // dc takes precedence over compressor.
    576 // TODO(dfawley): wrap the old compressor/decompressor using the new API?
    577 func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload, compressor encoding.Compressor) error {
    578 	pf, d, err := p.recvMsg(maxReceiveMessageSize)
    579 	if err != nil {
    580 		return err
    581 	}
    582 	if inPayload != nil {
    583 		inPayload.WireLength = len(d)
    584 	}
    585 
    586 	if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil {
    587 		return st.Err()
    588 	}
    589 
    590 	if pf == compressionMade {
    591 		// To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
    592 		// use this decompressor as the default.
    593 		if dc != nil {
    594 			d, err = dc.Do(bytes.NewReader(d))
    595 			if err != nil {
    596 				return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
    597 			}
    598 		} else {
    599 			dcReader, err := compressor.Decompress(bytes.NewReader(d))
    600 			if err != nil {
    601 				return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
    602 			}
    603 			d, err = ioutil.ReadAll(dcReader)
    604 			if err != nil {
    605 				return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
    606 			}
    607 		}
    608 	}
    609 	if len(d) > maxReceiveMessageSize {
    610 		// TODO: Revisit the error code. Currently keep it consistent with java
    611 		// implementation.
    612 		return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize)
    613 	}
    614 	if err := c.Unmarshal(d, m); err != nil {
    615 		return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
    616 	}
    617 	if inPayload != nil {
    618 		inPayload.RecvTime = time.Now()
    619 		inPayload.Payload = m
    620 		// TODO truncate large payload.
    621 		inPayload.Data = d
    622 		inPayload.Length = len(d)
    623 	}
    624 	return nil
    625 }
    626 
    627 type rpcInfo struct {
    628 	failfast bool
    629 }
    630 
    631 type rpcInfoContextKey struct{}
    632 
    633 func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context {
    634 	return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast})
    635 }
    636 
    637 func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
    638 	s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
    639 	return
    640 }
    641 
    642 // Code returns the error code for err if it was produced by the rpc system.
    643 // Otherwise, it returns codes.Unknown.
    644 //
    645 // Deprecated: use status.FromError and Code method instead.
    646 func Code(err error) codes.Code {
    647 	if s, ok := status.FromError(err); ok {
    648 		return s.Code()
    649 	}
    650 	return codes.Unknown
    651 }
    652 
    653 // ErrorDesc returns the error description of err if it was produced by the rpc system.
    654 // Otherwise, it returns err.Error() or empty string when err is nil.
    655 //
    656 // Deprecated: use status.FromError and Message method instead.
    657 func ErrorDesc(err error) string {
    658 	if s, ok := status.FromError(err); ok {
    659 		return s.Message()
    660 	}
    661 	return err.Error()
    662 }
    663 
    664 // Errorf returns an error containing an error code and a description;
    665 // Errorf returns nil if c is OK.
    666 //
    667 // Deprecated: use status.Errorf instead.
    668 func Errorf(c codes.Code, format string, a ...interface{}) error {
    669 	return status.Errorf(c, format, a...)
    670 }
    671 
    672 // setCallInfoCodec should only be called after CallOptions have been applied.
    673 func setCallInfoCodec(c *callInfo) error {
    674 	if c.codec != nil {
    675 		// codec was already set by a CallOption; use it.
    676 		return nil
    677 	}
    678 
    679 	if c.contentSubtype == "" {
    680 		// No codec specified in CallOptions; use proto by default.
    681 		c.codec = encoding.GetCodec(proto.Name)
    682 		return nil
    683 	}
    684 
    685 	// c.contentSubtype is already lowercased in CallContentSubtype
    686 	c.codec = encoding.GetCodec(c.contentSubtype)
    687 	if c.codec == nil {
    688 		return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
    689 	}
    690 	return nil
    691 }
    692 
    693 // parseDialTarget returns the network and address to pass to dialer
    694 func parseDialTarget(target string) (net string, addr string) {
    695 	net = "tcp"
    696 
    697 	m1 := strings.Index(target, ":")
    698 	m2 := strings.Index(target, ":/")
    699 
    700 	// handle unix:addr which will fail with url.Parse
    701 	if m1 >= 0 && m2 < 0 {
    702 		if n := target[0:m1]; n == "unix" {
    703 			net = n
    704 			addr = target[m1+1:]
    705 			return net, addr
    706 		}
    707 	}
    708 	if m2 >= 0 {
    709 		t, err := url.Parse(target)
    710 		if err != nil {
    711 			return net, target
    712 		}
    713 		scheme := t.Scheme
    714 		addr = t.Path
    715 		if scheme == "unix" {
    716 			net = scheme
    717 			if addr == "" {
    718 				addr = t.Host
    719 			}
    720 			return net, addr
    721 		}
    722 	}
    723 
    724 	return net, target
    725 }
    726 
    727 // The SupportPackageIsVersion variables are referenced from generated protocol
    728 // buffer files to ensure compatibility with the gRPC version used.  The latest
    729 // support package version is 5.
    730 //
    731 // Older versions are kept for compatibility. They may be removed if
    732 // compatibility cannot be maintained.
    733 //
    734 // These constants should not be referenced from any other code.
    735 const (
    736 	SupportPackageIsVersion3 = true
    737 	SupportPackageIsVersion4 = true
    738 	SupportPackageIsVersion5 = true
    739 )
    740 
    741 const grpcUA = "grpc-go/" + Version
    742