stream.go 18 KB

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