dialoptions.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /*
  2. *
  3. * Copyright 2018 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. "net"
  22. "time"
  23. "google.golang.org/grpc/backoff"
  24. "google.golang.org/grpc/channelz"
  25. "google.golang.org/grpc/credentials"
  26. "google.golang.org/grpc/credentials/insecure"
  27. "google.golang.org/grpc/internal"
  28. internalbackoff "google.golang.org/grpc/internal/backoff"
  29. "google.golang.org/grpc/internal/binarylog"
  30. "google.golang.org/grpc/internal/transport"
  31. "google.golang.org/grpc/keepalive"
  32. "google.golang.org/grpc/resolver"
  33. "google.golang.org/grpc/stats"
  34. )
  35. func init() {
  36. internal.AddGlobalDialOptions = func(opt ...DialOption) {
  37. globalDialOptions = append(globalDialOptions, opt...)
  38. }
  39. internal.ClearGlobalDialOptions = func() {
  40. globalDialOptions = nil
  41. }
  42. internal.WithBinaryLogger = withBinaryLogger
  43. internal.JoinDialOptions = newJoinDialOption
  44. internal.DisableGlobalDialOptions = newDisableGlobalDialOptions
  45. internal.WithRecvBufferPool = withRecvBufferPool
  46. }
  47. // dialOptions configure a Dial call. dialOptions are set by the DialOption
  48. // values passed to Dial.
  49. type dialOptions struct {
  50. unaryInt UnaryClientInterceptor
  51. streamInt StreamClientInterceptor
  52. chainUnaryInts []UnaryClientInterceptor
  53. chainStreamInts []StreamClientInterceptor
  54. cp Compressor
  55. dc Decompressor
  56. bs internalbackoff.Strategy
  57. block bool
  58. returnLastError bool
  59. timeout time.Duration
  60. authority string
  61. binaryLogger binarylog.Logger
  62. copts transport.ConnectOptions
  63. callOptions []CallOption
  64. channelzParentID *channelz.Identifier
  65. disableServiceConfig bool
  66. disableRetry bool
  67. disableHealthCheck bool
  68. healthCheckFunc internal.HealthChecker
  69. minConnectTimeout func() time.Duration
  70. defaultServiceConfig *ServiceConfig // defaultServiceConfig is parsed from defaultServiceConfigRawJSON.
  71. defaultServiceConfigRawJSON *string
  72. resolvers []resolver.Builder
  73. idleTimeout time.Duration
  74. recvBufferPool SharedBufferPool
  75. }
  76. // DialOption configures how we set up the connection.
  77. type DialOption interface {
  78. apply(*dialOptions)
  79. }
  80. var globalDialOptions []DialOption
  81. // EmptyDialOption does not alter the dial configuration. It can be embedded in
  82. // another structure to build custom dial options.
  83. //
  84. // # Experimental
  85. //
  86. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  87. // later release.
  88. type EmptyDialOption struct{}
  89. func (EmptyDialOption) apply(*dialOptions) {}
  90. type disableGlobalDialOptions struct{}
  91. func (disableGlobalDialOptions) apply(*dialOptions) {}
  92. // newDisableGlobalDialOptions returns a DialOption that prevents the ClientConn
  93. // from applying the global DialOptions (set via AddGlobalDialOptions).
  94. func newDisableGlobalDialOptions() DialOption {
  95. return &disableGlobalDialOptions{}
  96. }
  97. // funcDialOption wraps a function that modifies dialOptions into an
  98. // implementation of the DialOption interface.
  99. type funcDialOption struct {
  100. f func(*dialOptions)
  101. }
  102. func (fdo *funcDialOption) apply(do *dialOptions) {
  103. fdo.f(do)
  104. }
  105. func newFuncDialOption(f func(*dialOptions)) *funcDialOption {
  106. return &funcDialOption{
  107. f: f,
  108. }
  109. }
  110. type joinDialOption struct {
  111. opts []DialOption
  112. }
  113. func (jdo *joinDialOption) apply(do *dialOptions) {
  114. for _, opt := range jdo.opts {
  115. opt.apply(do)
  116. }
  117. }
  118. func newJoinDialOption(opts ...DialOption) DialOption {
  119. return &joinDialOption{opts: opts}
  120. }
  121. // WithSharedWriteBuffer allows reusing per-connection transport write buffer.
  122. // If this option is set to true every connection will release the buffer after
  123. // flushing the data on the wire.
  124. //
  125. // # Experimental
  126. //
  127. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  128. // later release.
  129. func WithSharedWriteBuffer(val bool) DialOption {
  130. return newFuncDialOption(func(o *dialOptions) {
  131. o.copts.SharedWriteBuffer = val
  132. })
  133. }
  134. // WithWriteBufferSize determines how much data can be batched before doing a
  135. // write on the wire. The corresponding memory allocation for this buffer will
  136. // be twice the size to keep syscalls low. The default value for this buffer is
  137. // 32KB.
  138. //
  139. // Zero or negative values will disable the write buffer such that each write
  140. // will be on underlying connection. Note: A Send call may not directly
  141. // translate to a write.
  142. func WithWriteBufferSize(s int) DialOption {
  143. return newFuncDialOption(func(o *dialOptions) {
  144. o.copts.WriteBufferSize = s
  145. })
  146. }
  147. // WithReadBufferSize lets you set the size of read buffer, this determines how
  148. // much data can be read at most for each read syscall.
  149. //
  150. // The default value for this buffer is 32KB. Zero or negative values will
  151. // disable read buffer for a connection so data framer can access the
  152. // underlying conn directly.
  153. func WithReadBufferSize(s int) DialOption {
  154. return newFuncDialOption(func(o *dialOptions) {
  155. o.copts.ReadBufferSize = s
  156. })
  157. }
  158. // WithInitialWindowSize returns a DialOption which sets the value for initial
  159. // window size on a stream. The lower bound for window size is 64K and any value
  160. // smaller than that will be ignored.
  161. func WithInitialWindowSize(s int32) DialOption {
  162. return newFuncDialOption(func(o *dialOptions) {
  163. o.copts.InitialWindowSize = s
  164. })
  165. }
  166. // WithInitialConnWindowSize returns a DialOption which sets the value for
  167. // initial window size on a connection. The lower bound for window size is 64K
  168. // and any value smaller than that will be ignored.
  169. func WithInitialConnWindowSize(s int32) DialOption {
  170. return newFuncDialOption(func(o *dialOptions) {
  171. o.copts.InitialConnWindowSize = s
  172. })
  173. }
  174. // WithMaxMsgSize returns a DialOption which sets the maximum message size the
  175. // client can receive.
  176. //
  177. // Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will
  178. // be supported throughout 1.x.
  179. func WithMaxMsgSize(s int) DialOption {
  180. return WithDefaultCallOptions(MaxCallRecvMsgSize(s))
  181. }
  182. // WithDefaultCallOptions returns a DialOption which sets the default
  183. // CallOptions for calls over the connection.
  184. func WithDefaultCallOptions(cos ...CallOption) DialOption {
  185. return newFuncDialOption(func(o *dialOptions) {
  186. o.callOptions = append(o.callOptions, cos...)
  187. })
  188. }
  189. // WithCodec returns a DialOption which sets a codec for message marshaling and
  190. // unmarshaling.
  191. //
  192. // Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be
  193. // supported throughout 1.x.
  194. func WithCodec(c Codec) DialOption {
  195. return WithDefaultCallOptions(CallCustomCodec(c))
  196. }
  197. // WithCompressor returns a DialOption which sets a Compressor to use for
  198. // message compression. It has lower priority than the compressor set by the
  199. // UseCompressor CallOption.
  200. //
  201. // Deprecated: use UseCompressor instead. Will be supported throughout 1.x.
  202. func WithCompressor(cp Compressor) DialOption {
  203. return newFuncDialOption(func(o *dialOptions) {
  204. o.cp = cp
  205. })
  206. }
  207. // WithDecompressor returns a DialOption which sets a Decompressor to use for
  208. // incoming message decompression. If incoming response messages are encoded
  209. // using the decompressor's Type(), it will be used. Otherwise, the message
  210. // encoding will be used to look up the compressor registered via
  211. // encoding.RegisterCompressor, which will then be used to decompress the
  212. // message. If no compressor is registered for the encoding, an Unimplemented
  213. // status error will be returned.
  214. //
  215. // Deprecated: use encoding.RegisterCompressor instead. Will be supported
  216. // throughout 1.x.
  217. func WithDecompressor(dc Decompressor) DialOption {
  218. return newFuncDialOption(func(o *dialOptions) {
  219. o.dc = dc
  220. })
  221. }
  222. // WithConnectParams configures the ClientConn to use the provided ConnectParams
  223. // for creating and maintaining connections to servers.
  224. //
  225. // The backoff configuration specified as part of the ConnectParams overrides
  226. // all defaults specified in
  227. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider
  228. // using the backoff.DefaultConfig as a base, in cases where you want to
  229. // override only a subset of the backoff configuration.
  230. func WithConnectParams(p ConnectParams) DialOption {
  231. return newFuncDialOption(func(o *dialOptions) {
  232. o.bs = internalbackoff.Exponential{Config: p.Backoff}
  233. o.minConnectTimeout = func() time.Duration {
  234. return p.MinConnectTimeout
  235. }
  236. })
  237. }
  238. // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
  239. // when backing off after failed connection attempts.
  240. //
  241. // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
  242. func WithBackoffMaxDelay(md time.Duration) DialOption {
  243. return WithBackoffConfig(BackoffConfig{MaxDelay: md})
  244. }
  245. // WithBackoffConfig configures the dialer to use the provided backoff
  246. // parameters after connection failures.
  247. //
  248. // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
  249. func WithBackoffConfig(b BackoffConfig) DialOption {
  250. bc := backoff.DefaultConfig
  251. bc.MaxDelay = b.MaxDelay
  252. return withBackoff(internalbackoff.Exponential{Config: bc})
  253. }
  254. // withBackoff sets the backoff strategy used for connectRetryNum after a failed
  255. // connection attempt.
  256. //
  257. // This can be exported if arbitrary backoff strategies are allowed by gRPC.
  258. func withBackoff(bs internalbackoff.Strategy) DialOption {
  259. return newFuncDialOption(func(o *dialOptions) {
  260. o.bs = bs
  261. })
  262. }
  263. // WithBlock returns a DialOption which makes callers of Dial block until the
  264. // underlying connection is up. Without this, Dial returns immediately and
  265. // connecting the server happens in background.
  266. //
  267. // Use of this feature is not recommended. For more information, please see:
  268. // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
  269. func WithBlock() DialOption {
  270. return newFuncDialOption(func(o *dialOptions) {
  271. o.block = true
  272. })
  273. }
  274. // WithReturnConnectionError returns a DialOption which makes the client connection
  275. // return a string containing both the last connection error that occurred and
  276. // the context.DeadlineExceeded error.
  277. // Implies WithBlock()
  278. //
  279. // Use of this feature is not recommended. For more information, please see:
  280. // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
  281. //
  282. // # Experimental
  283. //
  284. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  285. // later release.
  286. func WithReturnConnectionError() DialOption {
  287. return newFuncDialOption(func(o *dialOptions) {
  288. o.block = true
  289. o.returnLastError = true
  290. })
  291. }
  292. // WithInsecure returns a DialOption which disables transport security for this
  293. // ClientConn. Under the hood, it uses insecure.NewCredentials().
  294. //
  295. // Note that using this DialOption with per-RPC credentials (through
  296. // WithCredentialsBundle or WithPerRPCCredentials) which require transport
  297. // security is incompatible and will cause grpc.Dial() to fail.
  298. //
  299. // Deprecated: use WithTransportCredentials and insecure.NewCredentials()
  300. // instead. Will be supported throughout 1.x.
  301. func WithInsecure() DialOption {
  302. return newFuncDialOption(func(o *dialOptions) {
  303. o.copts.TransportCredentials = insecure.NewCredentials()
  304. })
  305. }
  306. // WithNoProxy returns a DialOption which disables the use of proxies for this
  307. // ClientConn. This is ignored if WithDialer or WithContextDialer are used.
  308. //
  309. // # Experimental
  310. //
  311. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  312. // later release.
  313. func WithNoProxy() DialOption {
  314. return newFuncDialOption(func(o *dialOptions) {
  315. o.copts.UseProxy = false
  316. })
  317. }
  318. // WithTransportCredentials returns a DialOption which configures a connection
  319. // level security credentials (e.g., TLS/SSL). This should not be used together
  320. // with WithCredentialsBundle.
  321. func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
  322. return newFuncDialOption(func(o *dialOptions) {
  323. o.copts.TransportCredentials = creds
  324. })
  325. }
  326. // WithPerRPCCredentials returns a DialOption which sets credentials and places
  327. // auth state on each outbound RPC.
  328. func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
  329. return newFuncDialOption(func(o *dialOptions) {
  330. o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
  331. })
  332. }
  333. // WithCredentialsBundle returns a DialOption to set a credentials bundle for
  334. // the ClientConn.WithCreds. This should not be used together with
  335. // WithTransportCredentials.
  336. //
  337. // # Experimental
  338. //
  339. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  340. // later release.
  341. func WithCredentialsBundle(b credentials.Bundle) DialOption {
  342. return newFuncDialOption(func(o *dialOptions) {
  343. o.copts.CredsBundle = b
  344. })
  345. }
  346. // WithTimeout returns a DialOption that configures a timeout for dialing a
  347. // ClientConn initially. This is valid if and only if WithBlock() is present.
  348. //
  349. // Deprecated: use DialContext instead of Dial and context.WithTimeout
  350. // instead. Will be supported throughout 1.x.
  351. func WithTimeout(d time.Duration) DialOption {
  352. return newFuncDialOption(func(o *dialOptions) {
  353. o.timeout = d
  354. })
  355. }
  356. // WithContextDialer returns a DialOption that sets a dialer to create
  357. // connections. If FailOnNonTempDialError() is set to true, and an error is
  358. // returned by f, gRPC checks the error's Temporary() method to decide if it
  359. // should try to reconnect to the network address.
  360. //
  361. // Note: All supported releases of Go (as of December 2023) override the OS
  362. // defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
  363. // with OS defaults for keepalive time and interval, use a net.Dialer that sets
  364. // the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket
  365. // option to true from the Control field. For a concrete example of how to do
  366. // this, see internal.NetDialerWithTCPKeepalive().
  367. //
  368. // For more information, please see [issue 23459] in the Go github repo.
  369. //
  370. // [issue 23459]: https://github.com/golang/go/issues/23459
  371. func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption {
  372. return newFuncDialOption(func(o *dialOptions) {
  373. o.copts.Dialer = f
  374. })
  375. }
  376. func init() {
  377. internal.WithHealthCheckFunc = withHealthCheckFunc
  378. }
  379. // WithDialer returns a DialOption that specifies a function to use for dialing
  380. // network addresses. If FailOnNonTempDialError() is set to true, and an error
  381. // is returned by f, gRPC checks the error's Temporary() method to decide if it
  382. // should try to reconnect to the network address.
  383. //
  384. // Deprecated: use WithContextDialer instead. Will be supported throughout
  385. // 1.x.
  386. func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
  387. return WithContextDialer(
  388. func(ctx context.Context, addr string) (net.Conn, error) {
  389. if deadline, ok := ctx.Deadline(); ok {
  390. return f(addr, time.Until(deadline))
  391. }
  392. return f(addr, 0)
  393. })
  394. }
  395. // WithStatsHandler returns a DialOption that specifies the stats handler for
  396. // all the RPCs and underlying network connections in this ClientConn.
  397. func WithStatsHandler(h stats.Handler) DialOption {
  398. return newFuncDialOption(func(o *dialOptions) {
  399. if h == nil {
  400. logger.Error("ignoring nil parameter in grpc.WithStatsHandler ClientOption")
  401. // Do not allow a nil stats handler, which would otherwise cause
  402. // panics.
  403. return
  404. }
  405. o.copts.StatsHandlers = append(o.copts.StatsHandlers, h)
  406. })
  407. }
  408. // withBinaryLogger returns a DialOption that specifies the binary logger for
  409. // this ClientConn.
  410. func withBinaryLogger(bl binarylog.Logger) DialOption {
  411. return newFuncDialOption(func(o *dialOptions) {
  412. o.binaryLogger = bl
  413. })
  414. }
  415. // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
  416. // non-temporary dial errors. If f is true, and dialer returns a non-temporary
  417. // error, gRPC will fail the connection to the network address and won't try to
  418. // reconnect. The default value of FailOnNonTempDialError is false.
  419. //
  420. // FailOnNonTempDialError only affects the initial dial, and does not do
  421. // anything useful unless you are also using WithBlock().
  422. //
  423. // Use of this feature is not recommended. For more information, please see:
  424. // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
  425. //
  426. // # Experimental
  427. //
  428. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  429. // later release.
  430. func FailOnNonTempDialError(f bool) DialOption {
  431. return newFuncDialOption(func(o *dialOptions) {
  432. o.copts.FailOnNonTempDialError = f
  433. })
  434. }
  435. // WithUserAgent returns a DialOption that specifies a user agent string for all
  436. // the RPCs.
  437. func WithUserAgent(s string) DialOption {
  438. return newFuncDialOption(func(o *dialOptions) {
  439. o.copts.UserAgent = s + " " + grpcUA
  440. })
  441. }
  442. // WithKeepaliveParams returns a DialOption that specifies keepalive parameters
  443. // for the client transport.
  444. func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
  445. if kp.Time < internal.KeepaliveMinPingTime {
  446. logger.Warningf("Adjusting keepalive ping interval to minimum period of %v", internal.KeepaliveMinPingTime)
  447. kp.Time = internal.KeepaliveMinPingTime
  448. }
  449. return newFuncDialOption(func(o *dialOptions) {
  450. o.copts.KeepaliveParams = kp
  451. })
  452. }
  453. // WithUnaryInterceptor returns a DialOption that specifies the interceptor for
  454. // unary RPCs.
  455. func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
  456. return newFuncDialOption(func(o *dialOptions) {
  457. o.unaryInt = f
  458. })
  459. }
  460. // WithChainUnaryInterceptor returns a DialOption that specifies the chained
  461. // interceptor for unary RPCs. The first interceptor will be the outer most,
  462. // while the last interceptor will be the inner most wrapper around the real call.
  463. // All interceptors added by this method will be chained, and the interceptor
  464. // defined by WithUnaryInterceptor will always be prepended to the chain.
  465. func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption {
  466. return newFuncDialOption(func(o *dialOptions) {
  467. o.chainUnaryInts = append(o.chainUnaryInts, interceptors...)
  468. })
  469. }
  470. // WithStreamInterceptor returns a DialOption that specifies the interceptor for
  471. // streaming RPCs.
  472. func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
  473. return newFuncDialOption(func(o *dialOptions) {
  474. o.streamInt = f
  475. })
  476. }
  477. // WithChainStreamInterceptor returns a DialOption that specifies the chained
  478. // interceptor for streaming RPCs. The first interceptor will be the outer most,
  479. // while the last interceptor will be the inner most wrapper around the real call.
  480. // All interceptors added by this method will be chained, and the interceptor
  481. // defined by WithStreamInterceptor will always be prepended to the chain.
  482. func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption {
  483. return newFuncDialOption(func(o *dialOptions) {
  484. o.chainStreamInts = append(o.chainStreamInts, interceptors...)
  485. })
  486. }
  487. // WithAuthority returns a DialOption that specifies the value to be used as the
  488. // :authority pseudo-header and as the server name in authentication handshake.
  489. func WithAuthority(a string) DialOption {
  490. return newFuncDialOption(func(o *dialOptions) {
  491. o.authority = a
  492. })
  493. }
  494. // WithChannelzParentID returns a DialOption that specifies the channelz ID of
  495. // current ClientConn's parent. This function is used in nested channel creation
  496. // (e.g. grpclb dial).
  497. //
  498. // # Experimental
  499. //
  500. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  501. // later release.
  502. func WithChannelzParentID(id *channelz.Identifier) DialOption {
  503. return newFuncDialOption(func(o *dialOptions) {
  504. o.channelzParentID = id
  505. })
  506. }
  507. // WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any
  508. // service config provided by the resolver and provides a hint to the resolver
  509. // to not fetch service configs.
  510. //
  511. // Note that this dial option only disables service config from resolver. If
  512. // default service config is provided, gRPC will use the default service config.
  513. func WithDisableServiceConfig() DialOption {
  514. return newFuncDialOption(func(o *dialOptions) {
  515. o.disableServiceConfig = true
  516. })
  517. }
  518. // WithDefaultServiceConfig returns a DialOption that configures the default
  519. // service config, which will be used in cases where:
  520. //
  521. // 1. WithDisableServiceConfig is also used, or
  522. //
  523. // 2. The name resolver does not provide a service config or provides an
  524. // invalid service config.
  525. //
  526. // The parameter s is the JSON representation of the default service config.
  527. // For more information about service configs, see:
  528. // https://github.com/grpc/grpc/blob/master/doc/service_config.md
  529. // For a simple example of usage, see:
  530. // examples/features/load_balancing/client/main.go
  531. func WithDefaultServiceConfig(s string) DialOption {
  532. return newFuncDialOption(func(o *dialOptions) {
  533. o.defaultServiceConfigRawJSON = &s
  534. })
  535. }
  536. // WithDisableRetry returns a DialOption that disables retries, even if the
  537. // service config enables them. This does not impact transparent retries, which
  538. // will happen automatically if no data is written to the wire or if the RPC is
  539. // unprocessed by the remote server.
  540. func WithDisableRetry() DialOption {
  541. return newFuncDialOption(func(o *dialOptions) {
  542. o.disableRetry = true
  543. })
  544. }
  545. // WithMaxHeaderListSize returns a DialOption that specifies the maximum
  546. // (uncompressed) size of header list that the client is prepared to accept.
  547. func WithMaxHeaderListSize(s uint32) DialOption {
  548. return newFuncDialOption(func(o *dialOptions) {
  549. o.copts.MaxHeaderListSize = &s
  550. })
  551. }
  552. // WithDisableHealthCheck disables the LB channel health checking for all
  553. // SubConns of this ClientConn.
  554. //
  555. // # Experimental
  556. //
  557. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  558. // later release.
  559. func WithDisableHealthCheck() DialOption {
  560. return newFuncDialOption(func(o *dialOptions) {
  561. o.disableHealthCheck = true
  562. })
  563. }
  564. // withHealthCheckFunc replaces the default health check function with the
  565. // provided one. It makes tests easier to change the health check function.
  566. //
  567. // For testing purpose only.
  568. func withHealthCheckFunc(f internal.HealthChecker) DialOption {
  569. return newFuncDialOption(func(o *dialOptions) {
  570. o.healthCheckFunc = f
  571. })
  572. }
  573. func defaultDialOptions() dialOptions {
  574. return dialOptions{
  575. copts: transport.ConnectOptions{
  576. ReadBufferSize: defaultReadBufSize,
  577. WriteBufferSize: defaultWriteBufSize,
  578. UseProxy: true,
  579. UserAgent: grpcUA,
  580. },
  581. bs: internalbackoff.DefaultExponential,
  582. healthCheckFunc: internal.HealthCheckFunc,
  583. idleTimeout: 30 * time.Minute,
  584. recvBufferPool: nopBufferPool{},
  585. }
  586. }
  587. // withGetMinConnectDeadline specifies the function that clientconn uses to
  588. // get minConnectDeadline. This can be used to make connection attempts happen
  589. // faster/slower.
  590. //
  591. // For testing purpose only.
  592. func withMinConnectDeadline(f func() time.Duration) DialOption {
  593. return newFuncDialOption(func(o *dialOptions) {
  594. o.minConnectTimeout = f
  595. })
  596. }
  597. // WithResolvers allows a list of resolver implementations to be registered
  598. // locally with the ClientConn without needing to be globally registered via
  599. // resolver.Register. They will be matched against the scheme used for the
  600. // current Dial only, and will take precedence over the global registry.
  601. //
  602. // # Experimental
  603. //
  604. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  605. // later release.
  606. func WithResolvers(rs ...resolver.Builder) DialOption {
  607. return newFuncDialOption(func(o *dialOptions) {
  608. o.resolvers = append(o.resolvers, rs...)
  609. })
  610. }
  611. // WithIdleTimeout returns a DialOption that configures an idle timeout for the
  612. // channel. If the channel is idle for the configured timeout, i.e there are no
  613. // ongoing RPCs and no new RPCs are initiated, the channel will enter idle mode
  614. // and as a result the name resolver and load balancer will be shut down. The
  615. // channel will exit idle mode when the Connect() method is called or when an
  616. // RPC is initiated.
  617. //
  618. // A default timeout of 30 minutes will be used if this dial option is not set
  619. // at dial time and idleness can be disabled by passing a timeout of zero.
  620. //
  621. // # Experimental
  622. //
  623. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  624. // later release.
  625. func WithIdleTimeout(d time.Duration) DialOption {
  626. return newFuncDialOption(func(o *dialOptions) {
  627. o.idleTimeout = d
  628. })
  629. }
  630. // WithRecvBufferPool returns a DialOption that configures the ClientConn
  631. // to use the provided shared buffer pool for parsing incoming messages. Depending
  632. // on the application's workload, this could result in reduced memory allocation.
  633. //
  634. // If you are unsure about how to implement a memory pool but want to utilize one,
  635. // begin with grpc.NewSharedBufferPool.
  636. //
  637. // Note: The shared buffer pool feature will not be active if any of the following
  638. // options are used: WithStatsHandler, EnableTracing, or binary logging. In such
  639. // cases, the shared buffer pool will be ignored.
  640. //
  641. // Deprecated: use experimental.WithRecvBufferPool instead. Will be deleted in
  642. // v1.60.0 or later.
  643. func WithRecvBufferPool(bufferPool SharedBufferPool) DialOption {
  644. return withRecvBufferPool(bufferPool)
  645. }
  646. func withRecvBufferPool(bufferPool SharedBufferPool) DialOption {
  647. return newFuncDialOption(func(o *dialOptions) {
  648. o.recvBufferPool = bufferPool
  649. })
  650. }