dialoptions.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. }
  46. // dialOptions configure a Dial call. dialOptions are set by the DialOption
  47. // values passed to Dial.
  48. type dialOptions struct {
  49. unaryInt UnaryClientInterceptor
  50. streamInt StreamClientInterceptor
  51. chainUnaryInts []UnaryClientInterceptor
  52. chainStreamInts []StreamClientInterceptor
  53. cp Compressor
  54. dc Decompressor
  55. bs internalbackoff.Strategy
  56. block bool
  57. returnLastError bool
  58. timeout time.Duration
  59. scChan <-chan ServiceConfig
  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. // WithServiceConfig returns a DialOption which has a channel to read the
  223. // service configuration.
  224. //
  225. // Deprecated: service config should be received through name resolver or via
  226. // WithDefaultServiceConfig, as specified at
  227. // https://github.com/grpc/grpc/blob/master/doc/service_config.md. Will be
  228. // removed in a future 1.x release.
  229. func WithServiceConfig(c <-chan ServiceConfig) DialOption {
  230. return newFuncDialOption(func(o *dialOptions) {
  231. o.scChan = c
  232. })
  233. }
  234. // WithConnectParams configures the ClientConn to use the provided ConnectParams
  235. // for creating and maintaining connections to servers.
  236. //
  237. // The backoff configuration specified as part of the ConnectParams overrides
  238. // all defaults specified in
  239. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider
  240. // using the backoff.DefaultConfig as a base, in cases where you want to
  241. // override only a subset of the backoff configuration.
  242. func WithConnectParams(p ConnectParams) DialOption {
  243. return newFuncDialOption(func(o *dialOptions) {
  244. o.bs = internalbackoff.Exponential{Config: p.Backoff}
  245. o.minConnectTimeout = func() time.Duration {
  246. return p.MinConnectTimeout
  247. }
  248. })
  249. }
  250. // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
  251. // when backing off after failed connection attempts.
  252. //
  253. // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
  254. func WithBackoffMaxDelay(md time.Duration) DialOption {
  255. return WithBackoffConfig(BackoffConfig{MaxDelay: md})
  256. }
  257. // WithBackoffConfig configures the dialer to use the provided backoff
  258. // parameters after connection failures.
  259. //
  260. // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
  261. func WithBackoffConfig(b BackoffConfig) DialOption {
  262. bc := backoff.DefaultConfig
  263. bc.MaxDelay = b.MaxDelay
  264. return withBackoff(internalbackoff.Exponential{Config: bc})
  265. }
  266. // withBackoff sets the backoff strategy used for connectRetryNum after a failed
  267. // connection attempt.
  268. //
  269. // This can be exported if arbitrary backoff strategies are allowed by gRPC.
  270. func withBackoff(bs internalbackoff.Strategy) DialOption {
  271. return newFuncDialOption(func(o *dialOptions) {
  272. o.bs = bs
  273. })
  274. }
  275. // WithBlock returns a DialOption which makes callers of Dial block until the
  276. // underlying connection is up. Without this, Dial returns immediately and
  277. // connecting the server happens in background.
  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. func WithBlock() DialOption {
  282. return newFuncDialOption(func(o *dialOptions) {
  283. o.block = true
  284. })
  285. }
  286. // WithReturnConnectionError returns a DialOption which makes the client connection
  287. // return a string containing both the last connection error that occurred and
  288. // the context.DeadlineExceeded error.
  289. // Implies WithBlock()
  290. //
  291. // Use of this feature is not recommended. For more information, please see:
  292. // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
  293. //
  294. // # Experimental
  295. //
  296. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  297. // later release.
  298. func WithReturnConnectionError() DialOption {
  299. return newFuncDialOption(func(o *dialOptions) {
  300. o.block = true
  301. o.returnLastError = true
  302. })
  303. }
  304. // WithInsecure returns a DialOption which disables transport security for this
  305. // ClientConn. Under the hood, it uses insecure.NewCredentials().
  306. //
  307. // Note that using this DialOption with per-RPC credentials (through
  308. // WithCredentialsBundle or WithPerRPCCredentials) which require transport
  309. // security is incompatible and will cause grpc.Dial() to fail.
  310. //
  311. // Deprecated: use WithTransportCredentials and insecure.NewCredentials()
  312. // instead. Will be supported throughout 1.x.
  313. func WithInsecure() DialOption {
  314. return newFuncDialOption(func(o *dialOptions) {
  315. o.copts.TransportCredentials = insecure.NewCredentials()
  316. })
  317. }
  318. // WithNoProxy returns a DialOption which disables the use of proxies for this
  319. // ClientConn. This is ignored if WithDialer or WithContextDialer are used.
  320. //
  321. // # Experimental
  322. //
  323. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  324. // later release.
  325. func WithNoProxy() DialOption {
  326. return newFuncDialOption(func(o *dialOptions) {
  327. o.copts.UseProxy = false
  328. })
  329. }
  330. // WithTransportCredentials returns a DialOption which configures a connection
  331. // level security credentials (e.g., TLS/SSL). This should not be used together
  332. // with WithCredentialsBundle.
  333. func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
  334. return newFuncDialOption(func(o *dialOptions) {
  335. o.copts.TransportCredentials = creds
  336. })
  337. }
  338. // WithPerRPCCredentials returns a DialOption which sets credentials and places
  339. // auth state on each outbound RPC.
  340. func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
  341. return newFuncDialOption(func(o *dialOptions) {
  342. o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
  343. })
  344. }
  345. // WithCredentialsBundle returns a DialOption to set a credentials bundle for
  346. // the ClientConn.WithCreds. This should not be used together with
  347. // WithTransportCredentials.
  348. //
  349. // # Experimental
  350. //
  351. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  352. // later release.
  353. func WithCredentialsBundle(b credentials.Bundle) DialOption {
  354. return newFuncDialOption(func(o *dialOptions) {
  355. o.copts.CredsBundle = b
  356. })
  357. }
  358. // WithTimeout returns a DialOption that configures a timeout for dialing a
  359. // ClientConn initially. This is valid if and only if WithBlock() is present.
  360. //
  361. // Deprecated: use DialContext instead of Dial and context.WithTimeout
  362. // instead. Will be supported throughout 1.x.
  363. func WithTimeout(d time.Duration) DialOption {
  364. return newFuncDialOption(func(o *dialOptions) {
  365. o.timeout = d
  366. })
  367. }
  368. // WithContextDialer returns a DialOption that sets a dialer to create
  369. // connections. If FailOnNonTempDialError() is set to true, and an error is
  370. // returned by f, gRPC checks the error's Temporary() method to decide if it
  371. // should try to reconnect to the network address.
  372. func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption {
  373. return newFuncDialOption(func(o *dialOptions) {
  374. o.copts.Dialer = f
  375. })
  376. }
  377. func init() {
  378. internal.WithHealthCheckFunc = withHealthCheckFunc
  379. }
  380. // WithDialer returns a DialOption that specifies a function to use for dialing
  381. // network addresses. If FailOnNonTempDialError() is set to true, and an error
  382. // is returned by f, gRPC checks the error's Temporary() method to decide if it
  383. // should try to reconnect to the network address.
  384. //
  385. // Deprecated: use WithContextDialer instead. Will be supported throughout
  386. // 1.x.
  387. func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
  388. return WithContextDialer(
  389. func(ctx context.Context, addr string) (net.Conn, error) {
  390. if deadline, ok := ctx.Deadline(); ok {
  391. return f(addr, time.Until(deadline))
  392. }
  393. return f(addr, 0)
  394. })
  395. }
  396. // WithStatsHandler returns a DialOption that specifies the stats handler for
  397. // all the RPCs and underlying network connections in this ClientConn.
  398. func WithStatsHandler(h stats.Handler) DialOption {
  399. return newFuncDialOption(func(o *dialOptions) {
  400. if h == nil {
  401. logger.Error("ignoring nil parameter in grpc.WithStatsHandler ClientOption")
  402. // Do not allow a nil stats handler, which would otherwise cause
  403. // panics.
  404. return
  405. }
  406. o.copts.StatsHandlers = append(o.copts.StatsHandlers, h)
  407. })
  408. }
  409. // withBinaryLogger returns a DialOption that specifies the binary logger for
  410. // this ClientConn.
  411. func withBinaryLogger(bl binarylog.Logger) DialOption {
  412. return newFuncDialOption(func(o *dialOptions) {
  413. o.binaryLogger = bl
  414. })
  415. }
  416. // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
  417. // non-temporary dial errors. If f is true, and dialer returns a non-temporary
  418. // error, gRPC will fail the connection to the network address and won't try to
  419. // reconnect. The default value of FailOnNonTempDialError is false.
  420. //
  421. // FailOnNonTempDialError only affects the initial dial, and does not do
  422. // anything useful unless you are also using WithBlock().
  423. //
  424. // Use of this feature is not recommended. For more information, please see:
  425. // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
  426. //
  427. // # Experimental
  428. //
  429. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  430. // later release.
  431. func FailOnNonTempDialError(f bool) DialOption {
  432. return newFuncDialOption(func(o *dialOptions) {
  433. o.copts.FailOnNonTempDialError = f
  434. })
  435. }
  436. // WithUserAgent returns a DialOption that specifies a user agent string for all
  437. // the RPCs.
  438. func WithUserAgent(s string) DialOption {
  439. return newFuncDialOption(func(o *dialOptions) {
  440. o.copts.UserAgent = s
  441. })
  442. }
  443. // WithKeepaliveParams returns a DialOption that specifies keepalive parameters
  444. // for the client transport.
  445. func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
  446. if kp.Time < internal.KeepaliveMinPingTime {
  447. logger.Warningf("Adjusting keepalive ping interval to minimum period of %v", internal.KeepaliveMinPingTime)
  448. kp.Time = internal.KeepaliveMinPingTime
  449. }
  450. return newFuncDialOption(func(o *dialOptions) {
  451. o.copts.KeepaliveParams = kp
  452. })
  453. }
  454. // WithUnaryInterceptor returns a DialOption that specifies the interceptor for
  455. // unary RPCs.
  456. func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
  457. return newFuncDialOption(func(o *dialOptions) {
  458. o.unaryInt = f
  459. })
  460. }
  461. // WithChainUnaryInterceptor returns a DialOption that specifies the chained
  462. // interceptor for unary RPCs. The first interceptor will be the outer most,
  463. // while the last interceptor will be the inner most wrapper around the real call.
  464. // All interceptors added by this method will be chained, and the interceptor
  465. // defined by WithUnaryInterceptor will always be prepended to the chain.
  466. func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption {
  467. return newFuncDialOption(func(o *dialOptions) {
  468. o.chainUnaryInts = append(o.chainUnaryInts, interceptors...)
  469. })
  470. }
  471. // WithStreamInterceptor returns a DialOption that specifies the interceptor for
  472. // streaming RPCs.
  473. func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
  474. return newFuncDialOption(func(o *dialOptions) {
  475. o.streamInt = f
  476. })
  477. }
  478. // WithChainStreamInterceptor returns a DialOption that specifies the chained
  479. // interceptor for streaming RPCs. The first interceptor will be the outer most,
  480. // while the last interceptor will be the inner most wrapper around the real call.
  481. // All interceptors added by this method will be chained, and the interceptor
  482. // defined by WithStreamInterceptor will always be prepended to the chain.
  483. func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption {
  484. return newFuncDialOption(func(o *dialOptions) {
  485. o.chainStreamInts = append(o.chainStreamInts, interceptors...)
  486. })
  487. }
  488. // WithAuthority returns a DialOption that specifies the value to be used as the
  489. // :authority pseudo-header and as the server name in authentication handshake.
  490. func WithAuthority(a string) DialOption {
  491. return newFuncDialOption(func(o *dialOptions) {
  492. o.authority = a
  493. })
  494. }
  495. // WithChannelzParentID returns a DialOption that specifies the channelz ID of
  496. // current ClientConn's parent. This function is used in nested channel creation
  497. // (e.g. grpclb dial).
  498. //
  499. // # Experimental
  500. //
  501. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  502. // later release.
  503. func WithChannelzParentID(id *channelz.Identifier) DialOption {
  504. return newFuncDialOption(func(o *dialOptions) {
  505. o.channelzParentID = id
  506. })
  507. }
  508. // WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any
  509. // service config provided by the resolver and provides a hint to the resolver
  510. // to not fetch service configs.
  511. //
  512. // Note that this dial option only disables service config from resolver. If
  513. // default service config is provided, gRPC will use the default service config.
  514. func WithDisableServiceConfig() DialOption {
  515. return newFuncDialOption(func(o *dialOptions) {
  516. o.disableServiceConfig = true
  517. })
  518. }
  519. // WithDefaultServiceConfig returns a DialOption that configures the default
  520. // service config, which will be used in cases where:
  521. //
  522. // 1. WithDisableServiceConfig is also used, or
  523. //
  524. // 2. The name resolver does not provide a service config or provides an
  525. // invalid service config.
  526. //
  527. // The parameter s is the JSON representation of the default service config.
  528. // For more information about service configs, see:
  529. // https://github.com/grpc/grpc/blob/master/doc/service_config.md
  530. // For a simple example of usage, see:
  531. // examples/features/load_balancing/client/main.go
  532. func WithDefaultServiceConfig(s string) DialOption {
  533. return newFuncDialOption(func(o *dialOptions) {
  534. o.defaultServiceConfigRawJSON = &s
  535. })
  536. }
  537. // WithDisableRetry returns a DialOption that disables retries, even if the
  538. // service config enables them. This does not impact transparent retries, which
  539. // will happen automatically if no data is written to the wire or if the RPC is
  540. // unprocessed by the remote server.
  541. func WithDisableRetry() DialOption {
  542. return newFuncDialOption(func(o *dialOptions) {
  543. o.disableRetry = true
  544. })
  545. }
  546. // WithMaxHeaderListSize returns a DialOption that specifies the maximum
  547. // (uncompressed) size of header list that the client is prepared to accept.
  548. func WithMaxHeaderListSize(s uint32) DialOption {
  549. return newFuncDialOption(func(o *dialOptions) {
  550. o.copts.MaxHeaderListSize = &s
  551. })
  552. }
  553. // WithDisableHealthCheck disables the LB channel health checking for all
  554. // SubConns of this ClientConn.
  555. //
  556. // # Experimental
  557. //
  558. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  559. // later release.
  560. func WithDisableHealthCheck() DialOption {
  561. return newFuncDialOption(func(o *dialOptions) {
  562. o.disableHealthCheck = true
  563. })
  564. }
  565. // withHealthCheckFunc replaces the default health check function with the
  566. // provided one. It makes tests easier to change the health check function.
  567. //
  568. // For testing purpose only.
  569. func withHealthCheckFunc(f internal.HealthChecker) DialOption {
  570. return newFuncDialOption(func(o *dialOptions) {
  571. o.healthCheckFunc = f
  572. })
  573. }
  574. func defaultDialOptions() dialOptions {
  575. return dialOptions{
  576. healthCheckFunc: internal.HealthCheckFunc,
  577. copts: transport.ConnectOptions{
  578. WriteBufferSize: defaultWriteBufSize,
  579. ReadBufferSize: defaultReadBufSize,
  580. UseProxy: true,
  581. },
  582. recvBufferPool: nopBufferPool{},
  583. idleTimeout: 30 * time.Minute,
  584. }
  585. }
  586. // withGetMinConnectDeadline specifies the function that clientconn uses to
  587. // get minConnectDeadline. This can be used to make connection attempts happen
  588. // faster/slower.
  589. //
  590. // For testing purpose only.
  591. func withMinConnectDeadline(f func() time.Duration) DialOption {
  592. return newFuncDialOption(func(o *dialOptions) {
  593. o.minConnectTimeout = f
  594. })
  595. }
  596. // WithResolvers allows a list of resolver implementations to be registered
  597. // locally with the ClientConn without needing to be globally registered via
  598. // resolver.Register. They will be matched against the scheme used for the
  599. // current Dial only, and will take precedence over the global registry.
  600. //
  601. // # Experimental
  602. //
  603. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  604. // later release.
  605. func WithResolvers(rs ...resolver.Builder) DialOption {
  606. return newFuncDialOption(func(o *dialOptions) {
  607. o.resolvers = append(o.resolvers, rs...)
  608. })
  609. }
  610. // WithIdleTimeout returns a DialOption that configures an idle timeout for the
  611. // channel. If the channel is idle for the configured timeout, i.e there are no
  612. // ongoing RPCs and no new RPCs are initiated, the channel will enter idle mode
  613. // and as a result the name resolver and load balancer will be shut down. The
  614. // channel will exit idle mode when the Connect() method is called or when an
  615. // RPC is initiated.
  616. //
  617. // A default timeout of 30 minutes will be used if this dial option is not set
  618. // at dial time and idleness can be disabled by passing a timeout of zero.
  619. //
  620. // # Experimental
  621. //
  622. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  623. // later release.
  624. func WithIdleTimeout(d time.Duration) DialOption {
  625. return newFuncDialOption(func(o *dialOptions) {
  626. o.idleTimeout = d
  627. })
  628. }
  629. // WithRecvBufferPool returns a DialOption that configures the ClientConn
  630. // to use the provided shared buffer pool for parsing incoming messages. Depending
  631. // on the application's workload, this could result in reduced memory allocation.
  632. //
  633. // If you are unsure about how to implement a memory pool but want to utilize one,
  634. // begin with grpc.NewSharedBufferPool.
  635. //
  636. // Note: The shared buffer pool feature will not be active if any of the following
  637. // options are used: WithStatsHandler, EnableTracing, or binary logging. In such
  638. // cases, the shared buffer pool will be ignored.
  639. //
  640. // # Experimental
  641. //
  642. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  643. // later release.
  644. func WithRecvBufferPool(bufferPool SharedBufferPool) DialOption {
  645. return newFuncDialOption(func(o *dialOptions) {
  646. o.recvBufferPool = bufferPool
  647. })
  648. }