stream.go 19 KB

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