stream.go 44 KB

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