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