3 * Copyright 2014 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
28 "golang.org/x/net/context"
29 "golang.org/x/net/trace"
30 "google.golang.org/grpc/codes"
31 "google.golang.org/grpc/metadata"
32 "google.golang.org/grpc/peer"
33 "google.golang.org/grpc/stats"
34 "google.golang.org/grpc/status"
35 "google.golang.org/grpc/transport"
38 // StreamHandler defines the handler called by gRPC server to complete the
39 // execution of a streaming RPC.
40 type StreamHandler func(srv interface{}, stream ServerStream) error
42 // StreamDesc represents a streaming RPC service's method specification.
43 type StreamDesc struct {
47 // At least one of these is true.
52 // Stream defines the common interface a client or server stream has to satisfy.
53 type Stream interface {
54 // Context returns the context for this stream.
55 Context() context.Context
56 // SendMsg blocks until it sends m, the stream is done or the stream
58 // On error, it aborts the stream and returns an RPC status on client
59 // side. On server side, it simply returns the error to the caller.
60 // SendMsg is called by generated code. Also Users can call SendMsg
61 // directly when it is really needed in their use cases.
62 // It's safe to have a goroutine calling SendMsg and another goroutine calling
63 // recvMsg on the same stream at the same time.
64 // But it is not safe to call SendMsg on the same stream in different goroutines.
65 SendMsg(m interface{}) error
66 // RecvMsg blocks until it receives a message or the stream is
67 // done. On client side, it returns io.EOF when the stream is done. On
68 // any other error, it aborts the stream and returns an RPC status. On
69 // server side, it simply returns the error to the caller.
70 // It's safe to have a goroutine calling SendMsg and another goroutine calling
71 // recvMsg on the same stream at the same time.
72 // But it is not safe to call RecvMsg on the same stream in different goroutines.
73 RecvMsg(m interface{}) error
76 // ClientStream defines the interface a client stream has to satisfy.
77 type ClientStream interface {
78 // Header returns the header metadata received from the server if there
79 // is any. It blocks if the metadata is not ready to read.
80 Header() (metadata.MD, error)
81 // Trailer returns the trailer metadata from the server, if there is any.
82 // It must only be called after stream.CloseAndRecv has returned, or
83 // stream.Recv has returned a non-nil error (including io.EOF).
85 // CloseSend closes the send direction of the stream. It closes the stream
86 // when non-nil error is met.
88 // Stream.SendMsg() may return a non-nil error when something wrong happens sending
89 // the request. The returned error indicates the status of this sending, not the final
91 // Always call Stream.RecvMsg() to get the final status if you care about the status of
96 // NewClientStream creates a new Stream for the client side. This is called
98 func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
99 if cc.dopts.streamInt != nil {
100 return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
102 return newClientStream(ctx, desc, cc, method, opts...)
105 func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
107 t transport.ClientTransport
110 cancel context.CancelFunc
113 mc := cc.GetMethodConfig(method)
114 if mc.WaitForReady != nil {
115 c.failFast = !*mc.WaitForReady
118 if mc.Timeout != nil {
119 ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
122 opts = append(cc.dopts.callOptions, opts...)
123 for _, o := range opts {
124 if err := o.before(&c); err != nil {
125 return nil, toRPCErr(err)
128 c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
129 c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
131 callHdr := &transport.CallHdr{
134 // If it's not client streaming, we should already have the request to be sent,
135 // so we don't flush the header.
136 // If it's client streaming, the user may never send a request or send it any
137 // time soon, so we ask the transport to flush the header.
138 Flush: desc.ClientStreams,
140 if cc.dopts.cp != nil {
141 callHdr.SendCompress = cc.dopts.cp.Type()
144 callHdr.Creds = c.creds
148 trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
149 trInfo.firstLine.client = true
150 if deadline, ok := ctx.Deadline(); ok {
151 trInfo.firstLine.deadline = deadline.Sub(time.Now())
153 trInfo.tr.LazyLog(&trInfo.firstLine, false)
154 ctx = trace.NewContext(ctx, trInfo.tr)
157 // Need to call tr.finish() if error is returned.
158 // Because tr will not be returned to caller.
159 trInfo.tr.LazyPrintf("RPC: [%v]", err)
165 ctx = newContextWithRPCInfo(ctx)
166 sh := cc.dopts.copts.StatsHandler
168 ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
169 begin := &stats.Begin{
171 BeginTime: time.Now(),
172 FailFast: c.failFast,
174 sh.HandleRPC(ctx, begin)
177 // Only handle end stats if err != nil.
182 sh.HandleRPC(ctx, end)
186 gopts := BalancerGetOptions{
187 BlockingWait: !c.failFast,
190 t, put, err = cc.getTransport(ctx, gopts)
192 // TODO(zhaoq): Probably revisit the error handling.
193 if _, ok := status.FromError(err); ok {
196 if err == errConnClosing || err == errConnUnavailable {
198 return nil, Errorf(codes.Unavailable, "%v", err)
202 // All the other errors are treated as Internal errors.
203 return nil, Errorf(codes.Internal, "%v", err)
206 s, err = t.NewStream(ctx, callHdr)
208 if _, ok := err.(transport.ConnectionError); ok && put != nil {
209 // If error is connection error, transport was sending data on wire,
210 // and we are not sure if anything has been sent on wire.
211 // If error is not connection error, we are sure nothing has been sent.
212 updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
218 if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
221 return nil, toRPCErr(err)
225 // Set callInfo.peer object from stream's context.
226 if peer, ok := peer.FromContext(s.Context()); ok {
233 codec: cc.dopts.codec,
243 tracing: EnableTracing,
247 statsHandler: cc.dopts.copts.StatsHandler,
249 if cc.dopts.cp != nil {
250 cs.cbuf = new(bytes.Buffer)
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.
257 // Incur transport error, simply exit.
258 case <-cc.ctx.Done():
259 cs.finish(ErrClientConnClosing)
260 cs.closeTransportStream(ErrClientConnClosing)
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)
267 cs.finish(errConnDrain)
268 cs.closeTransportStream(errConnDrain)
269 case <-s.Context().Done():
270 err := s.Context().Err()
272 cs.closeTransportStream(transport.ContextErr(err))
278 // clientStream implements a client side Stream.
279 type clientStream struct {
282 t transport.ClientTransport
290 cancel context.CancelFunc
292 tracing bool // set to EnableTracing when the clientStream is created.
298 // trInfo.tr is set when the clientStream is created (if EnableTracing is true),
299 // and is set to nil when the clientStream's finish method is called.
302 // statsCtx keeps the user context for stats handling.
303 // All stats collection should use the statsCtx (instead of the stream context)
304 // so that all the generated stats for a particular RPC can be associated in the processing phase.
305 statsCtx context.Context
306 statsHandler stats.Handler
309 func (cs *clientStream) Context() context.Context {
310 return cs.s.Context()
313 func (cs *clientStream) Header() (metadata.MD, error) {
314 m, err := cs.s.Header()
316 if _, ok := err.(transport.ConnectionError); !ok {
317 cs.closeTransportStream(err)
323 func (cs *clientStream) Trailer() metadata.MD {
324 return cs.s.Trailer()
327 func (cs *clientStream) SendMsg(m interface{}) (err error) {
330 if cs.trInfo.tr != nil {
331 cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
335 // TODO Investigate how to signal the stats handling party.
336 // generate error stats if err != nil && err != io.EOF?
345 // Specialize the process for server streaming. SendMesg is only called
346 // once when creating the stream object. io.EOF needs to be skipped when
347 // the rpc is early finished (before the stream object is created.).
348 // TODO: It is probably better to move this into the generated code.
349 if !cs.desc.ClientStreams && cs.desc.ServerStreams {
354 if _, ok := err.(transport.ConnectionError); !ok {
355 cs.closeTransportStream(err)
359 var outPayload *stats.OutPayload
360 if cs.statsHandler != nil {
361 outPayload = &stats.OutPayload{
365 out, err := encode(cs.codec, m, cs.cp, cs.cbuf, outPayload)
374 if cs.c.maxSendMessageSize == nil {
375 return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
377 if len(out) > *cs.c.maxSendMessageSize {
378 return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(out), *cs.c.maxSendMessageSize)
380 err = cs.t.Write(cs.s, out, &transport.Options{Last: false})
381 if err == nil && outPayload != nil {
382 outPayload.SentTime = time.Now()
383 cs.statsHandler.HandleRPC(cs.statsCtx, outPayload)
388 func (cs *clientStream) RecvMsg(m interface{}) (err error) {
389 var inPayload *stats.InPayload
390 if cs.statsHandler != nil {
391 inPayload = &stats.InPayload{
395 if cs.c.maxReceiveMessageSize == nil {
396 return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
398 err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, inPayload)
400 // err != nil indicates the termination of the stream.
408 if cs.trInfo.tr != nil {
409 cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
413 if inPayload != nil {
414 cs.statsHandler.HandleRPC(cs.statsCtx, inPayload)
416 if !cs.desc.ClientStreams || cs.desc.ServerStreams {
419 // Special handling for client streaming rpc.
420 // This recv expects EOF or errors, so we don't collect inPayload.
421 if cs.c.maxReceiveMessageSize == nil {
422 return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
424 err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, nil)
425 cs.closeTransportStream(err)
427 return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
430 if se := cs.s.Status().Err(); se != nil {
438 if _, ok := err.(transport.ConnectionError); !ok {
439 cs.closeTransportStream(err)
442 if statusErr := cs.s.Status().Err(); statusErr != nil {
445 // Returns io.EOF to indicate the end of the stream.
451 func (cs *clientStream) CloseSend() (err error) {
452 err = cs.t.Write(cs.s, nil, &transport.Options{Last: true})
458 if err == nil || err == io.EOF {
461 if _, ok := err.(transport.ConnectionError); !ok {
462 cs.closeTransportStream(err)
468 func (cs *clientStream) closeTransportStream(err error) {
476 cs.t.CloseStream(cs.s, err)
479 func (cs *clientStream) finish(err error) {
487 if cs.cancel != nil {
491 for _, o := range cs.opts {
495 updateRPCInfoInContext(cs.s.Context(), rpcInfo{
496 bytesSent: cs.s.BytesSent(),
497 bytesReceived: cs.s.BytesReceived(),
502 if cs.statsHandler != nil {
508 // end.Error is nil if the RPC finished successfully.
509 end.Error = toRPCErr(err)
511 cs.statsHandler.HandleRPC(cs.statsCtx, end)
516 if cs.trInfo.tr != nil {
517 if err == nil || err == io.EOF {
518 cs.trInfo.tr.LazyPrintf("RPC: [OK]")
520 cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
521 cs.trInfo.tr.SetError()
523 cs.trInfo.tr.Finish()
528 // ServerStream defines the interface a server stream has to satisfy.
529 type ServerStream interface {
530 // SetHeader sets the header metadata. It may be called multiple times.
531 // When call multiple times, all the provided metadata will be merged.
532 // All the metadata will be sent out when one of the following happens:
533 // - ServerStream.SendHeader() is called;
534 // - The first response is sent out;
535 // - An RPC status is sent out (error or success).
536 SetHeader(metadata.MD) error
537 // SendHeader sends the header metadata.
538 // The provided md and headers set by SetHeader() will be sent.
539 // It fails if called multiple times.
540 SendHeader(metadata.MD) error
541 // SetTrailer sets the trailer metadata which will be sent with the RPC status.
542 // When called more than once, all the provided metadata will be merged.
543 SetTrailer(metadata.MD)
547 // serverStream implements a server side Stream.
548 type serverStream struct {
549 t transport.ServerTransport
556 maxReceiveMessageSize int
557 maxSendMessageSize int
560 statsHandler stats.Handler
562 mu sync.Mutex // protects trInfo.tr after the service handler runs.
565 func (ss *serverStream) Context() context.Context {
566 return ss.s.Context()
569 func (ss *serverStream) SetHeader(md metadata.MD) error {
573 return ss.s.SetHeader(md)
576 func (ss *serverStream) SendHeader(md metadata.MD) error {
577 return ss.t.WriteHeader(ss.s, md)
580 func (ss *serverStream) SetTrailer(md metadata.MD) {
588 func (ss *serverStream) SendMsg(m interface{}) (err error) {
590 if ss.trInfo != nil {
592 if ss.trInfo.tr != nil {
594 ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
596 ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
597 ss.trInfo.tr.SetError()
603 var outPayload *stats.OutPayload
604 if ss.statsHandler != nil {
605 outPayload = &stats.OutPayload{}
607 out, err := encode(ss.codec, m, ss.cp, ss.cbuf, outPayload)
616 if len(out) > ss.maxSendMessageSize {
617 return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(out), ss.maxSendMessageSize)
619 if err := ss.t.Write(ss.s, out, &transport.Options{Last: false}); err != nil {
622 if outPayload != nil {
623 outPayload.SentTime = time.Now()
624 ss.statsHandler.HandleRPC(ss.s.Context(), outPayload)
629 func (ss *serverStream) RecvMsg(m interface{}) (err error) {
631 if ss.trInfo != nil {
633 if ss.trInfo.tr != nil {
635 ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
636 } else if err != io.EOF {
637 ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
638 ss.trInfo.tr.SetError()
644 var inPayload *stats.InPayload
645 if ss.statsHandler != nil {
646 inPayload = &stats.InPayload{}
648 if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload); err != nil {
652 if err == io.ErrUnexpectedEOF {
653 err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
657 if inPayload != nil {
658 ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)