rpc_util.go 22 KB

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