1
0

stream.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. "errors"
  21. "io"
  22. "math"
  23. "strconv"
  24. "sync"
  25. "time"
  26. "golang.org/x/net/context"
  27. "golang.org/x/net/trace"
  28. "google.golang.org/grpc/balancer"
  29. "google.golang.org/grpc/codes"
  30. "google.golang.org/grpc/encoding"
  31. "google.golang.org/grpc/grpclog"
  32. "google.golang.org/grpc/internal/channelz"
  33. "google.golang.org/grpc/internal/grpcrand"
  34. "google.golang.org/grpc/internal/transport"
  35. "google.golang.org/grpc/metadata"
  36. "google.golang.org/grpc/stats"
  37. "google.golang.org/grpc/status"
  38. )
  39. // StreamHandler defines the handler called by gRPC server to complete the
  40. // execution of a streaming RPC. If a StreamHandler returns an error, it
  41. // should be produced by the status package, or else gRPC will use
  42. // codes.Unknown as the status code and err.Error() as the status message
  43. // of the RPC.
  44. type StreamHandler func(srv interface{}, stream ServerStream) error
  45. // StreamDesc represents a streaming RPC service's method specification.
  46. type StreamDesc struct {
  47. StreamName string
  48. Handler StreamHandler
  49. // At least one of these is true.
  50. ServerStreams bool
  51. ClientStreams bool
  52. }
  53. // Stream defines the common interface a client or server stream has to satisfy.
  54. //
  55. // Deprecated: See ClientStream and ServerStream documentation instead.
  56. type Stream interface {
  57. // Deprecated: See ClientStream and ServerStream documentation instead.
  58. Context() context.Context
  59. // Deprecated: See ClientStream and ServerStream documentation instead.
  60. SendMsg(m interface{}) error
  61. // Deprecated: See ClientStream and ServerStream documentation instead.
  62. RecvMsg(m interface{}) error
  63. }
  64. // ClientStream defines the client-side behavior of a streaming RPC.
  65. //
  66. // All errors returned from ClientStream methods are compatible with the
  67. // status package.
  68. type ClientStream interface {
  69. // Header returns the header metadata received from the server if there
  70. // is any. It blocks if the metadata is not ready to read.
  71. Header() (metadata.MD, error)
  72. // Trailer returns the trailer metadata from the server, if there is any.
  73. // It must only be called after stream.CloseAndRecv has returned, or
  74. // stream.Recv has returned a non-nil error (including io.EOF).
  75. Trailer() metadata.MD
  76. // CloseSend closes the send direction of the stream. It closes the stream
  77. // when non-nil error is met.
  78. CloseSend() error
  79. // Context returns the context for this stream.
  80. //
  81. // It should not be called until after Header or RecvMsg has returned. Once
  82. // called, subsequent client-side retries are disabled.
  83. Context() context.Context
  84. // SendMsg is generally called by generated code. On error, SendMsg aborts
  85. // the stream. If the error was generated by the client, the status is
  86. // returned directly; otherwise, io.EOF is returned and the status of
  87. // the stream may be discovered using RecvMsg.
  88. //
  89. // SendMsg blocks until:
  90. // - There is sufficient flow control to schedule m with the transport, or
  91. // - The stream is done, or
  92. // - The stream breaks.
  93. //
  94. // SendMsg does not wait until the message is received by the server. An
  95. // untimely stream closure may result in lost messages. To ensure delivery,
  96. // users should ensure the RPC completed successfully using RecvMsg.
  97. //
  98. // It is safe to have a goroutine calling SendMsg and another goroutine
  99. // calling RecvMsg on the same stream at the same time, but it is not safe
  100. // to call SendMsg on the same stream in different goroutines.
  101. SendMsg(m interface{}) error
  102. // RecvMsg blocks until it receives a message into m or the stream is
  103. // done. It returns io.EOF when the stream completes successfully. On
  104. // any other error, the stream is aborted and the error contains the RPC
  105. // status.
  106. //
  107. // It is safe to have a goroutine calling SendMsg and another goroutine
  108. // calling RecvMsg on the same stream at the same time, but it is not
  109. // safe to call RecvMsg on the same stream in different goroutines.
  110. RecvMsg(m interface{}) error
  111. }
  112. // NewStream creates a new Stream for the client side. This is typically
  113. // called by generated code. ctx is used for the lifetime of the stream.
  114. //
  115. // To ensure resources are not leaked due to the stream returned, one of the following
  116. // actions must be performed:
  117. //
  118. // 1. Call Close on the ClientConn.
  119. // 2. Cancel the context provided.
  120. // 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated
  121. // client-streaming RPC, for instance, might use the helper function
  122. // CloseAndRecv (note that CloseSend does not Recv, therefore is not
  123. // guaranteed to release all resources).
  124. // 4. Receive a non-nil, non-io.EOF error from Header or SendMsg.
  125. //
  126. // If none of the above happen, a goroutine and a context will be leaked, and grpc
  127. // will not call the optionally-configured stats handler with a stats.End message.
  128. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) {
  129. // allow interceptor to see all applicable call options, which means those
  130. // configured as defaults from dial option as well as per-call options
  131. opts = combine(cc.dopts.callOptions, opts)
  132. if cc.dopts.streamInt != nil {
  133. return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
  134. }
  135. return newClientStream(ctx, desc, cc, method, opts...)
  136. }
  137. // NewClientStream is a wrapper for ClientConn.NewStream.
  138. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) {
  139. return cc.NewStream(ctx, desc, method, opts...)
  140. }
  141. func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
  142. if channelz.IsOn() {
  143. cc.incrCallsStarted()
  144. defer func() {
  145. if err != nil {
  146. cc.incrCallsFailed()
  147. }
  148. }()
  149. }
  150. c := defaultCallInfo()
  151. mc := cc.GetMethodConfig(method)
  152. if mc.WaitForReady != nil {
  153. c.failFast = !*mc.WaitForReady
  154. }
  155. // Possible context leak:
  156. // The cancel function for the child context we create will only be called
  157. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  158. // an error is generated by SendMsg.
  159. // https://github.com/grpc/grpc-go/issues/1818.
  160. var cancel context.CancelFunc
  161. if mc.Timeout != nil && *mc.Timeout >= 0 {
  162. ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
  163. } else {
  164. ctx, cancel = context.WithCancel(ctx)
  165. }
  166. defer func() {
  167. if err != nil {
  168. cancel()
  169. }
  170. }()
  171. for _, o := range opts {
  172. if err := o.before(c); err != nil {
  173. return nil, toRPCErr(err)
  174. }
  175. }
  176. c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
  177. c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  178. if err := setCallInfoCodec(c); err != nil {
  179. return nil, err
  180. }
  181. callHdr := &transport.CallHdr{
  182. Host: cc.authority,
  183. Method: method,
  184. ContentSubtype: c.contentSubtype,
  185. }
  186. // Set our outgoing compression according to the UseCompressor CallOption, if
  187. // set. In that case, also find the compressor from the encoding package.
  188. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  189. // if set.
  190. var cp Compressor
  191. var comp encoding.Compressor
  192. if ct := c.compressorType; ct != "" {
  193. callHdr.SendCompress = ct
  194. if ct != encoding.Identity {
  195. comp = encoding.GetCompressor(ct)
  196. if comp == nil {
  197. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  198. }
  199. }
  200. } else if cc.dopts.cp != nil {
  201. callHdr.SendCompress = cc.dopts.cp.Type()
  202. cp = cc.dopts.cp
  203. }
  204. if c.creds != nil {
  205. callHdr.Creds = c.creds
  206. }
  207. var trInfo traceInfo
  208. if EnableTracing {
  209. trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  210. trInfo.firstLine.client = true
  211. if deadline, ok := ctx.Deadline(); ok {
  212. trInfo.firstLine.deadline = deadline.Sub(time.Now())
  213. }
  214. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  215. ctx = trace.NewContext(ctx, trInfo.tr)
  216. }
  217. ctx = newContextWithRPCInfo(ctx, c.failFast)
  218. sh := cc.dopts.copts.StatsHandler
  219. var beginTime time.Time
  220. if sh != nil {
  221. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
  222. beginTime = time.Now()
  223. begin := &stats.Begin{
  224. Client: true,
  225. BeginTime: beginTime,
  226. FailFast: c.failFast,
  227. }
  228. sh.HandleRPC(ctx, begin)
  229. }
  230. cs := &clientStream{
  231. callHdr: callHdr,
  232. ctx: ctx,
  233. methodConfig: &mc,
  234. opts: opts,
  235. callInfo: c,
  236. cc: cc,
  237. desc: desc,
  238. codec: c.codec,
  239. cp: cp,
  240. comp: comp,
  241. cancel: cancel,
  242. beginTime: beginTime,
  243. firstAttempt: true,
  244. }
  245. if !cc.dopts.disableRetry {
  246. cs.retryThrottler = cc.retryThrottler.Load().(*retryThrottler)
  247. }
  248. cs.callInfo.stream = cs
  249. // Only this initial attempt has stats/tracing.
  250. // TODO(dfawley): move to newAttempt when per-attempt stats are implemented.
  251. if err := cs.newAttemptLocked(sh, trInfo); err != nil {
  252. cs.finish(err)
  253. return nil, err
  254. }
  255. op := func(a *csAttempt) error { return a.newStream() }
  256. if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }); err != nil {
  257. cs.finish(err)
  258. return nil, err
  259. }
  260. if desc != unaryStreamDesc {
  261. // Listen on cc and stream contexts to cleanup when the user closes the
  262. // ClientConn or cancels the stream context. In all other cases, an error
  263. // should already be injected into the recv buffer by the transport, which
  264. // the client will eventually receive, and then we will cancel the stream's
  265. // context in clientStream.finish.
  266. go func() {
  267. select {
  268. case <-cc.ctx.Done():
  269. cs.finish(ErrClientConnClosing)
  270. case <-ctx.Done():
  271. cs.finish(toRPCErr(ctx.Err()))
  272. }
  273. }()
  274. }
  275. return cs, nil
  276. }
  277. func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo traceInfo) error {
  278. cs.attempt = &csAttempt{
  279. cs: cs,
  280. dc: cs.cc.dopts.dc,
  281. statsHandler: sh,
  282. trInfo: trInfo,
  283. }
  284. if err := cs.ctx.Err(); err != nil {
  285. return toRPCErr(err)
  286. }
  287. t, done, err := cs.cc.getTransport(cs.ctx, cs.callInfo.failFast, cs.callHdr.Method)
  288. if err != nil {
  289. return err
  290. }
  291. cs.attempt.t = t
  292. cs.attempt.done = done
  293. return nil
  294. }
  295. func (a *csAttempt) newStream() error {
  296. cs := a.cs
  297. cs.callHdr.PreviousAttempts = cs.numRetries
  298. s, err := a.t.NewStream(cs.ctx, cs.callHdr)
  299. if err != nil {
  300. return toRPCErr(err)
  301. }
  302. cs.attempt.s = s
  303. cs.attempt.p = &parser{r: s}
  304. return nil
  305. }
  306. // clientStream implements a client side Stream.
  307. type clientStream struct {
  308. callHdr *transport.CallHdr
  309. opts []CallOption
  310. callInfo *callInfo
  311. cc *ClientConn
  312. desc *StreamDesc
  313. codec baseCodec
  314. cp Compressor
  315. comp encoding.Compressor
  316. cancel context.CancelFunc // cancels all attempts
  317. sentLast bool // sent an end stream
  318. beginTime time.Time
  319. methodConfig *MethodConfig
  320. ctx context.Context // the application's context, wrapped by stats/tracing
  321. retryThrottler *retryThrottler // The throttler active when the RPC began.
  322. mu sync.Mutex
  323. firstAttempt bool // if true, transparent retry is valid
  324. numRetries int // exclusive of transparent retry attempt(s)
  325. numRetriesSincePushback int // retries since pushback; to reset backoff
  326. finished bool // TODO: replace with atomic cmpxchg or sync.Once?
  327. attempt *csAttempt // the active client stream attempt
  328. // TODO(hedging): hedging will have multiple attempts simultaneously.
  329. committed bool // active attempt committed for retry?
  330. buffer []func(a *csAttempt) error // operations to replay on retry
  331. bufferSize int // current size of buffer
  332. }
  333. // csAttempt implements a single transport stream attempt within a
  334. // clientStream.
  335. type csAttempt struct {
  336. cs *clientStream
  337. t transport.ClientTransport
  338. s *transport.Stream
  339. p *parser
  340. done func(balancer.DoneInfo)
  341. finished bool
  342. dc Decompressor
  343. decomp encoding.Compressor
  344. decompSet bool
  345. mu sync.Mutex // guards trInfo.tr
  346. // trInfo.tr is set when created (if EnableTracing is true),
  347. // and cleared when the finish method is called.
  348. trInfo traceInfo
  349. statsHandler stats.Handler
  350. }
  351. func (cs *clientStream) commitAttemptLocked() {
  352. cs.committed = true
  353. cs.buffer = nil
  354. }
  355. func (cs *clientStream) commitAttempt() {
  356. cs.mu.Lock()
  357. cs.commitAttemptLocked()
  358. cs.mu.Unlock()
  359. }
  360. // shouldRetry returns nil if the RPC should be retried; otherwise it returns
  361. // the error that should be returned by the operation.
  362. func (cs *clientStream) shouldRetry(err error) error {
  363. if cs.attempt.s == nil && !cs.callInfo.failFast {
  364. // In the event of any error from NewStream (attempt.s == nil), we
  365. // never attempted to write anything to the wire, so we can retry
  366. // indefinitely for non-fail-fast RPCs.
  367. return nil
  368. }
  369. if cs.finished || cs.committed {
  370. // RPC is finished or committed; cannot retry.
  371. return err
  372. }
  373. // Wait for the trailers.
  374. if cs.attempt.s != nil {
  375. <-cs.attempt.s.Done()
  376. }
  377. if cs.firstAttempt && !cs.callInfo.failFast && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) {
  378. // First attempt, wait-for-ready, stream unprocessed: transparently retry.
  379. cs.firstAttempt = false
  380. return nil
  381. }
  382. cs.firstAttempt = false
  383. if cs.cc.dopts.disableRetry {
  384. return err
  385. }
  386. pushback := 0
  387. hasPushback := false
  388. if cs.attempt.s != nil {
  389. if to, toErr := cs.attempt.s.TrailersOnly(); toErr != nil {
  390. // Context error; stop now.
  391. return toErr
  392. } else if !to {
  393. return err
  394. }
  395. // TODO(retry): Move down if the spec changes to not check server pushback
  396. // before considering this a failure for throttling.
  397. sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"]
  398. if len(sps) == 1 {
  399. var e error
  400. if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 {
  401. grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0])
  402. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  403. return err
  404. }
  405. hasPushback = true
  406. } else if len(sps) > 1 {
  407. grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps)
  408. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  409. return err
  410. }
  411. }
  412. var code codes.Code
  413. if cs.attempt.s != nil {
  414. code = cs.attempt.s.Status().Code()
  415. } else {
  416. code = status.Convert(err).Code()
  417. }
  418. rp := cs.methodConfig.retryPolicy
  419. if rp == nil || !rp.retryableStatusCodes[code] {
  420. return err
  421. }
  422. // Note: the ordering here is important; we count this as a failure
  423. // only if the code matched a retryable code.
  424. if cs.retryThrottler.throttle() {
  425. return err
  426. }
  427. if cs.numRetries+1 >= rp.maxAttempts {
  428. return err
  429. }
  430. var dur time.Duration
  431. if hasPushback {
  432. dur = time.Millisecond * time.Duration(pushback)
  433. cs.numRetriesSincePushback = 0
  434. } else {
  435. fact := math.Pow(rp.backoffMultiplier, float64(cs.numRetriesSincePushback))
  436. cur := float64(rp.initialBackoff) * fact
  437. if max := float64(rp.maxBackoff); cur > max {
  438. cur = max
  439. }
  440. dur = time.Duration(grpcrand.Int63n(int64(cur)))
  441. cs.numRetriesSincePushback++
  442. }
  443. // TODO(dfawley): we could eagerly fail here if dur puts us past the
  444. // deadline, but unsure if it is worth doing.
  445. t := time.NewTimer(dur)
  446. select {
  447. case <-t.C:
  448. cs.numRetries++
  449. return nil
  450. case <-cs.ctx.Done():
  451. t.Stop()
  452. return status.FromContextError(cs.ctx.Err()).Err()
  453. }
  454. }
  455. // Returns nil if a retry was performed and succeeded; error otherwise.
  456. func (cs *clientStream) retryLocked(lastErr error) error {
  457. for {
  458. cs.attempt.finish(lastErr)
  459. if err := cs.shouldRetry(lastErr); err != nil {
  460. cs.commitAttemptLocked()
  461. return err
  462. }
  463. if err := cs.newAttemptLocked(nil, traceInfo{}); err != nil {
  464. return err
  465. }
  466. if lastErr = cs.replayBufferLocked(); lastErr == nil {
  467. return nil
  468. }
  469. }
  470. }
  471. func (cs *clientStream) Context() context.Context {
  472. cs.commitAttempt()
  473. // No need to lock before using attempt, since we know it is committed and
  474. // cannot change.
  475. return cs.attempt.s.Context()
  476. }
  477. func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error {
  478. cs.mu.Lock()
  479. for {
  480. if cs.committed {
  481. cs.mu.Unlock()
  482. return op(cs.attempt)
  483. }
  484. a := cs.attempt
  485. cs.mu.Unlock()
  486. err := op(a)
  487. cs.mu.Lock()
  488. if a != cs.attempt {
  489. // We started another attempt already.
  490. continue
  491. }
  492. if err == io.EOF {
  493. <-a.s.Done()
  494. }
  495. if err == nil || (err == io.EOF && a.s.Status().Code() == codes.OK) {
  496. onSuccess()
  497. cs.mu.Unlock()
  498. return err
  499. }
  500. if err := cs.retryLocked(err); err != nil {
  501. cs.mu.Unlock()
  502. return err
  503. }
  504. }
  505. }
  506. func (cs *clientStream) Header() (metadata.MD, error) {
  507. var m metadata.MD
  508. err := cs.withRetry(func(a *csAttempt) error {
  509. var err error
  510. m, err = a.s.Header()
  511. return toRPCErr(err)
  512. }, cs.commitAttemptLocked)
  513. if err != nil {
  514. cs.finish(err)
  515. }
  516. return m, err
  517. }
  518. func (cs *clientStream) Trailer() metadata.MD {
  519. // On RPC failure, we never need to retry, because usage requires that
  520. // RecvMsg() returned a non-nil error before calling this function is valid.
  521. // We would have retried earlier if necessary.
  522. //
  523. // Commit the attempt anyway, just in case users are not following those
  524. // directions -- it will prevent races and should not meaningfully impact
  525. // performance.
  526. cs.commitAttempt()
  527. if cs.attempt.s == nil {
  528. return nil
  529. }
  530. return cs.attempt.s.Trailer()
  531. }
  532. func (cs *clientStream) replayBufferLocked() error {
  533. a := cs.attempt
  534. for _, f := range cs.buffer {
  535. if err := f(a); err != nil {
  536. return err
  537. }
  538. }
  539. return nil
  540. }
  541. func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error) {
  542. // Note: we still will buffer if retry is disabled (for transparent retries).
  543. if cs.committed {
  544. return
  545. }
  546. cs.bufferSize += sz
  547. if cs.bufferSize > cs.callInfo.maxRetryRPCBufferSize {
  548. cs.commitAttemptLocked()
  549. return
  550. }
  551. cs.buffer = append(cs.buffer, op)
  552. }
  553. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  554. defer func() {
  555. if err != nil && err != io.EOF {
  556. // Call finish on the client stream for errors generated by this SendMsg
  557. // call, as these indicate problems created by this client. (Transport
  558. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  559. // error will be returned from RecvMsg eventually in that case, or be
  560. // retried.)
  561. cs.finish(err)
  562. }
  563. }()
  564. if cs.sentLast {
  565. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  566. }
  567. if !cs.desc.ClientStreams {
  568. cs.sentLast = true
  569. }
  570. data, err := encode(cs.codec, m)
  571. if err != nil {
  572. return err
  573. }
  574. compData, err := compress(data, cs.cp, cs.comp)
  575. if err != nil {
  576. return err
  577. }
  578. hdr, payload := msgHeader(data, compData)
  579. // TODO(dfawley): should we be checking len(data) instead?
  580. if len(payload) > *cs.callInfo.maxSendMessageSize {
  581. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize)
  582. }
  583. op := func(a *csAttempt) error {
  584. err := a.sendMsg(m, hdr, payload, data)
  585. // nil out the message and uncomp when replaying; they are only needed for
  586. // stats which is disabled for subsequent attempts.
  587. m, data = nil, nil
  588. return err
  589. }
  590. return cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) })
  591. }
  592. func (cs *clientStream) RecvMsg(m interface{}) error {
  593. err := cs.withRetry(func(a *csAttempt) error {
  594. return a.recvMsg(m)
  595. }, cs.commitAttemptLocked)
  596. if err != nil || !cs.desc.ServerStreams {
  597. // err != nil or non-server-streaming indicates end of stream.
  598. cs.finish(err)
  599. }
  600. return err
  601. }
  602. func (cs *clientStream) CloseSend() error {
  603. if cs.sentLast {
  604. // TODO: return an error and finish the stream instead, due to API misuse?
  605. return nil
  606. }
  607. cs.sentLast = true
  608. op := func(a *csAttempt) error {
  609. a.t.Write(a.s, nil, nil, &transport.Options{Last: true})
  610. // Always return nil; io.EOF is the only error that might make sense
  611. // instead, but there is no need to signal the client to call RecvMsg
  612. // as the only use left for the stream after CloseSend is to call
  613. // RecvMsg. This also matches historical behavior.
  614. return nil
  615. }
  616. cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) })
  617. // We never returned an error here for reasons.
  618. return nil
  619. }
  620. func (cs *clientStream) finish(err error) {
  621. if err == io.EOF {
  622. // Ending a stream with EOF indicates a success.
  623. err = nil
  624. }
  625. cs.mu.Lock()
  626. if cs.finished {
  627. cs.mu.Unlock()
  628. return
  629. }
  630. cs.finished = true
  631. cs.commitAttemptLocked()
  632. cs.mu.Unlock()
  633. if err == nil {
  634. cs.retryThrottler.successfulRPC()
  635. }
  636. if channelz.IsOn() {
  637. if err != nil {
  638. cs.cc.incrCallsFailed()
  639. } else {
  640. cs.cc.incrCallsSucceeded()
  641. }
  642. }
  643. if cs.attempt != nil {
  644. cs.attempt.finish(err)
  645. }
  646. // after functions all rely upon having a stream.
  647. if cs.attempt.s != nil {
  648. for _, o := range cs.opts {
  649. o.after(cs.callInfo)
  650. }
  651. }
  652. cs.cancel()
  653. }
  654. func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error {
  655. cs := a.cs
  656. if EnableTracing {
  657. a.mu.Lock()
  658. if a.trInfo.tr != nil {
  659. a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  660. }
  661. a.mu.Unlock()
  662. }
  663. if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil {
  664. if !cs.desc.ClientStreams {
  665. // For non-client-streaming RPCs, we return nil instead of EOF on error
  666. // because the generated code requires it. finish is not called; RecvMsg()
  667. // will call it with the stream's status independently.
  668. return nil
  669. }
  670. return io.EOF
  671. }
  672. if a.statsHandler != nil {
  673. a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now()))
  674. }
  675. if channelz.IsOn() {
  676. a.t.IncrMsgSent()
  677. }
  678. return nil
  679. }
  680. func (a *csAttempt) recvMsg(m interface{}) (err error) {
  681. cs := a.cs
  682. var inPayload *stats.InPayload
  683. if a.statsHandler != nil {
  684. inPayload = &stats.InPayload{
  685. Client: true,
  686. }
  687. }
  688. if !a.decompSet {
  689. // Block until we receive headers containing received message encoding.
  690. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  691. if a.dc == nil || a.dc.Type() != ct {
  692. // No configured decompressor, or it does not match the incoming
  693. // message encoding; attempt to find a registered compressor that does.
  694. a.dc = nil
  695. a.decomp = encoding.GetCompressor(ct)
  696. }
  697. } else {
  698. // No compression is used; disable our decompressor.
  699. a.dc = nil
  700. }
  701. // Only initialize this state once per stream.
  702. a.decompSet = true
  703. }
  704. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, inPayload, a.decomp)
  705. if err != nil {
  706. if err == io.EOF {
  707. if statusErr := a.s.Status().Err(); statusErr != nil {
  708. return statusErr
  709. }
  710. return io.EOF // indicates successful end of stream.
  711. }
  712. return toRPCErr(err)
  713. }
  714. if EnableTracing {
  715. a.mu.Lock()
  716. if a.trInfo.tr != nil {
  717. a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  718. }
  719. a.mu.Unlock()
  720. }
  721. if inPayload != nil {
  722. a.statsHandler.HandleRPC(cs.ctx, inPayload)
  723. }
  724. if channelz.IsOn() {
  725. a.t.IncrMsgRecv()
  726. }
  727. if cs.desc.ServerStreams {
  728. // Subsequent messages should be received by subsequent RecvMsg calls.
  729. return nil
  730. }
  731. // Special handling for non-server-stream rpcs.
  732. // This recv expects EOF or errors, so we don't collect inPayload.
  733. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp)
  734. if err == nil {
  735. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  736. }
  737. if err == io.EOF {
  738. return a.s.Status().Err() // non-server streaming Recv returns nil on success
  739. }
  740. return toRPCErr(err)
  741. }
  742. func (a *csAttempt) finish(err error) {
  743. a.mu.Lock()
  744. if a.finished {
  745. a.mu.Unlock()
  746. return
  747. }
  748. a.finished = true
  749. if err == io.EOF {
  750. // Ending a stream with EOF indicates a success.
  751. err = nil
  752. }
  753. if a.s != nil {
  754. a.t.CloseStream(a.s, err)
  755. }
  756. if a.done != nil {
  757. br := false
  758. var tr metadata.MD
  759. if a.s != nil {
  760. br = a.s.BytesReceived()
  761. tr = a.s.Trailer()
  762. }
  763. a.done(balancer.DoneInfo{
  764. Err: err,
  765. Trailer: tr,
  766. BytesSent: a.s != nil,
  767. BytesReceived: br,
  768. })
  769. }
  770. if a.statsHandler != nil {
  771. end := &stats.End{
  772. Client: true,
  773. BeginTime: a.cs.beginTime,
  774. EndTime: time.Now(),
  775. Error: err,
  776. }
  777. a.statsHandler.HandleRPC(a.cs.ctx, end)
  778. }
  779. if a.trInfo.tr != nil {
  780. if err == nil {
  781. a.trInfo.tr.LazyPrintf("RPC: [OK]")
  782. } else {
  783. a.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  784. a.trInfo.tr.SetError()
  785. }
  786. a.trInfo.tr.Finish()
  787. a.trInfo.tr = nil
  788. }
  789. a.mu.Unlock()
  790. }
  791. // ServerStream defines the server-side behavior of a streaming RPC.
  792. //
  793. // All errors returned from ServerStream methods are compatible with the
  794. // status package.
  795. type ServerStream interface {
  796. // SetHeader sets the header metadata. It may be called multiple times.
  797. // When call multiple times, all the provided metadata will be merged.
  798. // All the metadata will be sent out when one of the following happens:
  799. // - ServerStream.SendHeader() is called;
  800. // - The first response is sent out;
  801. // - An RPC status is sent out (error or success).
  802. SetHeader(metadata.MD) error
  803. // SendHeader sends the header metadata.
  804. // The provided md and headers set by SetHeader() will be sent.
  805. // It fails if called multiple times.
  806. SendHeader(metadata.MD) error
  807. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  808. // When called more than once, all the provided metadata will be merged.
  809. SetTrailer(metadata.MD)
  810. // Context returns the context for this stream.
  811. Context() context.Context
  812. // SendMsg sends a message. On error, SendMsg aborts the stream and the
  813. // error is returned directly.
  814. //
  815. // SendMsg blocks until:
  816. // - There is sufficient flow control to schedule m with the transport, or
  817. // - The stream is done, or
  818. // - The stream breaks.
  819. //
  820. // SendMsg does not wait until the message is received by the client. An
  821. // untimely stream closure may result in lost messages.
  822. //
  823. // It is safe to have a goroutine calling SendMsg and another goroutine
  824. // calling RecvMsg on the same stream at the same time, but it is not safe
  825. // to call SendMsg on the same stream in different goroutines.
  826. SendMsg(m interface{}) error
  827. // RecvMsg blocks until it receives a message into m or the stream is
  828. // done. It returns io.EOF when the client has performed a CloseSend. On
  829. // any non-EOF error, the stream is aborted and the error contains the
  830. // RPC status.
  831. //
  832. // It is safe to have a goroutine calling SendMsg and another goroutine
  833. // calling RecvMsg on the same stream at the same time, but it is not
  834. // safe to call RecvMsg on the same stream in different goroutines.
  835. RecvMsg(m interface{}) error
  836. }
  837. // serverStream implements a server side Stream.
  838. type serverStream struct {
  839. ctx context.Context
  840. t transport.ServerTransport
  841. s *transport.Stream
  842. p *parser
  843. codec baseCodec
  844. cp Compressor
  845. dc Decompressor
  846. comp encoding.Compressor
  847. decomp encoding.Compressor
  848. maxReceiveMessageSize int
  849. maxSendMessageSize int
  850. trInfo *traceInfo
  851. statsHandler stats.Handler
  852. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  853. }
  854. func (ss *serverStream) Context() context.Context {
  855. return ss.ctx
  856. }
  857. func (ss *serverStream) SetHeader(md metadata.MD) error {
  858. if md.Len() == 0 {
  859. return nil
  860. }
  861. return ss.s.SetHeader(md)
  862. }
  863. func (ss *serverStream) SendHeader(md metadata.MD) error {
  864. return ss.t.WriteHeader(ss.s, md)
  865. }
  866. func (ss *serverStream) SetTrailer(md metadata.MD) {
  867. if md.Len() == 0 {
  868. return
  869. }
  870. ss.s.SetTrailer(md)
  871. }
  872. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  873. defer func() {
  874. if ss.trInfo != nil {
  875. ss.mu.Lock()
  876. if ss.trInfo.tr != nil {
  877. if err == nil {
  878. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  879. } else {
  880. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  881. ss.trInfo.tr.SetError()
  882. }
  883. }
  884. ss.mu.Unlock()
  885. }
  886. if err != nil && err != io.EOF {
  887. st, _ := status.FromError(toRPCErr(err))
  888. ss.t.WriteStatus(ss.s, st)
  889. }
  890. if channelz.IsOn() && err == nil {
  891. ss.t.IncrMsgSent()
  892. }
  893. }()
  894. data, err := encode(ss.codec, m)
  895. if err != nil {
  896. return err
  897. }
  898. compData, err := compress(data, ss.cp, ss.comp)
  899. if err != nil {
  900. return err
  901. }
  902. hdr, payload := msgHeader(data, compData)
  903. // TODO(dfawley): should we be checking len(data) instead?
  904. if len(payload) > ss.maxSendMessageSize {
  905. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize)
  906. }
  907. if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil {
  908. return toRPCErr(err)
  909. }
  910. if ss.statsHandler != nil {
  911. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now()))
  912. }
  913. return nil
  914. }
  915. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  916. defer func() {
  917. if ss.trInfo != nil {
  918. ss.mu.Lock()
  919. if ss.trInfo.tr != nil {
  920. if err == nil {
  921. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  922. } else if err != io.EOF {
  923. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  924. ss.trInfo.tr.SetError()
  925. }
  926. }
  927. ss.mu.Unlock()
  928. }
  929. if err != nil && err != io.EOF {
  930. st, _ := status.FromError(toRPCErr(err))
  931. ss.t.WriteStatus(ss.s, st)
  932. }
  933. if channelz.IsOn() && err == nil {
  934. ss.t.IncrMsgRecv()
  935. }
  936. }()
  937. var inPayload *stats.InPayload
  938. if ss.statsHandler != nil {
  939. inPayload = &stats.InPayload{}
  940. }
  941. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil {
  942. if err == io.EOF {
  943. return err
  944. }
  945. if err == io.ErrUnexpectedEOF {
  946. err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  947. }
  948. return toRPCErr(err)
  949. }
  950. if inPayload != nil {
  951. ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
  952. }
  953. return nil
  954. }
  955. // MethodFromServerStream returns the method string for the input stream.
  956. // The returned string is in the format of "/service/method".
  957. func MethodFromServerStream(stream ServerStream) (string, bool) {
  958. return Method(stream.Context())
  959. }