stream.go 18 KB

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