rpc_util.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. "context"
  23. "encoding/binary"
  24. "fmt"
  25. "io"
  26. "math"
  27. "strings"
  28. "sync"
  29. "time"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/encoding"
  33. "google.golang.org/grpc/encoding/proto"
  34. "google.golang.org/grpc/internal/transport"
  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. )
  40. // Compressor defines the interface gRPC uses to compress a message.
  41. //
  42. // Deprecated: use package encoding.
  43. type Compressor interface {
  44. // Do compresses p into w.
  45. Do(w io.Writer, p []byte) error
  46. // Type returns the compression algorithm the Compressor uses.
  47. Type() string
  48. }
  49. type gzipCompressor struct {
  50. pool sync.Pool
  51. }
  52. // NewGZIPCompressor creates a Compressor based on GZIP.
  53. //
  54. // Deprecated: use package encoding/gzip.
  55. func NewGZIPCompressor() Compressor {
  56. c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression)
  57. return c
  58. }
  59. // NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
  60. // of assuming DefaultCompression.
  61. //
  62. // The error returned will be nil if the level is valid.
  63. //
  64. // Deprecated: use package encoding/gzip.
  65. func NewGZIPCompressorWithLevel(level int) (Compressor, error) {
  66. if level < gzip.DefaultCompression || level > gzip.BestCompression {
  67. return nil, fmt.Errorf("grpc: invalid compression level: %d", level)
  68. }
  69. return &gzipCompressor{
  70. pool: sync.Pool{
  71. New: func() interface{} {
  72. w, err := gzip.NewWriterLevel(io.Discard, level)
  73. if err != nil {
  74. panic(err)
  75. }
  76. return w
  77. },
  78. },
  79. }, nil
  80. }
  81. func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
  82. z := c.pool.Get().(*gzip.Writer)
  83. defer c.pool.Put(z)
  84. z.Reset(w)
  85. if _, err := z.Write(p); err != nil {
  86. return err
  87. }
  88. return z.Close()
  89. }
  90. func (c *gzipCompressor) Type() string {
  91. return "gzip"
  92. }
  93. // Decompressor defines the interface gRPC uses to decompress a message.
  94. //
  95. // Deprecated: use package encoding.
  96. type Decompressor interface {
  97. // Do reads the data from r and uncompress them.
  98. Do(r io.Reader) ([]byte, error)
  99. // Type returns the compression algorithm the Decompressor uses.
  100. Type() string
  101. }
  102. type gzipDecompressor struct {
  103. pool sync.Pool
  104. }
  105. // NewGZIPDecompressor creates a Decompressor based on GZIP.
  106. //
  107. // Deprecated: use package encoding/gzip.
  108. func NewGZIPDecompressor() Decompressor {
  109. return &gzipDecompressor{}
  110. }
  111. func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
  112. var z *gzip.Reader
  113. switch maybeZ := d.pool.Get().(type) {
  114. case nil:
  115. newZ, err := gzip.NewReader(r)
  116. if err != nil {
  117. return nil, err
  118. }
  119. z = newZ
  120. case *gzip.Reader:
  121. z = maybeZ
  122. if err := z.Reset(r); err != nil {
  123. d.pool.Put(z)
  124. return nil, err
  125. }
  126. }
  127. defer func() {
  128. z.Close()
  129. d.pool.Put(z)
  130. }()
  131. return io.ReadAll(z)
  132. }
  133. func (d *gzipDecompressor) Type() string {
  134. return "gzip"
  135. }
  136. // callInfo contains all related configuration and information about an RPC.
  137. type callInfo struct {
  138. compressorType string
  139. failFast bool
  140. maxReceiveMessageSize *int
  141. maxSendMessageSize *int
  142. creds credentials.PerRPCCredentials
  143. contentSubtype string
  144. codec baseCodec
  145. maxRetryRPCBufferSize int
  146. onFinish []func(err error)
  147. }
  148. func defaultCallInfo() *callInfo {
  149. return &callInfo{
  150. failFast: true,
  151. maxRetryRPCBufferSize: 256 * 1024, // 256KB
  152. }
  153. }
  154. // CallOption configures a Call before it starts or extracts information from
  155. // a Call after it completes.
  156. type CallOption interface {
  157. // before is called before the call is sent to any server. If before
  158. // returns a non-nil error, the RPC fails with that error.
  159. before(*callInfo) error
  160. // after is called after the call has completed. after cannot return an
  161. // error, so any failures should be reported via output parameters.
  162. after(*callInfo, *csAttempt)
  163. }
  164. // EmptyCallOption does not alter the Call configuration.
  165. // It can be embedded in another structure to carry satellite data for use
  166. // by interceptors.
  167. type EmptyCallOption struct{}
  168. func (EmptyCallOption) before(*callInfo) error { return nil }
  169. func (EmptyCallOption) after(*callInfo, *csAttempt) {}
  170. // Header returns a CallOptions that retrieves the header metadata
  171. // for a unary RPC.
  172. func Header(md *metadata.MD) CallOption {
  173. return HeaderCallOption{HeaderAddr: md}
  174. }
  175. // HeaderCallOption is a CallOption for collecting response header metadata.
  176. // The metadata field will be populated *after* the RPC completes.
  177. //
  178. // # Experimental
  179. //
  180. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  181. // later release.
  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, attempt *csAttempt) {
  187. *o.HeaderAddr, _ = attempt.s.Header()
  188. }
  189. // Trailer returns a CallOptions that retrieves the trailer metadata
  190. // for a unary RPC.
  191. func Trailer(md *metadata.MD) CallOption {
  192. return TrailerCallOption{TrailerAddr: md}
  193. }
  194. // TrailerCallOption is a CallOption for collecting response trailer metadata.
  195. // The metadata field will be populated *after* the RPC completes.
  196. //
  197. // # Experimental
  198. //
  199. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  200. // later release.
  201. type TrailerCallOption struct {
  202. TrailerAddr *metadata.MD
  203. }
  204. func (o TrailerCallOption) before(c *callInfo) error { return nil }
  205. func (o TrailerCallOption) after(c *callInfo, attempt *csAttempt) {
  206. *o.TrailerAddr = attempt.s.Trailer()
  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. //
  216. // # Experimental
  217. //
  218. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  219. // later release.
  220. type PeerCallOption struct {
  221. PeerAddr *peer.Peer
  222. }
  223. func (o PeerCallOption) before(c *callInfo) error { return nil }
  224. func (o PeerCallOption) after(c *callInfo, attempt *csAttempt) {
  225. if x, ok := peer.FromContext(attempt.s.Context()); ok {
  226. *o.PeerAddr = *x
  227. }
  228. }
  229. // WaitForReady configures the action to take when an RPC is attempted on broken
  230. // connections or unreachable servers. If waitForReady is false and the
  231. // connection is in the TRANSIENT_FAILURE state, the RPC will fail
  232. // immediately. Otherwise, the RPC client will block the call until a
  233. // connection is available (or the call is canceled or times out) and will
  234. // retry the call if it fails due to a transient error. gRPC will not retry if
  235. // data was written to the wire unless the server indicates it did not process
  236. // the data. Please refer to
  237. // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
  238. //
  239. // By default, RPCs don't "wait for ready".
  240. func WaitForReady(waitForReady bool) CallOption {
  241. return FailFastCallOption{FailFast: !waitForReady}
  242. }
  243. // FailFast is the opposite of WaitForReady.
  244. //
  245. // Deprecated: use WaitForReady.
  246. func FailFast(failFast bool) CallOption {
  247. return FailFastCallOption{FailFast: failFast}
  248. }
  249. // FailFastCallOption is a CallOption for indicating whether an RPC should fail
  250. // fast or not.
  251. //
  252. // # Experimental
  253. //
  254. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  255. // later release.
  256. type FailFastCallOption struct {
  257. FailFast bool
  258. }
  259. func (o FailFastCallOption) before(c *callInfo) error {
  260. c.failFast = o.FailFast
  261. return nil
  262. }
  263. func (o FailFastCallOption) after(c *callInfo, attempt *csAttempt) {}
  264. // OnFinish returns a CallOption that configures a callback to be called when
  265. // the call completes. The error passed to the callback is the status of the
  266. // RPC, and may be nil. The onFinish callback provided will only be called once
  267. // by gRPC. This is mainly used to be used by streaming interceptors, to be
  268. // notified when the RPC completes along with information about the status of
  269. // the RPC.
  270. //
  271. // # Experimental
  272. //
  273. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  274. // later release.
  275. func OnFinish(onFinish func(err error)) CallOption {
  276. return OnFinishCallOption{
  277. OnFinish: onFinish,
  278. }
  279. }
  280. // OnFinishCallOption is CallOption that indicates a callback to be called when
  281. // the call completes.
  282. //
  283. // # Experimental
  284. //
  285. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  286. // later release.
  287. type OnFinishCallOption struct {
  288. OnFinish func(error)
  289. }
  290. func (o OnFinishCallOption) before(c *callInfo) error {
  291. c.onFinish = append(c.onFinish, o.OnFinish)
  292. return nil
  293. }
  294. func (o OnFinishCallOption) after(c *callInfo, attempt *csAttempt) {}
  295. // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size
  296. // in bytes the client can receive. If this is not set, gRPC uses the default
  297. // 4MB.
  298. func MaxCallRecvMsgSize(bytes int) CallOption {
  299. return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes}
  300. }
  301. // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
  302. // size in bytes the client can receive.
  303. //
  304. // # Experimental
  305. //
  306. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  307. // later release.
  308. type MaxRecvMsgSizeCallOption struct {
  309. MaxRecvMsgSize int
  310. }
  311. func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
  312. c.maxReceiveMessageSize = &o.MaxRecvMsgSize
  313. return nil
  314. }
  315. func (o MaxRecvMsgSizeCallOption) after(c *callInfo, attempt *csAttempt) {}
  316. // MaxCallSendMsgSize returns a CallOption which sets the maximum message size
  317. // in bytes the client can send. If this is not set, gRPC uses the default
  318. // `math.MaxInt32`.
  319. func MaxCallSendMsgSize(bytes int) CallOption {
  320. return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes}
  321. }
  322. // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
  323. // size in bytes the client can send.
  324. //
  325. // # Experimental
  326. //
  327. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  328. // later release.
  329. type MaxSendMsgSizeCallOption struct {
  330. MaxSendMsgSize int
  331. }
  332. func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
  333. c.maxSendMessageSize = &o.MaxSendMsgSize
  334. return nil
  335. }
  336. func (o MaxSendMsgSizeCallOption) after(c *callInfo, attempt *csAttempt) {}
  337. // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
  338. // for a call.
  339. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
  340. return PerRPCCredsCallOption{Creds: creds}
  341. }
  342. // PerRPCCredsCallOption is a CallOption that indicates the per-RPC
  343. // credentials to use for the call.
  344. //
  345. // # Experimental
  346. //
  347. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  348. // later release.
  349. type PerRPCCredsCallOption struct {
  350. Creds credentials.PerRPCCredentials
  351. }
  352. func (o PerRPCCredsCallOption) before(c *callInfo) error {
  353. c.creds = o.Creds
  354. return nil
  355. }
  356. func (o PerRPCCredsCallOption) after(c *callInfo, attempt *csAttempt) {}
  357. // UseCompressor returns a CallOption which sets the compressor used when
  358. // sending the request. If WithCompressor is also set, UseCompressor has
  359. // higher priority.
  360. //
  361. // # Experimental
  362. //
  363. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  364. // later release.
  365. func UseCompressor(name string) CallOption {
  366. return CompressorCallOption{CompressorType: name}
  367. }
  368. // CompressorCallOption is a CallOption that indicates the compressor to use.
  369. //
  370. // # Experimental
  371. //
  372. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  373. // later release.
  374. type CompressorCallOption struct {
  375. CompressorType string
  376. }
  377. func (o CompressorCallOption) before(c *callInfo) error {
  378. c.compressorType = o.CompressorType
  379. return nil
  380. }
  381. func (o CompressorCallOption) after(c *callInfo, attempt *csAttempt) {}
  382. // CallContentSubtype returns a CallOption that will set the content-subtype
  383. // for a call. For example, if content-subtype is "json", the Content-Type over
  384. // the wire will be "application/grpc+json". The content-subtype is converted
  385. // to lowercase before being included in Content-Type. See Content-Type on
  386. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  387. // more details.
  388. //
  389. // If ForceCodec is not also used, the content-subtype will be used to look up
  390. // the Codec to use in the registry controlled by RegisterCodec. See the
  391. // documentation on RegisterCodec for details on registration. The lookup of
  392. // content-subtype is case-insensitive. If no such Codec is found, the call
  393. // will result in an error with code codes.Internal.
  394. //
  395. // If ForceCodec is also used, that Codec will be used for all request and
  396. // response messages, with the content-subtype set to the given contentSubtype
  397. // here for requests.
  398. func CallContentSubtype(contentSubtype string) CallOption {
  399. return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
  400. }
  401. // ContentSubtypeCallOption is a CallOption that indicates the content-subtype
  402. // used for marshaling messages.
  403. //
  404. // # Experimental
  405. //
  406. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  407. // later release.
  408. type ContentSubtypeCallOption struct {
  409. ContentSubtype string
  410. }
  411. func (o ContentSubtypeCallOption) before(c *callInfo) error {
  412. c.contentSubtype = o.ContentSubtype
  413. return nil
  414. }
  415. func (o ContentSubtypeCallOption) after(c *callInfo, attempt *csAttempt) {}
  416. // ForceCodec returns a CallOption that will set codec to be used for all
  417. // request and response messages for a call. The result of calling Name() will
  418. // be used as the content-subtype after converting to lowercase, unless
  419. // CallContentSubtype is also used.
  420. //
  421. // See Content-Type on
  422. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  423. // more details. Also see the documentation on RegisterCodec and
  424. // CallContentSubtype for more details on the interaction between Codec and
  425. // content-subtype.
  426. //
  427. // This function is provided for advanced users; prefer to use only
  428. // CallContentSubtype to select a registered codec instead.
  429. //
  430. // # Experimental
  431. //
  432. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  433. // later release.
  434. func ForceCodec(codec encoding.Codec) CallOption {
  435. return ForceCodecCallOption{Codec: codec}
  436. }
  437. // ForceCodecCallOption is a CallOption that indicates the codec used for
  438. // marshaling messages.
  439. //
  440. // # Experimental
  441. //
  442. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  443. // later release.
  444. type ForceCodecCallOption struct {
  445. Codec encoding.Codec
  446. }
  447. func (o ForceCodecCallOption) before(c *callInfo) error {
  448. c.codec = o.Codec
  449. return nil
  450. }
  451. func (o ForceCodecCallOption) after(c *callInfo, attempt *csAttempt) {}
  452. // CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
  453. // an encoding.Codec.
  454. //
  455. // Deprecated: use ForceCodec instead.
  456. func CallCustomCodec(codec Codec) CallOption {
  457. return CustomCodecCallOption{Codec: codec}
  458. }
  459. // CustomCodecCallOption is a CallOption that indicates the codec used for
  460. // marshaling messages.
  461. //
  462. // # Experimental
  463. //
  464. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  465. // later release.
  466. type CustomCodecCallOption struct {
  467. Codec Codec
  468. }
  469. func (o CustomCodecCallOption) before(c *callInfo) error {
  470. c.codec = o.Codec
  471. return nil
  472. }
  473. func (o CustomCodecCallOption) after(c *callInfo, attempt *csAttempt) {}
  474. // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
  475. // used for buffering this RPC's requests for retry purposes.
  476. //
  477. // # Experimental
  478. //
  479. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  480. // later release.
  481. func MaxRetryRPCBufferSize(bytes int) CallOption {
  482. return MaxRetryRPCBufferSizeCallOption{bytes}
  483. }
  484. // MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
  485. // memory to be used for caching this RPC for retry purposes.
  486. //
  487. // # Experimental
  488. //
  489. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  490. // later release.
  491. type MaxRetryRPCBufferSizeCallOption struct {
  492. MaxRetryRPCBufferSize int
  493. }
  494. func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error {
  495. c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize
  496. return nil
  497. }
  498. func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo, attempt *csAttempt) {}
  499. // The format of the payload: compressed or not?
  500. type payloadFormat uint8
  501. const (
  502. compressionNone payloadFormat = 0 // no compression
  503. compressionMade payloadFormat = 1 // compressed
  504. )
  505. // parser reads complete gRPC messages from the underlying reader.
  506. type parser struct {
  507. // r is the underlying reader.
  508. // See the comment on recvMsg for the permissible
  509. // error types.
  510. r io.Reader
  511. // The header of a gRPC message. Find more detail at
  512. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  513. header [5]byte
  514. }
  515. // recvMsg reads a complete gRPC message from the stream.
  516. //
  517. // It returns the message and its payload (compression/encoding)
  518. // format. The caller owns the returned msg memory.
  519. //
  520. // If there is an error, possible values are:
  521. // - io.EOF, when no messages remain
  522. // - io.ErrUnexpectedEOF
  523. // - of type transport.ConnectionError
  524. // - an error from the status package
  525. //
  526. // No other error values or types must be returned, which also means
  527. // that the underlying io.Reader must not return an incompatible
  528. // error.
  529. func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
  530. if _, err := p.r.Read(p.header[:]); err != nil {
  531. return 0, nil, err
  532. }
  533. pf = payloadFormat(p.header[0])
  534. length := binary.BigEndian.Uint32(p.header[1:])
  535. if length == 0 {
  536. return pf, nil, nil
  537. }
  538. if int64(length) > int64(maxInt) {
  539. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
  540. }
  541. if int(length) > maxReceiveMessageSize {
  542. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
  543. }
  544. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  545. // of making it for each message:
  546. msg = make([]byte, int(length))
  547. if _, err := p.r.Read(msg); err != nil {
  548. if err == io.EOF {
  549. err = io.ErrUnexpectedEOF
  550. }
  551. return 0, nil, err
  552. }
  553. return pf, msg, nil
  554. }
  555. // encode serializes msg and returns a buffer containing the message, or an
  556. // error if it is too large to be transmitted by grpc. If msg is nil, it
  557. // generates an empty message.
  558. func encode(c baseCodec, msg interface{}) ([]byte, error) {
  559. if msg == nil { // NOTE: typed nils will not be caught by this check
  560. return nil, nil
  561. }
  562. b, err := c.Marshal(msg)
  563. if err != nil {
  564. return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
  565. }
  566. if uint(len(b)) > math.MaxUint32 {
  567. return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
  568. }
  569. return b, nil
  570. }
  571. // compress returns the input bytes compressed by compressor or cp. If both
  572. // compressors are nil, returns nil.
  573. //
  574. // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
  575. func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
  576. if compressor == nil && cp == nil {
  577. return nil, nil
  578. }
  579. wrapErr := func(err error) error {
  580. return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
  581. }
  582. cbuf := &bytes.Buffer{}
  583. if compressor != nil {
  584. z, err := compressor.Compress(cbuf)
  585. if err != nil {
  586. return nil, wrapErr(err)
  587. }
  588. if _, err := z.Write(in); err != nil {
  589. return nil, wrapErr(err)
  590. }
  591. if err := z.Close(); err != nil {
  592. return nil, wrapErr(err)
  593. }
  594. } else {
  595. if err := cp.Do(cbuf, in); err != nil {
  596. return nil, wrapErr(err)
  597. }
  598. }
  599. return cbuf.Bytes(), nil
  600. }
  601. const (
  602. payloadLen = 1
  603. sizeLen = 4
  604. headerLen = payloadLen + sizeLen
  605. )
  606. // msgHeader returns a 5-byte header for the message being transmitted and the
  607. // payload, which is compData if non-nil or data otherwise.
  608. func msgHeader(data, compData []byte) (hdr []byte, payload []byte) {
  609. hdr = make([]byte, headerLen)
  610. if compData != nil {
  611. hdr[0] = byte(compressionMade)
  612. data = compData
  613. } else {
  614. hdr[0] = byte(compressionNone)
  615. }
  616. // Write length of payload into buf
  617. binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data)))
  618. return hdr, data
  619. }
  620. func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload {
  621. return &stats.OutPayload{
  622. Client: client,
  623. Payload: msg,
  624. Data: data,
  625. Length: len(data),
  626. WireLength: len(payload) + headerLen,
  627. CompressedLength: len(payload),
  628. SentTime: t,
  629. }
  630. }
  631. func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status {
  632. switch pf {
  633. case compressionNone:
  634. case compressionMade:
  635. if recvCompress == "" || recvCompress == encoding.Identity {
  636. return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
  637. }
  638. if !haveCompressor {
  639. return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  640. }
  641. default:
  642. return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
  643. }
  644. return nil
  645. }
  646. type payloadInfo struct {
  647. compressedLength int // The compressed length got from wire.
  648. uncompressedBytes []byte
  649. }
  650. func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) ([]byte, error) {
  651. pf, d, err := p.recvMsg(maxReceiveMessageSize)
  652. if err != nil {
  653. return nil, err
  654. }
  655. if payInfo != nil {
  656. payInfo.compressedLength = len(d)
  657. }
  658. if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil {
  659. return nil, st.Err()
  660. }
  661. var size int
  662. if pf == compressionMade {
  663. // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
  664. // use this decompressor as the default.
  665. if dc != nil {
  666. d, err = dc.Do(bytes.NewReader(d))
  667. size = len(d)
  668. } else {
  669. d, size, err = decompress(compressor, d, maxReceiveMessageSize)
  670. }
  671. if err != nil {
  672. return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err)
  673. }
  674. if size > maxReceiveMessageSize {
  675. // TODO: Revisit the error code. Currently keep it consistent with java
  676. // implementation.
  677. return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message after decompression larger than max (%d vs. %d)", size, maxReceiveMessageSize)
  678. }
  679. }
  680. return d, nil
  681. }
  682. // Using compressor, decompress d, returning data and size.
  683. // Optionally, if data will be over maxReceiveMessageSize, just return the size.
  684. func decompress(compressor encoding.Compressor, d []byte, maxReceiveMessageSize int) ([]byte, int, error) {
  685. dcReader, err := compressor.Decompress(bytes.NewReader(d))
  686. if err != nil {
  687. return nil, 0, err
  688. }
  689. if sizer, ok := compressor.(interface {
  690. DecompressedSize(compressedBytes []byte) int
  691. }); ok {
  692. if size := sizer.DecompressedSize(d); size >= 0 {
  693. if size > maxReceiveMessageSize {
  694. return nil, size, nil
  695. }
  696. // size is used as an estimate to size the buffer, but we
  697. // will read more data if available.
  698. // +MinRead so ReadFrom will not reallocate if size is correct.
  699. buf := bytes.NewBuffer(make([]byte, 0, size+bytes.MinRead))
  700. bytesRead, err := buf.ReadFrom(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1))
  701. return buf.Bytes(), int(bytesRead), err
  702. }
  703. }
  704. // Read from LimitReader with limit max+1. So if the underlying
  705. // reader is over limit, the result will be bigger than max.
  706. d, err = io.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1))
  707. return d, len(d), err
  708. }
  709. // For the two compressor parameters, both should not be set, but if they are,
  710. // dc takes precedence over compressor.
  711. // TODO(dfawley): wrap the old compressor/decompressor using the new API?
  712. func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error {
  713. d, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor)
  714. if err != nil {
  715. return err
  716. }
  717. if err := c.Unmarshal(d, m); err != nil {
  718. return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message: %v", err)
  719. }
  720. if payInfo != nil {
  721. payInfo.uncompressedBytes = d
  722. }
  723. return nil
  724. }
  725. // Information about RPC
  726. type rpcInfo struct {
  727. failfast bool
  728. preloaderInfo *compressorInfo
  729. }
  730. // Information about Preloader
  731. // Responsible for storing codec, and compressors
  732. // If stream (s) has context s.Context which stores rpcInfo that has non nil
  733. // pointers to codec, and compressors, then we can use preparedMsg for Async message prep
  734. // and reuse marshalled bytes
  735. type compressorInfo struct {
  736. codec baseCodec
  737. cp Compressor
  738. comp encoding.Compressor
  739. }
  740. type rpcInfoContextKey struct{}
  741. func newContextWithRPCInfo(ctx context.Context, failfast bool, codec baseCodec, cp Compressor, comp encoding.Compressor) context.Context {
  742. return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{
  743. failfast: failfast,
  744. preloaderInfo: &compressorInfo{
  745. codec: codec,
  746. cp: cp,
  747. comp: comp,
  748. },
  749. })
  750. }
  751. func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
  752. s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
  753. return
  754. }
  755. // Code returns the error code for err if it was produced by the rpc system.
  756. // Otherwise, it returns codes.Unknown.
  757. //
  758. // Deprecated: use status.Code instead.
  759. func Code(err error) codes.Code {
  760. return status.Code(err)
  761. }
  762. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  763. // Otherwise, it returns err.Error() or empty string when err is nil.
  764. //
  765. // Deprecated: use status.Convert and Message method instead.
  766. func ErrorDesc(err error) string {
  767. return status.Convert(err).Message()
  768. }
  769. // Errorf returns an error containing an error code and a description;
  770. // Errorf returns nil if c is OK.
  771. //
  772. // Deprecated: use status.Errorf instead.
  773. func Errorf(c codes.Code, format string, a ...interface{}) error {
  774. return status.Errorf(c, format, a...)
  775. }
  776. // toRPCErr converts an error into an error from the status package.
  777. func toRPCErr(err error) error {
  778. switch err {
  779. case nil, io.EOF:
  780. return err
  781. case context.DeadlineExceeded:
  782. return status.Error(codes.DeadlineExceeded, err.Error())
  783. case context.Canceled:
  784. return status.Error(codes.Canceled, err.Error())
  785. case io.ErrUnexpectedEOF:
  786. return status.Error(codes.Internal, err.Error())
  787. }
  788. switch e := err.(type) {
  789. case transport.ConnectionError:
  790. return status.Error(codes.Unavailable, e.Desc)
  791. case *transport.NewStreamError:
  792. return toRPCErr(e.Err)
  793. }
  794. if _, ok := status.FromError(err); ok {
  795. return err
  796. }
  797. return status.Error(codes.Unknown, err.Error())
  798. }
  799. // setCallInfoCodec should only be called after CallOptions have been applied.
  800. func setCallInfoCodec(c *callInfo) error {
  801. if c.codec != nil {
  802. // codec was already set by a CallOption; use it, but set the content
  803. // subtype if it is not set.
  804. if c.contentSubtype == "" {
  805. // c.codec is a baseCodec to hide the difference between grpc.Codec and
  806. // encoding.Codec (Name vs. String method name). We only support
  807. // setting content subtype from encoding.Codec to avoid a behavior
  808. // change with the deprecated version.
  809. if ec, ok := c.codec.(encoding.Codec); ok {
  810. c.contentSubtype = strings.ToLower(ec.Name())
  811. }
  812. }
  813. return nil
  814. }
  815. if c.contentSubtype == "" {
  816. // No codec specified in CallOptions; use proto by default.
  817. c.codec = encoding.GetCodec(proto.Name)
  818. return nil
  819. }
  820. // c.contentSubtype is already lowercased in CallContentSubtype
  821. c.codec = encoding.GetCodec(c.contentSubtype)
  822. if c.codec == nil {
  823. return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
  824. }
  825. return nil
  826. }
  827. // channelzData is used to store channelz related data for ClientConn, addrConn and Server.
  828. // These fields cannot be embedded in the original structs (e.g. ClientConn), since to do atomic
  829. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  830. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  831. type channelzData struct {
  832. callsStarted int64
  833. callsFailed int64
  834. callsSucceeded int64
  835. // lastCallStartedTime stores the timestamp that last call starts. It is of int64 type instead of
  836. // time.Time since it's more costly to atomically update time.Time variable than int64 variable.
  837. lastCallStartedTime int64
  838. }
  839. // The SupportPackageIsVersion variables are referenced from generated protocol
  840. // buffer files to ensure compatibility with the gRPC version used. The latest
  841. // support package version is 7.
  842. //
  843. // Older versions are kept for compatibility.
  844. //
  845. // These constants should not be referenced from any other code.
  846. const (
  847. SupportPackageIsVersion3 = true
  848. SupportPackageIsVersion4 = true
  849. SupportPackageIsVersion5 = true
  850. SupportPackageIsVersion6 = true
  851. SupportPackageIsVersion7 = true
  852. )
  853. const grpcUA = "grpc-go/" + Version