stream.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. "context"
  21. "errors"
  22. "io"
  23. "math"
  24. "strconv"
  25. "sync"
  26. "time"
  27. "golang.org/x/net/trace"
  28. "google.golang.org/grpc/balancer"
  29. "google.golang.org/grpc/codes"
  30. "google.golang.org/grpc/connectivity"
  31. "google.golang.org/grpc/encoding"
  32. "google.golang.org/grpc/grpclog"
  33. "google.golang.org/grpc/internal/balancerload"
  34. "google.golang.org/grpc/internal/binarylog"
  35. "google.golang.org/grpc/internal/channelz"
  36. "google.golang.org/grpc/internal/grpcrand"
  37. "google.golang.org/grpc/internal/transport"
  38. "google.golang.org/grpc/metadata"
  39. "google.golang.org/grpc/peer"
  40. "google.golang.org/grpc/stats"
  41. "google.golang.org/grpc/status"
  42. )
  43. // StreamHandler defines the handler called by gRPC server to complete the
  44. // execution of a streaming RPC. If a StreamHandler returns an error, it
  45. // should be produced by the status package, or else gRPC will use
  46. // codes.Unknown as the status code and err.Error() as the status message
  47. // of the RPC.
  48. type StreamHandler func(srv interface{}, stream ServerStream) error
  49. // StreamDesc represents a streaming RPC service's method specification.
  50. type StreamDesc struct {
  51. StreamName string
  52. Handler StreamHandler
  53. // At least one of these is true.
  54. ServerStreams bool
  55. ClientStreams bool
  56. }
  57. // Stream defines the common interface a client or server stream has to satisfy.
  58. //
  59. // Deprecated: See ClientStream and ServerStream documentation instead.
  60. type Stream interface {
  61. // Deprecated: See ClientStream and ServerStream documentation instead.
  62. Context() context.Context
  63. // Deprecated: See ClientStream and ServerStream documentation instead.
  64. SendMsg(m interface{}) error
  65. // Deprecated: See ClientStream and ServerStream documentation instead.
  66. RecvMsg(m interface{}) error
  67. }
  68. // ClientStream defines the client-side behavior of a streaming RPC.
  69. //
  70. // All errors returned from ClientStream methods are compatible with the
  71. // status package.
  72. type ClientStream interface {
  73. // Header returns the header metadata received from the server if there
  74. // is any. It blocks if the metadata is not ready to read.
  75. Header() (metadata.MD, error)
  76. // Trailer returns the trailer metadata from the server, if there is any.
  77. // It must only be called after stream.CloseAndRecv has returned, or
  78. // stream.Recv has returned a non-nil error (including io.EOF).
  79. Trailer() metadata.MD
  80. // CloseSend closes the send direction of the stream. It closes the stream
  81. // when non-nil error is met. It is also not safe to call CloseSend
  82. // concurrently with SendMsg.
  83. CloseSend() error
  84. // Context returns the context for this stream.
  85. //
  86. // It should not be called until after Header or RecvMsg has returned. Once
  87. // called, subsequent client-side retries are disabled.
  88. Context() context.Context
  89. // SendMsg is generally called by generated code. On error, SendMsg aborts
  90. // the stream. If the error was generated by the client, the status is
  91. // returned directly; otherwise, io.EOF is returned and the status of
  92. // the stream may be discovered using RecvMsg.
  93. //
  94. // SendMsg blocks until:
  95. // - There is sufficient flow control to schedule m with the transport, or
  96. // - The stream is done, or
  97. // - The stream breaks.
  98. //
  99. // SendMsg does not wait until the message is received by the server. An
  100. // untimely stream closure may result in lost messages. To ensure delivery,
  101. // users should ensure the RPC completed successfully using RecvMsg.
  102. //
  103. // It is safe to have a goroutine calling SendMsg and another goroutine
  104. // calling RecvMsg on the same stream at the same time, but it is not safe
  105. // to call SendMsg on the same stream in different goroutines. It is also
  106. // not safe to call CloseSend concurrently with SendMsg.
  107. SendMsg(m interface{}) error
  108. // RecvMsg blocks until it receives a message into m or the stream is
  109. // done. It returns io.EOF when the stream completes successfully. On
  110. // any other error, the stream is aborted and the error contains the RPC
  111. // status.
  112. //
  113. // It is safe to have a goroutine calling SendMsg and another goroutine
  114. // calling RecvMsg on the same stream at the same time, but it is not
  115. // safe to call RecvMsg on the same stream in different goroutines.
  116. RecvMsg(m interface{}) error
  117. }
  118. // NewStream creates a new Stream for the client side. This is typically
  119. // called by generated code. ctx is used for the lifetime of the stream.
  120. //
  121. // To ensure resources are not leaked due to the stream returned, one of the following
  122. // actions must be performed:
  123. //
  124. // 1. Call Close on the ClientConn.
  125. // 2. Cancel the context provided.
  126. // 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated
  127. // client-streaming RPC, for instance, might use the helper function
  128. // CloseAndRecv (note that CloseSend does not Recv, therefore is not
  129. // guaranteed to release all resources).
  130. // 4. Receive a non-nil, non-io.EOF error from Header or SendMsg.
  131. //
  132. // If none of the above happen, a goroutine and a context will be leaked, and grpc
  133. // will not call the optionally-configured stats handler with a stats.End message.
  134. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) {
  135. // allow interceptor to see all applicable call options, which means those
  136. // configured as defaults from dial option as well as per-call options
  137. opts = combine(cc.dopts.callOptions, opts)
  138. if cc.dopts.streamInt != nil {
  139. return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
  140. }
  141. return newClientStream(ctx, desc, cc, method, opts...)
  142. }
  143. // NewClientStream is a wrapper for ClientConn.NewStream.
  144. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) {
  145. return cc.NewStream(ctx, desc, method, opts...)
  146. }
  147. func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
  148. if channelz.IsOn() {
  149. cc.incrCallsStarted()
  150. defer func() {
  151. if err != nil {
  152. cc.incrCallsFailed()
  153. }
  154. }()
  155. }
  156. c := defaultCallInfo()
  157. // Provide an opportunity for the first RPC to see the first service config
  158. // provided by the resolver.
  159. if err := cc.waitForResolvedAddrs(ctx); err != nil {
  160. return nil, err
  161. }
  162. mc := cc.GetMethodConfig(method)
  163. if mc.WaitForReady != nil {
  164. c.failFast = !*mc.WaitForReady
  165. }
  166. // Possible context leak:
  167. // The cancel function for the child context we create will only be called
  168. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  169. // an error is generated by SendMsg.
  170. // https://github.com/grpc/grpc-go/issues/1818.
  171. var cancel context.CancelFunc
  172. if mc.Timeout != nil && *mc.Timeout >= 0 {
  173. ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
  174. } else {
  175. ctx, cancel = context.WithCancel(ctx)
  176. }
  177. defer func() {
  178. if err != nil {
  179. cancel()
  180. }
  181. }()
  182. for _, o := range opts {
  183. if err := o.before(c); err != nil {
  184. return nil, toRPCErr(err)
  185. }
  186. }
  187. c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
  188. c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  189. if err := setCallInfoCodec(c); err != nil {
  190. return nil, err
  191. }
  192. callHdr := &transport.CallHdr{
  193. Host: cc.authority,
  194. Method: method,
  195. ContentSubtype: c.contentSubtype,
  196. }
  197. // Set our outgoing compression according to the UseCompressor CallOption, if
  198. // set. In that case, also find the compressor from the encoding package.
  199. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  200. // if set.
  201. var cp Compressor
  202. var comp encoding.Compressor
  203. if ct := c.compressorType; ct != "" {
  204. callHdr.SendCompress = ct
  205. if ct != encoding.Identity {
  206. comp = encoding.GetCompressor(ct)
  207. if comp == nil {
  208. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  209. }
  210. }
  211. } else if cc.dopts.cp != nil {
  212. callHdr.SendCompress = cc.dopts.cp.Type()
  213. cp = cc.dopts.cp
  214. }
  215. if c.creds != nil {
  216. callHdr.Creds = c.creds
  217. }
  218. var trInfo *traceInfo
  219. if EnableTracing {
  220. trInfo = &traceInfo{
  221. tr: trace.New("grpc.Sent."+methodFamily(method), method),
  222. firstLine: firstLine{
  223. client: true,
  224. },
  225. }
  226. if deadline, ok := ctx.Deadline(); ok {
  227. trInfo.firstLine.deadline = time.Until(deadline)
  228. }
  229. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  230. ctx = trace.NewContext(ctx, trInfo.tr)
  231. }
  232. ctx = newContextWithRPCInfo(ctx, c.failFast)
  233. sh := cc.dopts.copts.StatsHandler
  234. var beginTime time.Time
  235. if sh != nil {
  236. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
  237. beginTime = time.Now()
  238. begin := &stats.Begin{
  239. Client: true,
  240. BeginTime: beginTime,
  241. FailFast: c.failFast,
  242. }
  243. sh.HandleRPC(ctx, begin)
  244. }
  245. cs := &clientStream{
  246. callHdr: callHdr,
  247. ctx: ctx,
  248. methodConfig: &mc,
  249. opts: opts,
  250. callInfo: c,
  251. cc: cc,
  252. desc: desc,
  253. codec: c.codec,
  254. cp: cp,
  255. comp: comp,
  256. cancel: cancel,
  257. beginTime: beginTime,
  258. firstAttempt: true,
  259. }
  260. if !cc.dopts.disableRetry {
  261. cs.retryThrottler = cc.retryThrottler.Load().(*retryThrottler)
  262. }
  263. cs.binlog = binarylog.GetMethodLogger(method)
  264. cs.callInfo.stream = cs
  265. // Only this initial attempt has stats/tracing.
  266. // TODO(dfawley): move to newAttempt when per-attempt stats are implemented.
  267. if err := cs.newAttemptLocked(sh, trInfo); err != nil {
  268. cs.finish(err)
  269. return nil, err
  270. }
  271. op := func(a *csAttempt) error { return a.newStream() }
  272. if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }); err != nil {
  273. cs.finish(err)
  274. return nil, err
  275. }
  276. if cs.binlog != nil {
  277. md, _ := metadata.FromOutgoingContext(ctx)
  278. logEntry := &binarylog.ClientHeader{
  279. OnClientSide: true,
  280. Header: md,
  281. MethodName: method,
  282. Authority: cs.cc.authority,
  283. }
  284. if deadline, ok := ctx.Deadline(); ok {
  285. logEntry.Timeout = time.Until(deadline)
  286. if logEntry.Timeout < 0 {
  287. logEntry.Timeout = 0
  288. }
  289. }
  290. cs.binlog.Log(logEntry)
  291. }
  292. if desc != unaryStreamDesc {
  293. // Listen on cc and stream contexts to cleanup when the user closes the
  294. // ClientConn or cancels the stream context. In all other cases, an error
  295. // should already be injected into the recv buffer by the transport, which
  296. // the client will eventually receive, and then we will cancel the stream's
  297. // context in clientStream.finish.
  298. go func() {
  299. select {
  300. case <-cc.ctx.Done():
  301. cs.finish(ErrClientConnClosing)
  302. case <-ctx.Done():
  303. cs.finish(toRPCErr(ctx.Err()))
  304. }
  305. }()
  306. }
  307. return cs, nil
  308. }
  309. func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo *traceInfo) error {
  310. cs.attempt = &csAttempt{
  311. cs: cs,
  312. dc: cs.cc.dopts.dc,
  313. statsHandler: sh,
  314. trInfo: trInfo,
  315. }
  316. if err := cs.ctx.Err(); err != nil {
  317. return toRPCErr(err)
  318. }
  319. t, done, err := cs.cc.getTransport(cs.ctx, cs.callInfo.failFast, cs.callHdr.Method)
  320. if err != nil {
  321. return err
  322. }
  323. if trInfo != nil {
  324. trInfo.firstLine.SetRemoteAddr(t.RemoteAddr())
  325. }
  326. cs.attempt.t = t
  327. cs.attempt.done = done
  328. return nil
  329. }
  330. func (a *csAttempt) newStream() error {
  331. cs := a.cs
  332. cs.callHdr.PreviousAttempts = cs.numRetries
  333. s, err := a.t.NewStream(cs.ctx, cs.callHdr)
  334. if err != nil {
  335. return toRPCErr(err)
  336. }
  337. cs.attempt.s = s
  338. cs.attempt.p = &parser{r: s}
  339. return nil
  340. }
  341. // clientStream implements a client side Stream.
  342. type clientStream struct {
  343. callHdr *transport.CallHdr
  344. opts []CallOption
  345. callInfo *callInfo
  346. cc *ClientConn
  347. desc *StreamDesc
  348. codec baseCodec
  349. cp Compressor
  350. comp encoding.Compressor
  351. cancel context.CancelFunc // cancels all attempts
  352. sentLast bool // sent an end stream
  353. beginTime time.Time
  354. methodConfig *MethodConfig
  355. ctx context.Context // the application's context, wrapped by stats/tracing
  356. retryThrottler *retryThrottler // The throttler active when the RPC began.
  357. binlog *binarylog.MethodLogger // Binary logger, can be nil.
  358. // serverHeaderBinlogged is a boolean for whether server header has been
  359. // logged. Server header will be logged when the first time one of those
  360. // happens: stream.Header(), stream.Recv().
  361. //
  362. // It's only read and used by Recv() and Header(), so it doesn't need to be
  363. // synchronized.
  364. serverHeaderBinlogged bool
  365. mu sync.Mutex
  366. firstAttempt bool // if true, transparent retry is valid
  367. numRetries int // exclusive of transparent retry attempt(s)
  368. numRetriesSincePushback int // retries since pushback; to reset backoff
  369. finished bool // TODO: replace with atomic cmpxchg or sync.Once?
  370. attempt *csAttempt // the active client stream attempt
  371. // TODO(hedging): hedging will have multiple attempts simultaneously.
  372. committed bool // active attempt committed for retry?
  373. buffer []func(a *csAttempt) error // operations to replay on retry
  374. bufferSize int // current size of buffer
  375. }
  376. // csAttempt implements a single transport stream attempt within a
  377. // clientStream.
  378. type csAttempt struct {
  379. cs *clientStream
  380. t transport.ClientTransport
  381. s *transport.Stream
  382. p *parser
  383. done func(balancer.DoneInfo)
  384. finished bool
  385. dc Decompressor
  386. decomp encoding.Compressor
  387. decompSet bool
  388. mu sync.Mutex // guards trInfo.tr
  389. // trInfo may be nil (if EnableTracing is false).
  390. // trInfo.tr is set when created (if EnableTracing is true),
  391. // and cleared when the finish method is called.
  392. trInfo *traceInfo
  393. statsHandler stats.Handler
  394. }
  395. func (cs *clientStream) commitAttemptLocked() {
  396. cs.committed = true
  397. cs.buffer = nil
  398. }
  399. func (cs *clientStream) commitAttempt() {
  400. cs.mu.Lock()
  401. cs.commitAttemptLocked()
  402. cs.mu.Unlock()
  403. }
  404. // shouldRetry returns nil if the RPC should be retried; otherwise it returns
  405. // the error that should be returned by the operation.
  406. func (cs *clientStream) shouldRetry(err error) error {
  407. if cs.attempt.s == nil && !cs.callInfo.failFast {
  408. // In the event of any error from NewStream (attempt.s == nil), we
  409. // never attempted to write anything to the wire, so we can retry
  410. // indefinitely for non-fail-fast RPCs.
  411. return nil
  412. }
  413. if cs.finished || cs.committed {
  414. // RPC is finished or committed; cannot retry.
  415. return err
  416. }
  417. // Wait for the trailers.
  418. if cs.attempt.s != nil {
  419. <-cs.attempt.s.Done()
  420. }
  421. if cs.firstAttempt && !cs.callInfo.failFast && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) {
  422. // First attempt, wait-for-ready, stream unprocessed: transparently retry.
  423. cs.firstAttempt = false
  424. return nil
  425. }
  426. cs.firstAttempt = false
  427. if cs.cc.dopts.disableRetry {
  428. return err
  429. }
  430. pushback := 0
  431. hasPushback := false
  432. if cs.attempt.s != nil {
  433. if to, toErr := cs.attempt.s.TrailersOnly(); toErr != nil || !to {
  434. return err
  435. }
  436. // TODO(retry): Move down if the spec changes to not check server pushback
  437. // before considering this a failure for throttling.
  438. sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"]
  439. if len(sps) == 1 {
  440. var e error
  441. if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 {
  442. grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0])
  443. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  444. return err
  445. }
  446. hasPushback = true
  447. } else if len(sps) > 1 {
  448. grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps)
  449. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  450. return err
  451. }
  452. }
  453. var code codes.Code
  454. if cs.attempt.s != nil {
  455. code = cs.attempt.s.Status().Code()
  456. } else {
  457. code = status.Convert(err).Code()
  458. }
  459. rp := cs.methodConfig.retryPolicy
  460. if rp == nil || !rp.retryableStatusCodes[code] {
  461. return err
  462. }
  463. // Note: the ordering here is important; we count this as a failure
  464. // only if the code matched a retryable code.
  465. if cs.retryThrottler.throttle() {
  466. return err
  467. }
  468. if cs.numRetries+1 >= rp.maxAttempts {
  469. return err
  470. }
  471. var dur time.Duration
  472. if hasPushback {
  473. dur = time.Millisecond * time.Duration(pushback)
  474. cs.numRetriesSincePushback = 0
  475. } else {
  476. fact := math.Pow(rp.backoffMultiplier, float64(cs.numRetriesSincePushback))
  477. cur := float64(rp.initialBackoff) * fact
  478. if max := float64(rp.maxBackoff); cur > max {
  479. cur = max
  480. }
  481. dur = time.Duration(grpcrand.Int63n(int64(cur)))
  482. cs.numRetriesSincePushback++
  483. }
  484. // TODO(dfawley): we could eagerly fail here if dur puts us past the
  485. // deadline, but unsure if it is worth doing.
  486. t := time.NewTimer(dur)
  487. select {
  488. case <-t.C:
  489. cs.numRetries++
  490. return nil
  491. case <-cs.ctx.Done():
  492. t.Stop()
  493. return status.FromContextError(cs.ctx.Err()).Err()
  494. }
  495. }
  496. // Returns nil if a retry was performed and succeeded; error otherwise.
  497. func (cs *clientStream) retryLocked(lastErr error) error {
  498. for {
  499. cs.attempt.finish(lastErr)
  500. if err := cs.shouldRetry(lastErr); err != nil {
  501. cs.commitAttemptLocked()
  502. return err
  503. }
  504. if err := cs.newAttemptLocked(nil, nil); err != nil {
  505. return err
  506. }
  507. if lastErr = cs.replayBufferLocked(); lastErr == nil {
  508. return nil
  509. }
  510. }
  511. }
  512. func (cs *clientStream) Context() context.Context {
  513. cs.commitAttempt()
  514. // No need to lock before using attempt, since we know it is committed and
  515. // cannot change.
  516. return cs.attempt.s.Context()
  517. }
  518. func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error {
  519. cs.mu.Lock()
  520. for {
  521. if cs.committed {
  522. cs.mu.Unlock()
  523. return op(cs.attempt)
  524. }
  525. a := cs.attempt
  526. cs.mu.Unlock()
  527. err := op(a)
  528. cs.mu.Lock()
  529. if a != cs.attempt {
  530. // We started another attempt already.
  531. continue
  532. }
  533. if err == io.EOF {
  534. <-a.s.Done()
  535. }
  536. if err == nil || (err == io.EOF && a.s.Status().Code() == codes.OK) {
  537. onSuccess()
  538. cs.mu.Unlock()
  539. return err
  540. }
  541. if err := cs.retryLocked(err); err != nil {
  542. cs.mu.Unlock()
  543. return err
  544. }
  545. }
  546. }
  547. func (cs *clientStream) Header() (metadata.MD, error) {
  548. var m metadata.MD
  549. err := cs.withRetry(func(a *csAttempt) error {
  550. var err error
  551. m, err = a.s.Header()
  552. return toRPCErr(err)
  553. }, cs.commitAttemptLocked)
  554. if err != nil {
  555. cs.finish(err)
  556. return nil, err
  557. }
  558. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  559. // Only log if binary log is on and header has not been logged.
  560. logEntry := &binarylog.ServerHeader{
  561. OnClientSide: true,
  562. Header: m,
  563. PeerAddr: nil,
  564. }
  565. if peer, ok := peer.FromContext(cs.Context()); ok {
  566. logEntry.PeerAddr = peer.Addr
  567. }
  568. cs.binlog.Log(logEntry)
  569. cs.serverHeaderBinlogged = true
  570. }
  571. return m, err
  572. }
  573. func (cs *clientStream) Trailer() metadata.MD {
  574. // On RPC failure, we never need to retry, because usage requires that
  575. // RecvMsg() returned a non-nil error before calling this function is valid.
  576. // We would have retried earlier if necessary.
  577. //
  578. // Commit the attempt anyway, just in case users are not following those
  579. // directions -- it will prevent races and should not meaningfully impact
  580. // performance.
  581. cs.commitAttempt()
  582. if cs.attempt.s == nil {
  583. return nil
  584. }
  585. return cs.attempt.s.Trailer()
  586. }
  587. func (cs *clientStream) replayBufferLocked() error {
  588. a := cs.attempt
  589. for _, f := range cs.buffer {
  590. if err := f(a); err != nil {
  591. return err
  592. }
  593. }
  594. return nil
  595. }
  596. func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error) {
  597. // Note: we still will buffer if retry is disabled (for transparent retries).
  598. if cs.committed {
  599. return
  600. }
  601. cs.bufferSize += sz
  602. if cs.bufferSize > cs.callInfo.maxRetryRPCBufferSize {
  603. cs.commitAttemptLocked()
  604. return
  605. }
  606. cs.buffer = append(cs.buffer, op)
  607. }
  608. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  609. defer func() {
  610. if err != nil && err != io.EOF {
  611. // Call finish on the client stream for errors generated by this SendMsg
  612. // call, as these indicate problems created by this client. (Transport
  613. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  614. // error will be returned from RecvMsg eventually in that case, or be
  615. // retried.)
  616. cs.finish(err)
  617. }
  618. }()
  619. if cs.sentLast {
  620. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  621. }
  622. if !cs.desc.ClientStreams {
  623. cs.sentLast = true
  624. }
  625. data, err := encode(cs.codec, m)
  626. if err != nil {
  627. return err
  628. }
  629. compData, err := compress(data, cs.cp, cs.comp)
  630. if err != nil {
  631. return err
  632. }
  633. hdr, payload := msgHeader(data, compData)
  634. // TODO(dfawley): should we be checking len(data) instead?
  635. if len(payload) > *cs.callInfo.maxSendMessageSize {
  636. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize)
  637. }
  638. msgBytes := data // Store the pointer before setting to nil. For binary logging.
  639. op := func(a *csAttempt) error {
  640. err := a.sendMsg(m, hdr, payload, data)
  641. // nil out the message and uncomp when replaying; they are only needed for
  642. // stats which is disabled for subsequent attempts.
  643. m, data = nil, nil
  644. return err
  645. }
  646. err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) })
  647. if cs.binlog != nil && err == nil {
  648. cs.binlog.Log(&binarylog.ClientMessage{
  649. OnClientSide: true,
  650. Message: msgBytes,
  651. })
  652. }
  653. return
  654. }
  655. func (cs *clientStream) RecvMsg(m interface{}) error {
  656. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  657. // Call Header() to binary log header if it's not already logged.
  658. cs.Header()
  659. }
  660. var recvInfo *payloadInfo
  661. if cs.binlog != nil {
  662. recvInfo = &payloadInfo{}
  663. }
  664. err := cs.withRetry(func(a *csAttempt) error {
  665. return a.recvMsg(m, recvInfo)
  666. }, cs.commitAttemptLocked)
  667. if cs.binlog != nil && err == nil {
  668. cs.binlog.Log(&binarylog.ServerMessage{
  669. OnClientSide: true,
  670. Message: recvInfo.uncompressedBytes,
  671. })
  672. }
  673. if err != nil || !cs.desc.ServerStreams {
  674. // err != nil or non-server-streaming indicates end of stream.
  675. cs.finish(err)
  676. if cs.binlog != nil {
  677. // finish will not log Trailer. Log Trailer here.
  678. logEntry := &binarylog.ServerTrailer{
  679. OnClientSide: true,
  680. Trailer: cs.Trailer(),
  681. Err: err,
  682. }
  683. if logEntry.Err == io.EOF {
  684. logEntry.Err = nil
  685. }
  686. if peer, ok := peer.FromContext(cs.Context()); ok {
  687. logEntry.PeerAddr = peer.Addr
  688. }
  689. cs.binlog.Log(logEntry)
  690. }
  691. }
  692. return err
  693. }
  694. func (cs *clientStream) CloseSend() error {
  695. if cs.sentLast {
  696. // TODO: return an error and finish the stream instead, due to API misuse?
  697. return nil
  698. }
  699. cs.sentLast = true
  700. op := func(a *csAttempt) error {
  701. a.t.Write(a.s, nil, nil, &transport.Options{Last: true})
  702. // Always return nil; io.EOF is the only error that might make sense
  703. // instead, but there is no need to signal the client to call RecvMsg
  704. // as the only use left for the stream after CloseSend is to call
  705. // RecvMsg. This also matches historical behavior.
  706. return nil
  707. }
  708. cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) })
  709. if cs.binlog != nil {
  710. cs.binlog.Log(&binarylog.ClientHalfClose{
  711. OnClientSide: true,
  712. })
  713. }
  714. // We never returned an error here for reasons.
  715. return nil
  716. }
  717. func (cs *clientStream) finish(err error) {
  718. if err == io.EOF {
  719. // Ending a stream with EOF indicates a success.
  720. err = nil
  721. }
  722. cs.mu.Lock()
  723. if cs.finished {
  724. cs.mu.Unlock()
  725. return
  726. }
  727. cs.finished = true
  728. cs.commitAttemptLocked()
  729. cs.mu.Unlock()
  730. // For binary logging. only log cancel in finish (could be caused by RPC ctx
  731. // canceled or ClientConn closed). Trailer will be logged in RecvMsg.
  732. //
  733. // Only one of cancel or trailer needs to be logged. In the cases where
  734. // users don't call RecvMsg, users must have already canceled the RPC.
  735. if cs.binlog != nil && status.Code(err) == codes.Canceled {
  736. cs.binlog.Log(&binarylog.Cancel{
  737. OnClientSide: true,
  738. })
  739. }
  740. if err == nil {
  741. cs.retryThrottler.successfulRPC()
  742. }
  743. if channelz.IsOn() {
  744. if err != nil {
  745. cs.cc.incrCallsFailed()
  746. } else {
  747. cs.cc.incrCallsSucceeded()
  748. }
  749. }
  750. if cs.attempt != nil {
  751. cs.attempt.finish(err)
  752. }
  753. // after functions all rely upon having a stream.
  754. if cs.attempt.s != nil {
  755. for _, o := range cs.opts {
  756. o.after(cs.callInfo)
  757. }
  758. }
  759. cs.cancel()
  760. }
  761. func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error {
  762. cs := a.cs
  763. if a.trInfo != nil {
  764. a.mu.Lock()
  765. if a.trInfo.tr != nil {
  766. a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  767. }
  768. a.mu.Unlock()
  769. }
  770. if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil {
  771. if !cs.desc.ClientStreams {
  772. // For non-client-streaming RPCs, we return nil instead of EOF on error
  773. // because the generated code requires it. finish is not called; RecvMsg()
  774. // will call it with the stream's status independently.
  775. return nil
  776. }
  777. return io.EOF
  778. }
  779. if a.statsHandler != nil {
  780. a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now()))
  781. }
  782. if channelz.IsOn() {
  783. a.t.IncrMsgSent()
  784. }
  785. return nil
  786. }
  787. func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) {
  788. cs := a.cs
  789. if a.statsHandler != nil && payInfo == nil {
  790. payInfo = &payloadInfo{}
  791. }
  792. if !a.decompSet {
  793. // Block until we receive headers containing received message encoding.
  794. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  795. if a.dc == nil || a.dc.Type() != ct {
  796. // No configured decompressor, or it does not match the incoming
  797. // message encoding; attempt to find a registered compressor that does.
  798. a.dc = nil
  799. a.decomp = encoding.GetCompressor(ct)
  800. }
  801. } else {
  802. // No compression is used; disable our decompressor.
  803. a.dc = nil
  804. }
  805. // Only initialize this state once per stream.
  806. a.decompSet = true
  807. }
  808. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, payInfo, a.decomp)
  809. if err != nil {
  810. if err == io.EOF {
  811. if statusErr := a.s.Status().Err(); statusErr != nil {
  812. return statusErr
  813. }
  814. return io.EOF // indicates successful end of stream.
  815. }
  816. return toRPCErr(err)
  817. }
  818. if a.trInfo != nil {
  819. a.mu.Lock()
  820. if a.trInfo.tr != nil {
  821. a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  822. }
  823. a.mu.Unlock()
  824. }
  825. if a.statsHandler != nil {
  826. a.statsHandler.HandleRPC(cs.ctx, &stats.InPayload{
  827. Client: true,
  828. RecvTime: time.Now(),
  829. Payload: m,
  830. // TODO truncate large payload.
  831. Data: payInfo.uncompressedBytes,
  832. WireLength: payInfo.wireLength,
  833. Length: len(payInfo.uncompressedBytes),
  834. })
  835. }
  836. if channelz.IsOn() {
  837. a.t.IncrMsgRecv()
  838. }
  839. if cs.desc.ServerStreams {
  840. // Subsequent messages should be received by subsequent RecvMsg calls.
  841. return nil
  842. }
  843. // Special handling for non-server-stream rpcs.
  844. // This recv expects EOF or errors, so we don't collect inPayload.
  845. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp)
  846. if err == nil {
  847. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  848. }
  849. if err == io.EOF {
  850. return a.s.Status().Err() // non-server streaming Recv returns nil on success
  851. }
  852. return toRPCErr(err)
  853. }
  854. func (a *csAttempt) finish(err error) {
  855. a.mu.Lock()
  856. if a.finished {
  857. a.mu.Unlock()
  858. return
  859. }
  860. a.finished = true
  861. if err == io.EOF {
  862. // Ending a stream with EOF indicates a success.
  863. err = nil
  864. }
  865. var tr metadata.MD
  866. if a.s != nil {
  867. a.t.CloseStream(a.s, err)
  868. tr = a.s.Trailer()
  869. }
  870. if a.done != nil {
  871. br := false
  872. if a.s != nil {
  873. br = a.s.BytesReceived()
  874. }
  875. a.done(balancer.DoneInfo{
  876. Err: err,
  877. Trailer: tr,
  878. BytesSent: a.s != nil,
  879. BytesReceived: br,
  880. ServerLoad: balancerload.Parse(tr),
  881. })
  882. }
  883. if a.statsHandler != nil {
  884. end := &stats.End{
  885. Client: true,
  886. BeginTime: a.cs.beginTime,
  887. EndTime: time.Now(),
  888. Trailer: tr,
  889. Error: err,
  890. }
  891. a.statsHandler.HandleRPC(a.cs.ctx, end)
  892. }
  893. if a.trInfo != nil && a.trInfo.tr != nil {
  894. if err == nil {
  895. a.trInfo.tr.LazyPrintf("RPC: [OK]")
  896. } else {
  897. a.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  898. a.trInfo.tr.SetError()
  899. }
  900. a.trInfo.tr.Finish()
  901. a.trInfo.tr = nil
  902. }
  903. a.mu.Unlock()
  904. }
  905. func (ac *addrConn) newClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, opts ...CallOption) (_ ClientStream, err error) {
  906. ac.mu.Lock()
  907. if ac.transport != t {
  908. ac.mu.Unlock()
  909. return nil, status.Error(codes.Canceled, "the provided transport is no longer valid to use")
  910. }
  911. // transition to CONNECTING state when an attempt starts
  912. if ac.state != connectivity.Connecting {
  913. ac.updateConnectivityState(connectivity.Connecting)
  914. ac.cc.handleSubConnStateChange(ac.acbw, ac.state)
  915. }
  916. ac.mu.Unlock()
  917. if t == nil {
  918. // TODO: return RPC error here?
  919. return nil, errors.New("transport provided is nil")
  920. }
  921. // defaultCallInfo contains unnecessary info(i.e. failfast, maxRetryRPCBufferSize), so we just initialize an empty struct.
  922. c := &callInfo{}
  923. for _, o := range opts {
  924. if err := o.before(c); err != nil {
  925. return nil, toRPCErr(err)
  926. }
  927. }
  928. c.maxReceiveMessageSize = getMaxSize(nil, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  929. c.maxSendMessageSize = getMaxSize(nil, c.maxSendMessageSize, defaultServerMaxSendMessageSize)
  930. // Possible context leak:
  931. // The cancel function for the child context we create will only be called
  932. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  933. // an error is generated by SendMsg.
  934. // https://github.com/grpc/grpc-go/issues/1818.
  935. ctx, cancel := context.WithCancel(ctx)
  936. defer func() {
  937. if err != nil {
  938. cancel()
  939. }
  940. }()
  941. if err := setCallInfoCodec(c); err != nil {
  942. return nil, err
  943. }
  944. callHdr := &transport.CallHdr{
  945. Host: ac.cc.authority,
  946. Method: method,
  947. ContentSubtype: c.contentSubtype,
  948. }
  949. // Set our outgoing compression according to the UseCompressor CallOption, if
  950. // set. In that case, also find the compressor from the encoding package.
  951. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  952. // if set.
  953. var cp Compressor
  954. var comp encoding.Compressor
  955. if ct := c.compressorType; ct != "" {
  956. callHdr.SendCompress = ct
  957. if ct != encoding.Identity {
  958. comp = encoding.GetCompressor(ct)
  959. if comp == nil {
  960. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  961. }
  962. }
  963. } else if ac.cc.dopts.cp != nil {
  964. callHdr.SendCompress = ac.cc.dopts.cp.Type()
  965. cp = ac.cc.dopts.cp
  966. }
  967. if c.creds != nil {
  968. callHdr.Creds = c.creds
  969. }
  970. as := &addrConnStream{
  971. callHdr: callHdr,
  972. ac: ac,
  973. ctx: ctx,
  974. cancel: cancel,
  975. opts: opts,
  976. callInfo: c,
  977. desc: desc,
  978. codec: c.codec,
  979. cp: cp,
  980. comp: comp,
  981. t: t,
  982. }
  983. as.callInfo.stream = as
  984. s, err := as.t.NewStream(as.ctx, as.callHdr)
  985. if err != nil {
  986. err = toRPCErr(err)
  987. return nil, err
  988. }
  989. as.s = s
  990. as.p = &parser{r: s}
  991. ac.incrCallsStarted()
  992. if desc != unaryStreamDesc {
  993. // Listen on cc and stream contexts to cleanup when the user closes the
  994. // ClientConn or cancels the stream context. In all other cases, an error
  995. // should already be injected into the recv buffer by the transport, which
  996. // the client will eventually receive, and then we will cancel the stream's
  997. // context in clientStream.finish.
  998. go func() {
  999. select {
  1000. case <-ac.ctx.Done():
  1001. as.finish(status.Error(codes.Canceled, "grpc: the SubConn is closing"))
  1002. case <-ctx.Done():
  1003. as.finish(toRPCErr(ctx.Err()))
  1004. }
  1005. }()
  1006. }
  1007. return as, nil
  1008. }
  1009. type addrConnStream struct {
  1010. s *transport.Stream
  1011. ac *addrConn
  1012. callHdr *transport.CallHdr
  1013. cancel context.CancelFunc
  1014. opts []CallOption
  1015. callInfo *callInfo
  1016. t transport.ClientTransport
  1017. ctx context.Context
  1018. sentLast bool
  1019. desc *StreamDesc
  1020. codec baseCodec
  1021. cp Compressor
  1022. comp encoding.Compressor
  1023. decompSet bool
  1024. dc Decompressor
  1025. decomp encoding.Compressor
  1026. p *parser
  1027. mu sync.Mutex
  1028. finished bool
  1029. }
  1030. func (as *addrConnStream) Header() (metadata.MD, error) {
  1031. m, err := as.s.Header()
  1032. if err != nil {
  1033. as.finish(toRPCErr(err))
  1034. }
  1035. return m, err
  1036. }
  1037. func (as *addrConnStream) Trailer() metadata.MD {
  1038. return as.s.Trailer()
  1039. }
  1040. func (as *addrConnStream) CloseSend() error {
  1041. if as.sentLast {
  1042. // TODO: return an error and finish the stream instead, due to API misuse?
  1043. return nil
  1044. }
  1045. as.sentLast = true
  1046. as.t.Write(as.s, nil, nil, &transport.Options{Last: true})
  1047. // Always return nil; io.EOF is the only error that might make sense
  1048. // instead, but there is no need to signal the client to call RecvMsg
  1049. // as the only use left for the stream after CloseSend is to call
  1050. // RecvMsg. This also matches historical behavior.
  1051. return nil
  1052. }
  1053. func (as *addrConnStream) Context() context.Context {
  1054. return as.s.Context()
  1055. }
  1056. func (as *addrConnStream) SendMsg(m interface{}) (err error) {
  1057. defer func() {
  1058. if err != nil && err != io.EOF {
  1059. // Call finish on the client stream for errors generated by this SendMsg
  1060. // call, as these indicate problems created by this client. (Transport
  1061. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  1062. // error will be returned from RecvMsg eventually in that case, or be
  1063. // retried.)
  1064. as.finish(err)
  1065. }
  1066. }()
  1067. if as.sentLast {
  1068. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  1069. }
  1070. if !as.desc.ClientStreams {
  1071. as.sentLast = true
  1072. }
  1073. data, err := encode(as.codec, m)
  1074. if err != nil {
  1075. return err
  1076. }
  1077. compData, err := compress(data, as.cp, as.comp)
  1078. if err != nil {
  1079. return err
  1080. }
  1081. hdr, payld := msgHeader(data, compData)
  1082. // TODO(dfawley): should we be checking len(data) instead?
  1083. if len(payld) > *as.callInfo.maxSendMessageSize {
  1084. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payld), *as.callInfo.maxSendMessageSize)
  1085. }
  1086. if err := as.t.Write(as.s, hdr, payld, &transport.Options{Last: !as.desc.ClientStreams}); err != nil {
  1087. if !as.desc.ClientStreams {
  1088. // For non-client-streaming RPCs, we return nil instead of EOF on error
  1089. // because the generated code requires it. finish is not called; RecvMsg()
  1090. // will call it with the stream's status independently.
  1091. return nil
  1092. }
  1093. return io.EOF
  1094. }
  1095. if channelz.IsOn() {
  1096. as.t.IncrMsgSent()
  1097. }
  1098. return nil
  1099. }
  1100. func (as *addrConnStream) RecvMsg(m interface{}) (err error) {
  1101. defer func() {
  1102. if err != nil || !as.desc.ServerStreams {
  1103. // err != nil or non-server-streaming indicates end of stream.
  1104. as.finish(err)
  1105. }
  1106. }()
  1107. if !as.decompSet {
  1108. // Block until we receive headers containing received message encoding.
  1109. if ct := as.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  1110. if as.dc == nil || as.dc.Type() != ct {
  1111. // No configured decompressor, or it does not match the incoming
  1112. // message encoding; attempt to find a registered compressor that does.
  1113. as.dc = nil
  1114. as.decomp = encoding.GetCompressor(ct)
  1115. }
  1116. } else {
  1117. // No compression is used; disable our decompressor.
  1118. as.dc = nil
  1119. }
  1120. // Only initialize this state once per stream.
  1121. as.decompSet = true
  1122. }
  1123. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1124. if err != nil {
  1125. if err == io.EOF {
  1126. if statusErr := as.s.Status().Err(); statusErr != nil {
  1127. return statusErr
  1128. }
  1129. return io.EOF // indicates successful end of stream.
  1130. }
  1131. return toRPCErr(err)
  1132. }
  1133. if channelz.IsOn() {
  1134. as.t.IncrMsgRecv()
  1135. }
  1136. if as.desc.ServerStreams {
  1137. // Subsequent messages should be received by subsequent RecvMsg calls.
  1138. return nil
  1139. }
  1140. // Special handling for non-server-stream rpcs.
  1141. // This recv expects EOF or errors, so we don't collect inPayload.
  1142. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1143. if err == nil {
  1144. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  1145. }
  1146. if err == io.EOF {
  1147. return as.s.Status().Err() // non-server streaming Recv returns nil on success
  1148. }
  1149. return toRPCErr(err)
  1150. }
  1151. func (as *addrConnStream) finish(err error) {
  1152. as.mu.Lock()
  1153. if as.finished {
  1154. as.mu.Unlock()
  1155. return
  1156. }
  1157. as.finished = true
  1158. if err == io.EOF {
  1159. // Ending a stream with EOF indicates a success.
  1160. err = nil
  1161. }
  1162. if as.s != nil {
  1163. as.t.CloseStream(as.s, err)
  1164. }
  1165. if err != nil {
  1166. as.ac.incrCallsFailed()
  1167. } else {
  1168. as.ac.incrCallsSucceeded()
  1169. }
  1170. as.cancel()
  1171. as.mu.Unlock()
  1172. }
  1173. // ServerStream defines the server-side behavior of a streaming RPC.
  1174. //
  1175. // All errors returned from ServerStream methods are compatible with the
  1176. // status package.
  1177. type ServerStream interface {
  1178. // SetHeader sets the header metadata. It may be called multiple times.
  1179. // When call multiple times, all the provided metadata will be merged.
  1180. // All the metadata will be sent out when one of the following happens:
  1181. // - ServerStream.SendHeader() is called;
  1182. // - The first response is sent out;
  1183. // - An RPC status is sent out (error or success).
  1184. SetHeader(metadata.MD) error
  1185. // SendHeader sends the header metadata.
  1186. // The provided md and headers set by SetHeader() will be sent.
  1187. // It fails if called multiple times.
  1188. SendHeader(metadata.MD) error
  1189. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  1190. // When called more than once, all the provided metadata will be merged.
  1191. SetTrailer(metadata.MD)
  1192. // Context returns the context for this stream.
  1193. Context() context.Context
  1194. // SendMsg sends a message. On error, SendMsg aborts the stream and the
  1195. // error is returned directly.
  1196. //
  1197. // SendMsg blocks until:
  1198. // - There is sufficient flow control to schedule m with the transport, or
  1199. // - The stream is done, or
  1200. // - The stream breaks.
  1201. //
  1202. // SendMsg does not wait until the message is received by the client. An
  1203. // untimely stream closure may result in lost messages.
  1204. //
  1205. // It is safe to have a goroutine calling SendMsg and another goroutine
  1206. // calling RecvMsg on the same stream at the same time, but it is not safe
  1207. // to call SendMsg on the same stream in different goroutines.
  1208. SendMsg(m interface{}) error
  1209. // RecvMsg blocks until it receives a message into m or the stream is
  1210. // done. It returns io.EOF when the client has performed a CloseSend. On
  1211. // any non-EOF error, the stream is aborted and the error contains the
  1212. // RPC status.
  1213. //
  1214. // It is safe to have a goroutine calling SendMsg and another goroutine
  1215. // calling RecvMsg on the same stream at the same time, but it is not
  1216. // safe to call RecvMsg on the same stream in different goroutines.
  1217. RecvMsg(m interface{}) error
  1218. }
  1219. // serverStream implements a server side Stream.
  1220. type serverStream struct {
  1221. ctx context.Context
  1222. t transport.ServerTransport
  1223. s *transport.Stream
  1224. p *parser
  1225. codec baseCodec
  1226. cp Compressor
  1227. dc Decompressor
  1228. comp encoding.Compressor
  1229. decomp encoding.Compressor
  1230. maxReceiveMessageSize int
  1231. maxSendMessageSize int
  1232. trInfo *traceInfo
  1233. statsHandler stats.Handler
  1234. binlog *binarylog.MethodLogger
  1235. // serverHeaderBinlogged indicates whether server header has been logged. It
  1236. // will happen when one of the following two happens: stream.SendHeader(),
  1237. // stream.Send().
  1238. //
  1239. // It's only checked in send and sendHeader, doesn't need to be
  1240. // synchronized.
  1241. serverHeaderBinlogged bool
  1242. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  1243. }
  1244. func (ss *serverStream) Context() context.Context {
  1245. return ss.ctx
  1246. }
  1247. func (ss *serverStream) SetHeader(md metadata.MD) error {
  1248. if md.Len() == 0 {
  1249. return nil
  1250. }
  1251. return ss.s.SetHeader(md)
  1252. }
  1253. func (ss *serverStream) SendHeader(md metadata.MD) error {
  1254. err := ss.t.WriteHeader(ss.s, md)
  1255. if ss.binlog != nil && !ss.serverHeaderBinlogged {
  1256. h, _ := ss.s.Header()
  1257. ss.binlog.Log(&binarylog.ServerHeader{
  1258. Header: h,
  1259. })
  1260. ss.serverHeaderBinlogged = true
  1261. }
  1262. return err
  1263. }
  1264. func (ss *serverStream) SetTrailer(md metadata.MD) {
  1265. if md.Len() == 0 {
  1266. return
  1267. }
  1268. ss.s.SetTrailer(md)
  1269. }
  1270. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  1271. defer func() {
  1272. if ss.trInfo != nil {
  1273. ss.mu.Lock()
  1274. if ss.trInfo.tr != nil {
  1275. if err == nil {
  1276. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  1277. } else {
  1278. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1279. ss.trInfo.tr.SetError()
  1280. }
  1281. }
  1282. ss.mu.Unlock()
  1283. }
  1284. if err != nil && err != io.EOF {
  1285. st, _ := status.FromError(toRPCErr(err))
  1286. ss.t.WriteStatus(ss.s, st)
  1287. // Non-user specified status was sent out. This should be an error
  1288. // case (as a server side Cancel maybe).
  1289. //
  1290. // This is not handled specifically now. User will return a final
  1291. // status from the service handler, we will log that error instead.
  1292. // This behavior is similar to an interceptor.
  1293. }
  1294. if channelz.IsOn() && err == nil {
  1295. ss.t.IncrMsgSent()
  1296. }
  1297. }()
  1298. data, err := encode(ss.codec, m)
  1299. if err != nil {
  1300. return err
  1301. }
  1302. compData, err := compress(data, ss.cp, ss.comp)
  1303. if err != nil {
  1304. return err
  1305. }
  1306. hdr, payload := msgHeader(data, compData)
  1307. // TODO(dfawley): should we be checking len(data) instead?
  1308. if len(payload) > ss.maxSendMessageSize {
  1309. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize)
  1310. }
  1311. if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil {
  1312. return toRPCErr(err)
  1313. }
  1314. if ss.binlog != nil {
  1315. if !ss.serverHeaderBinlogged {
  1316. h, _ := ss.s.Header()
  1317. ss.binlog.Log(&binarylog.ServerHeader{
  1318. Header: h,
  1319. })
  1320. ss.serverHeaderBinlogged = true
  1321. }
  1322. ss.binlog.Log(&binarylog.ServerMessage{
  1323. Message: data,
  1324. })
  1325. }
  1326. if ss.statsHandler != nil {
  1327. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now()))
  1328. }
  1329. return nil
  1330. }
  1331. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  1332. defer func() {
  1333. if ss.trInfo != nil {
  1334. ss.mu.Lock()
  1335. if ss.trInfo.tr != nil {
  1336. if err == nil {
  1337. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  1338. } else if err != io.EOF {
  1339. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1340. ss.trInfo.tr.SetError()
  1341. }
  1342. }
  1343. ss.mu.Unlock()
  1344. }
  1345. if err != nil && err != io.EOF {
  1346. st, _ := status.FromError(toRPCErr(err))
  1347. ss.t.WriteStatus(ss.s, st)
  1348. // Non-user specified status was sent out. This should be an error
  1349. // case (as a server side Cancel maybe).
  1350. //
  1351. // This is not handled specifically now. User will return a final
  1352. // status from the service handler, we will log that error instead.
  1353. // This behavior is similar to an interceptor.
  1354. }
  1355. if channelz.IsOn() && err == nil {
  1356. ss.t.IncrMsgRecv()
  1357. }
  1358. }()
  1359. var payInfo *payloadInfo
  1360. if ss.statsHandler != nil || ss.binlog != nil {
  1361. payInfo = &payloadInfo{}
  1362. }
  1363. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, payInfo, ss.decomp); err != nil {
  1364. if err == io.EOF {
  1365. if ss.binlog != nil {
  1366. ss.binlog.Log(&binarylog.ClientHalfClose{})
  1367. }
  1368. return err
  1369. }
  1370. if err == io.ErrUnexpectedEOF {
  1371. err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  1372. }
  1373. return toRPCErr(err)
  1374. }
  1375. if ss.statsHandler != nil {
  1376. ss.statsHandler.HandleRPC(ss.s.Context(), &stats.InPayload{
  1377. RecvTime: time.Now(),
  1378. Payload: m,
  1379. // TODO truncate large payload.
  1380. Data: payInfo.uncompressedBytes,
  1381. WireLength: payInfo.wireLength,
  1382. Length: len(payInfo.uncompressedBytes),
  1383. })
  1384. }
  1385. if ss.binlog != nil {
  1386. ss.binlog.Log(&binarylog.ClientMessage{
  1387. Message: payInfo.uncompressedBytes,
  1388. })
  1389. }
  1390. return nil
  1391. }
  1392. // MethodFromServerStream returns the method string for the input stream.
  1393. // The returned string is in the format of "/service/method".
  1394. func MethodFromServerStream(stream ServerStream) (string, bool) {
  1395. return Method(stream.Context())
  1396. }