Debian Codegraph @

vendor/google.golang.org/grpc/rpc_util.go

raw
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
19 package grpc
20
21 import (
22 "bytes"
23 "compress/gzip"
24 stdctx "context"
25 "encoding/binary"
26 "io"
27 "io/ioutil"
28 "math"
29 "os"
30 "sync"
31 "time"
32
33 "golang.org/x/net/context"
34 "google.golang.org/grpc/codes"
35 "google.golang.org/grpc/credentials"
36 "google.golang.org/grpc/metadata"
37 "google.golang.org/grpc/peer"
38 "google.golang.org/grpc/stats"
39 "google.golang.org/grpc/status"
40 "google.golang.org/grpc/transport"
41 )
42
43 // Compressor defines the interface gRPC uses to compress a message.
44 type Compressor interface {
45 // Do compresses p into w.
46 Do(w io.Writer, p []byte) error
47 // Type returns the compression algorithm the Compressor uses.
48 Type() string
49 }
50
51 type gzipCompressor struct {
52 pool sync.Pool
53 }
54
55 // NewGZIPCompressor creates a Compressor based on GZIP.
56 func NewGZIPCompressor() Compressor {
57 return &gzipCompressor{
58 pool: sync.Pool{
59 New: func() interface{} {
60 return gzip.NewWriter(ioutil.Discard)
61 },
62 },
63 }
64 }
65
66 func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
67 z := c.pool.Get().(*gzip.Writer)
68 defer c.pool.Put(z)
69 z.Reset(w)
70 if _, err := z.Write(p); err != nil {
71 return err
72 }
73 return z.Close()
74 }
75
76 func (c *gzipCompressor) Type() string {
77 return "gzip"
78 }
79
80 // Decompressor defines the interface gRPC uses to decompress a message.
81 type Decompressor interface {
82 // Do reads the data from r and uncompress them.
83 Do(r io.Reader) ([]byte, error)
84 // Type returns the compression algorithm the Decompressor uses.
85 Type() string
86 }
87
88 type gzipDecompressor struct {
89 pool sync.Pool
90 }
91
92 // NewGZIPDecompressor creates a Decompressor based on GZIP.
93 func NewGZIPDecompressor() Decompressor {
94 return &gzipDecompressor{}
95 }
96
97 func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
98 var z *gzip.Reader
99 switch maybeZ := d.pool.Get().(type) {
100 case nil:
101 newZ, err := gzip.NewReader(r)
102 if err != nil {
103 return nil, err
104 }
105 z = newZ
106 case *gzip.Reader:
107 z = maybeZ
108 if err := z.Reset(r); err != nil {
109 d.pool.Put(z)
110 return nil, err
111 }
112 }
113
114 defer func() {
115 z.Close()
116 d.pool.Put(z)
117 }()
118 return ioutil.ReadAll(z)
119 }
120
121 func (d *gzipDecompressor) Type() string {
122 return "gzip"
123 }
124
125 // callInfo contains all related configuration and information about an RPC.
126 type callInfo struct {
127 failFast bool
128 headerMD metadata.MD
129 trailerMD metadata.MD
130 peer *peer.Peer
131 traceInfo traceInfo // in trace.go
132 maxReceiveMessageSize *int
133 maxSendMessageSize *int
134 creds credentials.PerRPCCredentials
135 }
136
137 func defaultCallInfo() *callInfo {
138 return &callInfo{failFast: true}
139 }
140
141 // CallOption configures a Call before it starts or extracts information from
142 // a Call after it completes.
143 type CallOption interface {
144 // before is called before the call is sent to any server. If before
145 // returns a non-nil error, the RPC fails with that error.
146 before(*callInfo) error
147
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
153 // EmptyCallOption does not alter the Call configuration.
154 // It can be embedded in another structure to carry satellite data for use
155 // by interceptors.
156 type EmptyCallOption struct{}
157
158 func (EmptyCallOption) before(*callInfo) error { return nil }
159 func (EmptyCallOption) after(*callInfo) {}
160
161 type beforeCall func(c *callInfo) error
162
163 func (o beforeCall) before(c *callInfo) error { return o(c) }
164 func (o beforeCall) after(c *callInfo) {}
165
166 type afterCall func(c *callInfo)
167
168 func (o afterCall) before(c *callInfo) error { return nil }
169 func (o afterCall) after(c *callInfo) { o(c) }
170
171 // Header returns a CallOptions that retrieves the header metadata
172 // for a unary RPC.
173 func Header(md *metadata.MD) CallOption {
174 return afterCall(func(c *callInfo) {
175 *md = c.headerMD
176 })
177 }
178
179 // Trailer returns a CallOptions that retrieves the trailer metadata
180 // for a unary RPC.
181 func Trailer(md *metadata.MD) CallOption {
182 return afterCall(func(c *callInfo) {
183 *md = c.trailerMD
184 })
185 }
186
187 // Peer returns a CallOption that retrieves peer information for a
188 // unary RPC.
189 func Peer(peer *peer.Peer) CallOption {
190 return afterCall(func(c *callInfo) {
191 if c.peer != nil {
192 *peer = *c.peer
193 }
194 })
195 }
196
197 // FailFast configures the action to take when an RPC is attempted on broken
198 // connections or unreachable servers. If failfast is true, the RPC will fail
199 // immediately. Otherwise, the RPC client will block the call until a
200 // connection is available (or the call is canceled or times out) and will retry
201 // the call if it fails due to a transient error. Please refer to
202 // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
203 // Note: failFast is default to true.
204 func FailFast(failFast bool) CallOption {
205 return beforeCall(func(c *callInfo) error {
206 c.failFast = failFast
207 return nil
208 })
209 }
210
211 // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
212 func MaxCallRecvMsgSize(s int) CallOption {
213 return beforeCall(func(o *callInfo) error {
214 o.maxReceiveMessageSize = &s
215 return nil
216 })
217 }
218
219 // MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
220 func MaxCallSendMsgSize(s int) CallOption {
221 return beforeCall(func(o *callInfo) error {
222 o.maxSendMessageSize = &s
223 return nil
224 })
225 }
226
227 // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
228 // for a call.
229 func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
230 return beforeCall(func(c *callInfo) error {
231 c.creds = creds
232 return nil
233 })
234 }
235
236 // The format of the payload: compressed or not?
237 type payloadFormat uint8
238
239 const (
240 compressionNone payloadFormat = iota // no compression
241 compressionMade
242 )
243
244 // parser reads complete gRPC messages from the underlying reader.
245 type parser struct {
246 // r is the underlying reader.
247 // See the comment on recvMsg for the permissible
248 // error types.
249 r io.Reader
250
251 // The header of a gRPC message. Find more detail
252 // at https://grpc.io/docs/guides/wire.html.
253 header [5]byte
254 }
255
256 // recvMsg reads a complete gRPC message from the stream.
257 //
258 // It returns the message and its payload (compression/encoding)
259 // format. The caller owns the returned msg memory.
260 //
261 // If there is an error, possible values are:
262 // * io.EOF, when no messages remain
263 // * io.ErrUnexpectedEOF
264 // * of type transport.ConnectionError
265 // * of type transport.StreamError
266 // No other error values or types must be returned, which also means
267 // that the underlying io.Reader must not return an incompatible
268 // error.
269 func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
270 if _, err := p.r.Read(p.header[:]); err != nil {
271 return 0, nil, err
272 }
273
274 pf = payloadFormat(p.header[0])
275 length := binary.BigEndian.Uint32(p.header[1:])
276
277 if length == 0 {
278 return pf, nil, nil
279 }
280 if length > uint32(maxReceiveMessageSize) {
281 return 0, nil, Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
282 }
283 // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
284 // of making it for each message:
285 msg = make([]byte, int(length))
286 if _, err := p.r.Read(msg); err != nil {
287 if err == io.EOF {
288 err = io.ErrUnexpectedEOF
289 }
290 return 0, nil, err
291 }
292 return pf, msg, nil
293 }
294
295 // encode serializes msg and returns a buffer of message header and a buffer of msg.
296 // If msg is nil, it generates the message header and an empty msg buffer.
297 func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayload *stats.OutPayload) ([]byte, []byte, error) {
298 var b []byte
299 const (
300 payloadLen = 1
301 sizeLen = 4
302 )
303
304 if msg != nil {
305 var err error
306 b, err = c.Marshal(msg)
307 if err != nil {
308 return nil, nil, Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
309 }
310 if outPayload != nil {
311 outPayload.Payload = msg
312 // TODO truncate large payload.
313 outPayload.Data = b
314 outPayload.Length = len(b)
315 }
316 if cp != nil {
317 if err := cp.Do(cbuf, b); err != nil {
318 return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
319 }
320 b = cbuf.Bytes()
321 }
322 }
323
324 if uint(len(b)) > math.MaxUint32 {
325 return nil, nil, Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
326 }
327
328 bufHeader := make([]byte, payloadLen+sizeLen)
329 if cp == nil {
330 bufHeader[0] = byte(compressionNone)
331 } else {
332 bufHeader[0] = byte(compressionMade)
333 }
334 // Write length of b into buf
335 binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b)))
336 if outPayload != nil {
337 outPayload.WireLength = payloadLen + sizeLen + len(b)
338 }
339 return bufHeader, b, nil
340 }
341
342 func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error {
343 switch pf {
344 case compressionNone:
345 case compressionMade:
346 if dc == nil || recvCompress != dc.Type() {
347 return Errorf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
348 }
349 default:
350 return Errorf(codes.Internal, "grpc: received unexpected payload format %d", pf)
351 }
352 return nil
353 }
354
355 func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload) error {
356 pf, d, err := p.recvMsg(maxReceiveMessageSize)
357 if err != nil {
358 return err
359 }
360 if inPayload != nil {
361 inPayload.WireLength = len(d)
362 }
363 if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil {
364 return err
365 }
366 if pf == compressionMade {
367 d, err = dc.Do(bytes.NewReader(d))
368 if err != nil {
369 return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
370 }
371 }
372 if len(d) > maxReceiveMessageSize {
373 // TODO: Revisit the error code. Currently keep it consistent with java
374 // implementation.
375 return Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize)
376 }
377 if err := c.Unmarshal(d, m); err != nil {
378 return Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
379 }
380 if inPayload != nil {
381 inPayload.RecvTime = time.Now()
382 inPayload.Payload = m
383 // TODO truncate large payload.
384 inPayload.Data = d
385 inPayload.Length = len(d)
386 }
387 return nil
388 }
389
390 type rpcInfo struct {
391 failfast bool
392 bytesSent bool
393 bytesReceived bool
394 }
395
396 type rpcInfoContextKey struct{}
397
398 func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context {
399 return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast})
400 }
401
402 func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
403 s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
404 return
405 }
406
407 func updateRPCInfoInContext(ctx context.Context, s rpcInfo) {
408 if ss, ok := rpcInfoFromContext(ctx); ok {
409 ss.bytesReceived = s.bytesReceived
410 ss.bytesSent = s.bytesSent
411 }
412 return
413 }
414
415 // toRPCErr converts an error into an error from the status package.
416 func toRPCErr(err error) error {
417 if _, ok := status.FromError(err); ok {
418 return err
419 }
420 switch e := err.(type) {
421 case transport.StreamError:
422 return status.Error(e.Code, e.Desc)
423 case transport.ConnectionError:
424 return status.Error(codes.Unavailable, e.Desc)
425 default:
426 switch err {
427 case context.DeadlineExceeded, stdctx.DeadlineExceeded:
428 return status.Error(codes.DeadlineExceeded, err.Error())
429 case context.Canceled, stdctx.Canceled:
430 return status.Error(codes.Canceled, err.Error())
431 case ErrClientConnClosing:
432 return status.Error(codes.FailedPrecondition, err.Error())
433 }
434 }
435 return status.Error(codes.Unknown, err.Error())
436 }
437
438 // convertCode converts a standard Go error into its canonical code. Note that
439 // this is only used to translate the error returned by the server applications.
440 func convertCode(err error) codes.Code {
441 switch err {
442 case nil:
443 return codes.OK
444 case io.EOF:
445 return codes.OutOfRange
446 case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
447 return codes.FailedPrecondition
448 case os.ErrInvalid:
449 return codes.InvalidArgument
450 case context.Canceled, stdctx.Canceled:
451 return codes.Canceled
452 case context.DeadlineExceeded, stdctx.DeadlineExceeded:
453 return codes.DeadlineExceeded
454 }
455 switch {
456 case os.IsExist(err):
457 return codes.AlreadyExists
458 case os.IsNotExist(err):
459 return codes.NotFound
460 case os.IsPermission(err):
461 return codes.PermissionDenied
462 }
463 return codes.Unknown
464 }
465
466 // Code returns the error code for err if it was produced by the rpc system.
467 // Otherwise, it returns codes.Unknown.
468 //
469 // Deprecated; use status.FromError and Code method instead.
470 func Code(err error) codes.Code {
471 if s, ok := status.FromError(err); ok {
472 return s.Code()
473 }
474 return codes.Unknown
475 }
476
477 // ErrorDesc returns the error description of err if it was produced by the rpc system.
478 // Otherwise, it returns err.Error() or empty string when err is nil.
479 //
480 // Deprecated; use status.FromError and Message method instead.
481 func ErrorDesc(err error) string {
482 if s, ok := status.FromError(err); ok {
483 return s.Message()
484 }
485 return err.Error()
486 }
487
488 // Errorf returns an error containing an error code and a description;
489 // Errorf returns nil if c is OK.
490 //
491 // Deprecated; use status.Errorf instead.
492 func Errorf(c codes.Code, format string, a ...interface{}) error {
493 return status.Errorf(c, format, a...)
494 }
495
496 // MethodConfig defines the configuration recommended by the service providers for a
497 // particular method.
498 // This is EXPERIMENTAL and subject to change.
499 type MethodConfig struct {
500 // WaitForReady indicates whether RPCs sent to this method should wait until
501 // the connection is ready by default (!failfast). The value specified via the
502 // gRPC client API will override the value set here.
503 WaitForReady *bool
504 // Timeout is the default timeout for RPCs sent to this method. The actual
505 // deadline used will be the minimum of the value specified here and the value
506 // set by the application via the gRPC client API. If either one is not set,
507 // then the other will be used. If neither is set, then the RPC has no deadline.
508 Timeout *time.Duration
509 // MaxReqSize is the maximum allowed payload size for an individual request in a
510 // stream (client->server) in bytes. The size which is measured is the serialized
511 // payload after per-message compression (but before stream compression) in bytes.
512 // The actual value used is the minimum of the value specified here and the value set
513 // by the application via the gRPC client API. If either one is not set, then the other
514 // will be used. If neither is set, then the built-in default is used.
515 MaxReqSize *int
516 // MaxRespSize is the maximum allowed payload size for an individual response in a
517 // stream (server->client) in bytes.
518 MaxRespSize *int
519 }
520
521 // ServiceConfig is provided by the service provider and contains parameters for how
522 // clients that connect to the service should behave.
523 // This is EXPERIMENTAL and subject to change.
524 type ServiceConfig struct {
525 // LB is the load balancer the service providers recommends. The balancer specified
526 // via grpc.WithBalancer will override this.
527 LB Balancer
528 // Methods contains a map for the methods in this service.
529 // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig.
530 // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists.
531 // Otherwise, the method has no MethodConfig to use.
532 Methods map[string]MethodConfig
533 }
534
535 func min(a, b *int) *int {
536 if *a < *b {
537 return a
538 }
539 return b
540 }
541
542 func getMaxSize(mcMax, doptMax *int, defaultVal int) *int {
543 if mcMax == nil && doptMax == nil {
544 return &defaultVal
545 }
546 if mcMax != nil && doptMax != nil {
547 return min(mcMax, doptMax)
548 }
549 if mcMax != nil {
550 return mcMax
551 }
552 return doptMax
553 }
554
555 // SupportPackageIsVersion3 is referenced from generated protocol buffer files.
556 // The latest support package version is 4.
557 // SupportPackageIsVersion3 is kept for compatibility. It will be removed in the
558 // next support package version update.
559 const SupportPackageIsVersion3 = true
560
561 // SupportPackageIsVersion4 is referenced from generated protocol buffer files
562 // to assert that that code is compatible with this version of the grpc package.
563 //
564 // This constant may be renamed in the future if a change in the generated code
565 // requires a synchronised update of grpc-go and protoc-gen-go. This constant
566 // should not be referenced from any other code.
567 const SupportPackageIsVersion4 = true
568
569 // Version is the current grpc version.
570 const Version = "1.7.5"
571
572 const grpcUA = "grpc-go/" + Version