Debian Codegraph @

vendor/google.golang.org/grpc/stream.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 "errors"
24 "io"
25 "sync"
26 "time"
27
28 "golang.org/x/net/context"
29 "golang.org/x/net/trace"
30 "google.golang.org/grpc/balancer"
31 "google.golang.org/grpc/codes"
32 "google.golang.org/grpc/metadata"
33 "google.golang.org/grpc/peer"
34 "google.golang.org/grpc/stats"
35 "google.golang.org/grpc/status"
36 "google.golang.org/grpc/transport"
37 )
38
39 // StreamHandler defines the handler called by gRPC server to complete the
40 // execution of a streaming RPC.
41 type StreamHandler func(srv interface{}, stream ServerStream) error
42
43 // StreamDesc represents a streaming RPC service's method specification.
44 type StreamDesc struct {
45 StreamName string
46 Handler StreamHandler
47
48 // At least one of these is true.
49 ServerStreams bool
50 ClientStreams bool
51 }
52
53 // Stream defines the common interface a client or server stream has to satisfy.
54 type Stream interface {
55 // Context returns the context for this stream.
56 Context() context.Context
57 // SendMsg blocks until it sends m, the stream is done or the stream
58 // breaks.
59 // On error, it aborts the stream and returns an RPC status on client
60 // side. On server side, it simply returns the error to the caller.
61 // SendMsg is called by generated code. Also Users can call SendMsg
62 // directly when it is really needed in their use cases.
63 // It's safe to have a goroutine calling SendMsg and another goroutine calling
64 // recvMsg on the same stream at the same time.
65 // But it is not safe to call SendMsg on the same stream in different goroutines.
66 SendMsg(m interface{}) error
67 // RecvMsg blocks until it receives a message or the stream is
68 // done. On client side, it returns io.EOF when the stream is done. On
69 // any other error, it aborts the stream and returns an RPC status. On
70 // server side, it simply returns the error to the caller.
71 // It's safe to have a goroutine calling SendMsg and another goroutine calling
72 // recvMsg on the same stream at the same time.
73 // But it is not safe to call RecvMsg on the same stream in different goroutines.
74 RecvMsg(m interface{}) error
75 }
76
77 // ClientStream defines the interface a client stream has to satisfy.
78 type ClientStream interface {
79 // Header returns the header metadata received from the server if there
80 // is any. It blocks if the metadata is not ready to read.
81 Header() (metadata.MD, error)
82 // Trailer returns the trailer metadata from the server, if there is any.
83 // It must only be called after stream.CloseAndRecv has returned, or
84 // stream.Recv has returned a non-nil error (including io.EOF).
85 Trailer() metadata.MD
86 // CloseSend closes the send direction of the stream. It closes the stream
87 // when non-nil error is met.
88 CloseSend() error
89 // Stream.SendMsg() may return a non-nil error when something wrong happens sending
90 // the request. The returned error indicates the status of this sending, not the final
91 // status of the RPC.
92 // Always call Stream.RecvMsg() to get the final status if you care about the status of
93 // the RPC.
94 Stream
95 }
96
97 // NewClientStream creates a new Stream for the client side. This is called
98 // by generated code.
99 func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
100 if cc.dopts.streamInt != nil {
101 return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
102 }
103 return newClientStream(ctx, desc, cc, method, opts...)
104 }
105
106 func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
107 var (
108 t transport.ClientTransport
109 s *transport.Stream
110 done func(balancer.DoneInfo)
111 cancel context.CancelFunc
112 )
113 c := defaultCallInfo()
114 mc := cc.GetMethodConfig(method)
115 if mc.WaitForReady != nil {
116 c.failFast = !*mc.WaitForReady
117 }
118
119 if mc.Timeout != nil {
120 ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
121 defer func() {
122 if err != nil {
123 cancel()
124 }
125 }()
126 }
127
128 opts = append(cc.dopts.callOptions, opts...)
129 for _, o := range opts {
130 if err := o.before(c); err != nil {
131 return nil, toRPCErr(err)
132 }
133 }
134 c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
135 c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
136
137 callHdr := &transport.CallHdr{
138 Host: cc.authority,
139 Method: method,
140 // If it's not client streaming, we should already have the request to be sent,
141 // so we don't flush the header.
142 // If it's client streaming, the user may never send a request or send it any
143 // time soon, so we ask the transport to flush the header.
144 Flush: desc.ClientStreams,
145 }
146 if cc.dopts.cp != nil {
147 callHdr.SendCompress = cc.dopts.cp.Type()
148 }
149 if c.creds != nil {
150 callHdr.Creds = c.creds
151 }
152 var trInfo traceInfo
153 if EnableTracing {
154 trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
155 trInfo.firstLine.client = true
156 if deadline, ok := ctx.Deadline(); ok {
157 trInfo.firstLine.deadline = deadline.Sub(time.Now())
158 }
159 trInfo.tr.LazyLog(&trInfo.firstLine, false)
160 ctx = trace.NewContext(ctx, trInfo.tr)
161 defer func() {
162 if err != nil {
163 // Need to call tr.finish() if error is returned.
164 // Because tr will not be returned to caller.
165 trInfo.tr.LazyPrintf("RPC: [%v]", err)
166 trInfo.tr.SetError()
167 trInfo.tr.Finish()
168 }
169 }()
170 }
171 ctx = newContextWithRPCInfo(ctx, c.failFast)
172 sh := cc.dopts.copts.StatsHandler
173 if sh != nil {
174 ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
175 begin := &stats.Begin{
176 Client: true,
177 BeginTime: time.Now(),
178 FailFast: c.failFast,
179 }
180 sh.HandleRPC(ctx, begin)
181 defer func() {
182 if err != nil {
183 // Only handle end stats if err != nil.
184 end := &stats.End{
185 Client: true,
186 Error: err,
187 }
188 sh.HandleRPC(ctx, end)
189 }
190 }()
191 }
192 for {
193 t, done, err = cc.getTransport(ctx, c.failFast)
194 if err != nil {
195 // TODO(zhaoq): Probably revisit the error handling.
196 if _, ok := status.FromError(err); ok {
197 return nil, err
198 }
199 if err == errConnClosing || err == errConnUnavailable {
200 if c.failFast {
201 return nil, Errorf(codes.Unavailable, "%v", err)
202 }
203 continue
204 }
205 // All the other errors are treated as Internal errors.
206 return nil, Errorf(codes.Internal, "%v", err)
207 }
208
209 s, err = t.NewStream(ctx, callHdr)
210 if err != nil {
211 if _, ok := err.(transport.ConnectionError); ok && done != nil {
212 // If error is connection error, transport was sending data on wire,
213 // and we are not sure if anything has been sent on wire.
214 // If error is not connection error, we are sure nothing has been sent.
215 updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
216 }
217 if done != nil {
218 done(balancer.DoneInfo{Err: err})
219 done = nil
220 }
221 if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
222 continue
223 }
224 return nil, toRPCErr(err)
225 }
226 break
227 }
228 // Set callInfo.peer object from stream's context.
229 if peer, ok := peer.FromContext(s.Context()); ok {
230 c.peer = peer
231 }
232 cs := &clientStream{
233 opts: opts,
234 c: c,
235 desc: desc,
236 codec: cc.dopts.codec,
237 cp: cc.dopts.cp,
238 dc: cc.dopts.dc,
239 cancel: cancel,
240
241 done: done,
242 t: t,
243 s: s,
244 p: &parser{r: s},
245
246 tracing: EnableTracing,
247 trInfo: trInfo,
248
249 statsCtx: ctx,
250 statsHandler: cc.dopts.copts.StatsHandler,
251 }
252 // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination
253 // when there is no pending I/O operations on this stream.
254 go func() {
255 select {
256 case <-t.Error():
257 // Incur transport error, simply exit.
258 case <-cc.ctx.Done():
259 cs.finish(ErrClientConnClosing)
260 cs.closeTransportStream(ErrClientConnClosing)
261 case <-s.Done():
262 // TODO: The trace of the RPC is terminated here when there is no pending
263 // I/O, which is probably not the optimal solution.
264 cs.finish(s.Status().Err())
265 cs.closeTransportStream(nil)
266 case <-s.GoAway():
267 cs.finish(errConnDrain)
268 cs.closeTransportStream(errConnDrain)
269 case <-s.Context().Done():
270 err := s.Context().Err()
271 cs.finish(err)
272 cs.closeTransportStream(transport.ContextErr(err))
273 }
274 }()
275 return cs, nil
276 }
277
278 // clientStream implements a client side Stream.
279 type clientStream struct {
280 opts []CallOption
281 c *callInfo
282 t transport.ClientTransport
283 s *transport.Stream
284 p *parser
285 desc *StreamDesc
286 codec Codec
287 cp Compressor
288 dc Decompressor
289 cancel context.CancelFunc
290
291 tracing bool // set to EnableTracing when the clientStream is created.
292
293 mu sync.Mutex
294 done func(balancer.DoneInfo)
295 closed bool
296 finished bool
297 // trInfo.tr is set when the clientStream is created (if EnableTracing is true),
298 // and is set to nil when the clientStream's finish method is called.
299 trInfo traceInfo
300
301 // statsCtx keeps the user context for stats handling.
302 // All stats collection should use the statsCtx (instead of the stream context)
303 // so that all the generated stats for a particular RPC can be associated in the processing phase.
304 statsCtx context.Context
305 statsHandler stats.Handler
306 }
307
308 func (cs *clientStream) Context() context.Context {
309 return cs.s.Context()
310 }
311
312 func (cs *clientStream) Header() (metadata.MD, error) {
313 m, err := cs.s.Header()
314 if err != nil {
315 if _, ok := err.(transport.ConnectionError); !ok {
316 cs.closeTransportStream(err)
317 }
318 }
319 return m, err
320 }
321
322 func (cs *clientStream) Trailer() metadata.MD {
323 return cs.s.Trailer()
324 }
325
326 func (cs *clientStream) SendMsg(m interface{}) (err error) {
327 if cs.tracing {
328 cs.mu.Lock()
329 if cs.trInfo.tr != nil {
330 cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
331 }
332 cs.mu.Unlock()
333 }
334 // TODO Investigate how to signal the stats handling party.
335 // generate error stats if err != nil && err != io.EOF?
336 defer func() {
337 if err != nil {
338 cs.finish(err)
339 }
340 if err == nil {
341 return
342 }
343 if err == io.EOF {
344 // Specialize the process for server streaming. SendMsg is only called
345 // once when creating the stream object. io.EOF needs to be skipped when
346 // the rpc is early finished (before the stream object is created.).
347 // TODO: It is probably better to move this into the generated code.
348 if !cs.desc.ClientStreams && cs.desc.ServerStreams {
349 err = nil
350 }
351 return
352 }
353 if _, ok := err.(transport.ConnectionError); !ok {
354 cs.closeTransportStream(err)
355 }
356 err = toRPCErr(err)
357 }()
358 var outPayload *stats.OutPayload
359 if cs.statsHandler != nil {
360 outPayload = &stats.OutPayload{
361 Client: true,
362 }
363 }
364 hdr, data, err := encode(cs.codec, m, cs.cp, bytes.NewBuffer([]byte{}), outPayload)
365 if err != nil {
366 return err
367 }
368 if cs.c.maxSendMessageSize == nil {
369 return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
370 }
371 if len(data) > *cs.c.maxSendMessageSize {
372 return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), *cs.c.maxSendMessageSize)
373 }
374 err = cs.t.Write(cs.s, hdr, data, &transport.Options{Last: false})
375 if err == nil && outPayload != nil {
376 outPayload.SentTime = time.Now()
377 cs.statsHandler.HandleRPC(cs.statsCtx, outPayload)
378 }
379 return err
380 }
381
382 func (cs *clientStream) RecvMsg(m interface{}) (err error) {
383 var inPayload *stats.InPayload
384 if cs.statsHandler != nil {
385 inPayload = &stats.InPayload{
386 Client: true,
387 }
388 }
389 if cs.c.maxReceiveMessageSize == nil {
390 return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
391 }
392 err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, inPayload)
393 defer func() {
394 // err != nil indicates the termination of the stream.
395 if err != nil {
396 cs.finish(err)
397 }
398 }()
399 if err == nil {
400 if cs.tracing {
401 cs.mu.Lock()
402 if cs.trInfo.tr != nil {
403 cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
404 }
405 cs.mu.Unlock()
406 }
407 if inPayload != nil {
408 cs.statsHandler.HandleRPC(cs.statsCtx, inPayload)
409 }
410 if !cs.desc.ClientStreams || cs.desc.ServerStreams {
411 return
412 }
413 // Special handling for client streaming rpc.
414 // This recv expects EOF or errors, so we don't collect inPayload.
415 if cs.c.maxReceiveMessageSize == nil {
416 return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
417 }
418 err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, nil)
419 cs.closeTransportStream(err)
420 if err == nil {
421 return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
422 }
423 if err == io.EOF {
424 if se := cs.s.Status().Err(); se != nil {
425 return se
426 }
427 cs.finish(err)
428 return nil
429 }
430 return toRPCErr(err)
431 }
432 if _, ok := err.(transport.ConnectionError); !ok {
433 cs.closeTransportStream(err)
434 }
435 if err == io.EOF {
436 if statusErr := cs.s.Status().Err(); statusErr != nil {
437 return statusErr
438 }
439 // Returns io.EOF to indicate the end of the stream.
440 return
441 }
442 return toRPCErr(err)
443 }
444
445 func (cs *clientStream) CloseSend() (err error) {
446 err = cs.t.Write(cs.s, nil, nil, &transport.Options{Last: true})
447 defer func() {
448 if err != nil {
449 cs.finish(err)
450 }
451 }()
452 if err == nil || err == io.EOF {
453 return nil
454 }
455 if _, ok := err.(transport.ConnectionError); !ok {
456 cs.closeTransportStream(err)
457 }
458 err = toRPCErr(err)
459 return
460 }
461
462 func (cs *clientStream) closeTransportStream(err error) {
463 cs.mu.Lock()
464 if cs.closed {
465 cs.mu.Unlock()
466 return
467 }
468 cs.closed = true
469 cs.mu.Unlock()
470 cs.t.CloseStream(cs.s, err)
471 }
472
473 func (cs *clientStream) finish(err error) {
474 cs.mu.Lock()
475 defer cs.mu.Unlock()
476 if cs.finished {
477 return
478 }
479 cs.finished = true
480 defer func() {
481 if cs.cancel != nil {
482 cs.cancel()
483 }
484 }()
485 for _, o := range cs.opts {
486 o.after(cs.c)
487 }
488 if cs.done != nil {
489 updateRPCInfoInContext(cs.s.Context(), rpcInfo{
490 bytesSent: cs.s.BytesSent(),
491 bytesReceived: cs.s.BytesReceived(),
492 })
493 cs.done(balancer.DoneInfo{Err: err})
494 cs.done = nil
495 }
496 if cs.statsHandler != nil {
497 end := &stats.End{
498 Client: true,
499 EndTime: time.Now(),
500 }
501 if err != io.EOF {
502 // end.Error is nil if the RPC finished successfully.
503 end.Error = toRPCErr(err)
504 }
505 cs.statsHandler.HandleRPC(cs.statsCtx, end)
506 }
507 if !cs.tracing {
508 return
509 }
510 if cs.trInfo.tr != nil {
511 if err == nil || err == io.EOF {
512 cs.trInfo.tr.LazyPrintf("RPC: [OK]")
513 } else {
514 cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
515 cs.trInfo.tr.SetError()
516 }
517 cs.trInfo.tr.Finish()
518 cs.trInfo.tr = nil
519 }
520 }
521
522 // ServerStream defines the interface a server stream has to satisfy.
523 type ServerStream interface {
524 // SetHeader sets the header metadata. It may be called multiple times.
525 // When call multiple times, all the provided metadata will be merged.
526 // All the metadata will be sent out when one of the following happens:
527 // - ServerStream.SendHeader() is called;
528 // - The first response is sent out;
529 // - An RPC status is sent out (error or success).
530 SetHeader(metadata.MD) error
531 // SendHeader sends the header metadata.
532 // The provided md and headers set by SetHeader() will be sent.
533 // It fails if called multiple times.
534 SendHeader(metadata.MD) error
535 // SetTrailer sets the trailer metadata which will be sent with the RPC status.
536 // When called more than once, all the provided metadata will be merged.
537 SetTrailer(metadata.MD)
538 Stream
539 }
540
541 // serverStream implements a server side Stream.
542 type serverStream struct {
543 t transport.ServerTransport
544 s *transport.Stream
545 p *parser
546 codec Codec
547 cp Compressor
548 dc Decompressor
549 maxReceiveMessageSize int
550 maxSendMessageSize int
551 trInfo *traceInfo
552
553 statsHandler stats.Handler
554
555 mu sync.Mutex // protects trInfo.tr after the service handler runs.
556 }
557
558 func (ss *serverStream) Context() context.Context {
559 return ss.s.Context()
560 }
561
562 func (ss *serverStream) SetHeader(md metadata.MD) error {
563 if md.Len() == 0 {
564 return nil
565 }
566 return ss.s.SetHeader(md)
567 }
568
569 func (ss *serverStream) SendHeader(md metadata.MD) error {
570 return ss.t.WriteHeader(ss.s, md)
571 }
572
573 func (ss *serverStream) SetTrailer(md metadata.MD) {
574 if md.Len() == 0 {
575 return
576 }
577 ss.s.SetTrailer(md)
578 return
579 }
580
581 func (ss *serverStream) SendMsg(m interface{}) (err error) {
582 defer func() {
583 if ss.trInfo != nil {
584 ss.mu.Lock()
585 if ss.trInfo.tr != nil {
586 if err == nil {
587 ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
588 } else {
589 ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
590 ss.trInfo.tr.SetError()
591 }
592 }
593 ss.mu.Unlock()
594 }
595 if err != nil && err != io.EOF {
596 st, _ := status.FromError(toRPCErr(err))
597 ss.t.WriteStatus(ss.s, st)
598 }
599 }()
600 var outPayload *stats.OutPayload
601 if ss.statsHandler != nil {
602 outPayload = &stats.OutPayload{}
603 }
604 hdr, data, err := encode(ss.codec, m, ss.cp, bytes.NewBuffer([]byte{}), outPayload)
605 if err != nil {
606 return err
607 }
608 if len(data) > ss.maxSendMessageSize {
609 return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), ss.maxSendMessageSize)
610 }
611 if err := ss.t.Write(ss.s, hdr, data, &transport.Options{Last: false}); err != nil {
612 return toRPCErr(err)
613 }
614 if outPayload != nil {
615 outPayload.SentTime = time.Now()
616 ss.statsHandler.HandleRPC(ss.s.Context(), outPayload)
617 }
618 return nil
619 }
620
621 func (ss *serverStream) RecvMsg(m interface{}) (err error) {
622 defer func() {
623 if ss.trInfo != nil {
624 ss.mu.Lock()
625 if ss.trInfo.tr != nil {
626 if err == nil {
627 ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
628 } else if err != io.EOF {
629 ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
630 ss.trInfo.tr.SetError()
631 }
632 }
633 ss.mu.Unlock()
634 }
635 if err != nil && err != io.EOF {
636 st, _ := status.FromError(toRPCErr(err))
637 ss.t.WriteStatus(ss.s, st)
638 }
639 }()
640 var inPayload *stats.InPayload
641 if ss.statsHandler != nil {
642 inPayload = &stats.InPayload{}
643 }
644 if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload); err != nil {
645 if err == io.EOF {
646 return err
647 }
648 if err == io.ErrUnexpectedEOF {
649 err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
650 }
651 return toRPCErr(err)
652 }
653 if inPayload != nil {
654 ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
655 }
656 return nil
657 }