rpc_util.go 23 KB

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