stream.go 18 KB

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