stream.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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 { return a.t.Write(a.s, nil, nil, &transport.Options{Last: true}) }
  609. cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) })
  610. // We never returned an error here for reasons.
  611. return nil
  612. }
  613. func (cs *clientStream) finish(err error) {
  614. if err == io.EOF {
  615. // Ending a stream with EOF indicates a success.
  616. err = nil
  617. }
  618. cs.mu.Lock()
  619. if cs.finished {
  620. cs.mu.Unlock()
  621. return
  622. }
  623. cs.finished = true
  624. cs.commitAttemptLocked()
  625. cs.mu.Unlock()
  626. if err == nil {
  627. cs.retryThrottler.successfulRPC()
  628. }
  629. if channelz.IsOn() {
  630. if err != nil {
  631. cs.cc.incrCallsFailed()
  632. } else {
  633. cs.cc.incrCallsSucceeded()
  634. }
  635. }
  636. if cs.attempt != nil {
  637. cs.attempt.finish(err)
  638. }
  639. // after functions all rely upon having a stream.
  640. if cs.attempt.s != nil {
  641. for _, o := range cs.opts {
  642. o.after(cs.callInfo)
  643. }
  644. }
  645. cs.cancel()
  646. }
  647. func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error {
  648. cs := a.cs
  649. if EnableTracing {
  650. a.mu.Lock()
  651. if a.trInfo.tr != nil {
  652. a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  653. }
  654. a.mu.Unlock()
  655. }
  656. if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil {
  657. if !cs.desc.ClientStreams {
  658. // For non-client-streaming RPCs, we return nil instead of EOF on error
  659. // because the generated code requires it. finish is not called; RecvMsg()
  660. // will call it with the stream's status independently.
  661. return nil
  662. }
  663. return io.EOF
  664. }
  665. if a.statsHandler != nil {
  666. a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now()))
  667. }
  668. if channelz.IsOn() {
  669. a.t.IncrMsgSent()
  670. }
  671. return nil
  672. }
  673. func (a *csAttempt) recvMsg(m interface{}) (err error) {
  674. cs := a.cs
  675. var inPayload *stats.InPayload
  676. if a.statsHandler != nil {
  677. inPayload = &stats.InPayload{
  678. Client: true,
  679. }
  680. }
  681. if !a.decompSet {
  682. // Block until we receive headers containing received message encoding.
  683. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  684. if a.dc == nil || a.dc.Type() != ct {
  685. // No configured decompressor, or it does not match the incoming
  686. // message encoding; attempt to find a registered compressor that does.
  687. a.dc = nil
  688. a.decomp = encoding.GetCompressor(ct)
  689. }
  690. } else {
  691. // No compression is used; disable our decompressor.
  692. a.dc = nil
  693. }
  694. // Only initialize this state once per stream.
  695. a.decompSet = true
  696. }
  697. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, inPayload, a.decomp)
  698. if err != nil {
  699. if err == io.EOF {
  700. if statusErr := a.s.Status().Err(); statusErr != nil {
  701. return statusErr
  702. }
  703. return io.EOF // indicates successful end of stream.
  704. }
  705. return toRPCErr(err)
  706. }
  707. if EnableTracing {
  708. a.mu.Lock()
  709. if a.trInfo.tr != nil {
  710. a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  711. }
  712. a.mu.Unlock()
  713. }
  714. if inPayload != nil {
  715. a.statsHandler.HandleRPC(cs.ctx, inPayload)
  716. }
  717. if channelz.IsOn() {
  718. a.t.IncrMsgRecv()
  719. }
  720. if cs.desc.ServerStreams {
  721. // Subsequent messages should be received by subsequent RecvMsg calls.
  722. return nil
  723. }
  724. // Special handling for non-server-stream rpcs.
  725. // This recv expects EOF or errors, so we don't collect inPayload.
  726. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp)
  727. if err == nil {
  728. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  729. }
  730. if err == io.EOF {
  731. return a.s.Status().Err() // non-server streaming Recv returns nil on success
  732. }
  733. return toRPCErr(err)
  734. }
  735. func (a *csAttempt) finish(err error) {
  736. a.mu.Lock()
  737. if a.finished {
  738. a.mu.Unlock()
  739. return
  740. }
  741. a.finished = true
  742. if err == io.EOF {
  743. // Ending a stream with EOF indicates a success.
  744. err = nil
  745. }
  746. if a.s != nil {
  747. a.t.CloseStream(a.s, err)
  748. }
  749. if a.done != nil {
  750. br := false
  751. if a.s != nil {
  752. br = a.s.BytesReceived()
  753. }
  754. a.done(balancer.DoneInfo{
  755. Err: err,
  756. BytesSent: a.s != nil,
  757. BytesReceived: br,
  758. })
  759. }
  760. if a.statsHandler != nil {
  761. end := &stats.End{
  762. Client: true,
  763. BeginTime: a.cs.beginTime,
  764. EndTime: time.Now(),
  765. Error: err,
  766. }
  767. a.statsHandler.HandleRPC(a.cs.ctx, end)
  768. }
  769. if a.trInfo.tr != nil {
  770. if err == nil {
  771. a.trInfo.tr.LazyPrintf("RPC: [OK]")
  772. } else {
  773. a.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  774. a.trInfo.tr.SetError()
  775. }
  776. a.trInfo.tr.Finish()
  777. a.trInfo.tr = nil
  778. }
  779. a.mu.Unlock()
  780. }
  781. // ServerStream defines the server-side behavior of a streaming RPC.
  782. //
  783. // All errors returned from ServerStream methods are compatible with the
  784. // status package.
  785. type ServerStream interface {
  786. // SetHeader sets the header metadata. It may be called multiple times.
  787. // When call multiple times, all the provided metadata will be merged.
  788. // All the metadata will be sent out when one of the following happens:
  789. // - ServerStream.SendHeader() is called;
  790. // - The first response is sent out;
  791. // - An RPC status is sent out (error or success).
  792. SetHeader(metadata.MD) error
  793. // SendHeader sends the header metadata.
  794. // The provided md and headers set by SetHeader() will be sent.
  795. // It fails if called multiple times.
  796. SendHeader(metadata.MD) error
  797. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  798. // When called more than once, all the provided metadata will be merged.
  799. SetTrailer(metadata.MD)
  800. // Context returns the context for this stream.
  801. Context() context.Context
  802. // SendMsg sends a message. On error, SendMsg aborts the stream and the
  803. // error is returned directly.
  804. //
  805. // SendMsg blocks until:
  806. // - There is sufficient flow control to schedule m with the transport, or
  807. // - The stream is done, or
  808. // - The stream breaks.
  809. //
  810. // SendMsg does not wait until the message is received by the client. An
  811. // untimely stream closure may result in lost messages.
  812. //
  813. // It is safe to have a goroutine calling SendMsg and another goroutine
  814. // calling RecvMsg on the same stream at the same time, but it is not safe
  815. // to call SendMsg on the same stream in different goroutines.
  816. SendMsg(m interface{}) error
  817. // RecvMsg blocks until it receives a message into m or the stream is
  818. // done. It returns io.EOF when the client has performed a CloseSend. On
  819. // any non-EOF error, the stream is aborted and the error contains the
  820. // RPC status.
  821. //
  822. // It is safe to have a goroutine calling SendMsg and another goroutine
  823. // calling RecvMsg on the same stream at the same time, but it is not
  824. // safe to call RecvMsg on the same stream in different goroutines.
  825. RecvMsg(m interface{}) error
  826. }
  827. // serverStream implements a server side Stream.
  828. type serverStream struct {
  829. ctx context.Context
  830. t transport.ServerTransport
  831. s *transport.Stream
  832. p *parser
  833. codec baseCodec
  834. cp Compressor
  835. dc Decompressor
  836. comp encoding.Compressor
  837. decomp encoding.Compressor
  838. maxReceiveMessageSize int
  839. maxSendMessageSize int
  840. trInfo *traceInfo
  841. statsHandler stats.Handler
  842. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  843. }
  844. func (ss *serverStream) Context() context.Context {
  845. return ss.ctx
  846. }
  847. func (ss *serverStream) SetHeader(md metadata.MD) error {
  848. if md.Len() == 0 {
  849. return nil
  850. }
  851. return ss.s.SetHeader(md)
  852. }
  853. func (ss *serverStream) SendHeader(md metadata.MD) error {
  854. return ss.t.WriteHeader(ss.s, md)
  855. }
  856. func (ss *serverStream) SetTrailer(md metadata.MD) {
  857. if md.Len() == 0 {
  858. return
  859. }
  860. ss.s.SetTrailer(md)
  861. }
  862. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  863. defer func() {
  864. if ss.trInfo != nil {
  865. ss.mu.Lock()
  866. if ss.trInfo.tr != nil {
  867. if err == nil {
  868. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  869. } else {
  870. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  871. ss.trInfo.tr.SetError()
  872. }
  873. }
  874. ss.mu.Unlock()
  875. }
  876. if err != nil && err != io.EOF {
  877. st, _ := status.FromError(toRPCErr(err))
  878. ss.t.WriteStatus(ss.s, st)
  879. }
  880. if channelz.IsOn() && err == nil {
  881. ss.t.IncrMsgSent()
  882. }
  883. }()
  884. data, err := encode(ss.codec, m)
  885. if err != nil {
  886. return err
  887. }
  888. compData, err := compress(data, ss.cp, ss.comp)
  889. if err != nil {
  890. return err
  891. }
  892. hdr, payload := msgHeader(data, compData)
  893. // TODO(dfawley): should we be checking len(data) instead?
  894. if len(payload) > ss.maxSendMessageSize {
  895. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize)
  896. }
  897. if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil {
  898. return toRPCErr(err)
  899. }
  900. if ss.statsHandler != nil {
  901. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now()))
  902. }
  903. return nil
  904. }
  905. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  906. defer func() {
  907. if ss.trInfo != nil {
  908. ss.mu.Lock()
  909. if ss.trInfo.tr != nil {
  910. if err == nil {
  911. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  912. } else if err != io.EOF {
  913. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  914. ss.trInfo.tr.SetError()
  915. }
  916. }
  917. ss.mu.Unlock()
  918. }
  919. if err != nil && err != io.EOF {
  920. st, _ := status.FromError(toRPCErr(err))
  921. ss.t.WriteStatus(ss.s, st)
  922. }
  923. if channelz.IsOn() && err == nil {
  924. ss.t.IncrMsgRecv()
  925. }
  926. }()
  927. var inPayload *stats.InPayload
  928. if ss.statsHandler != nil {
  929. inPayload = &stats.InPayload{}
  930. }
  931. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil {
  932. if err == io.EOF {
  933. return err
  934. }
  935. if err == io.ErrUnexpectedEOF {
  936. err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  937. }
  938. return toRPCErr(err)
  939. }
  940. if inPayload != nil {
  941. ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
  942. }
  943. return nil
  944. }
  945. // MethodFromServerStream returns the method string for the input stream.
  946. // The returned string is in the format of "/service/method".
  947. func MethodFromServerStream(stream ServerStream) (string, bool) {
  948. return Method(stream.Context())
  949. }