rpc_util.go 21 KB

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