stream.go 43 KB

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