rpc_util.go 30 KB

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