stream.go 53 KB

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