3 * Copyright 2018 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
27 "google.golang.org/grpc/balancer"
28 "google.golang.org/grpc/credentials"
29 "google.golang.org/grpc/internal"
30 "google.golang.org/grpc/internal/backoff"
31 "google.golang.org/grpc/internal/envconfig"
32 "google.golang.org/grpc/internal/transport"
33 "google.golang.org/grpc/keepalive"
34 "google.golang.org/grpc/resolver"
35 "google.golang.org/grpc/stats"
38 // dialOptions configure a Dial call. dialOptions are set by the DialOption
39 // values passed to Dial.
40 type dialOptions struct {
41 unaryInt UnaryClientInterceptor
42 streamInt StreamClientInterceptor
49 scChan <-chan ServiceConfig
51 copts transport.ConnectOptions
52 callOptions []CallOption
53 // This is used by v1 balancer dial option WithBalancer to support v1
54 // balancer, and also by WithBalancerName dial option.
55 balancerBuilder balancer.Builder
56 // This is to support grpclb.
57 resolverBuilder resolver.Builder
58 reqHandshake envconfig.RequireHandshakeSetting
59 channelzParentID int64
60 disableServiceConfig bool
62 disableHealthCheck bool
63 healthCheckFunc internal.HealthChecker
66 // DialOption configures how we set up the connection.
67 type DialOption interface {
71 // EmptyDialOption does not alter the dial configuration. It can be embedded in
72 // another structure to build custom dial options.
74 // This API is EXPERIMENTAL.
75 type EmptyDialOption struct{}
77 func (EmptyDialOption) apply(*dialOptions) {}
79 // funcDialOption wraps a function that modifies dialOptions into an
80 // implementation of the DialOption interface.
81 type funcDialOption struct {
85 func (fdo *funcDialOption) apply(do *dialOptions) {
89 func newFuncDialOption(f func(*dialOptions)) *funcDialOption {
90 return &funcDialOption{
95 // WithWaitForHandshake blocks until the initial settings frame is received from
96 // the server before assigning RPCs to the connection.
98 // Deprecated: this is the default behavior, and this option will be removed
99 // after the 1.18 release.
100 func WithWaitForHandshake() DialOption {
101 return newFuncDialOption(func(o *dialOptions) {
102 o.reqHandshake = envconfig.RequireHandshakeOn
106 // WithWriteBufferSize determines how much data can be batched before doing a
107 // write on the wire. The corresponding memory allocation for this buffer will
108 // be twice the size to keep syscalls low. The default value for this buffer is
111 // Zero will disable the write buffer such that each write will be on underlying
112 // connection. Note: A Send call may not directly translate to a write.
113 func WithWriteBufferSize(s int) DialOption {
114 return newFuncDialOption(func(o *dialOptions) {
115 o.copts.WriteBufferSize = s
119 // WithReadBufferSize lets you set the size of read buffer, this determines how
120 // much data can be read at most for each read syscall.
122 // The default value for this buffer is 32KB. Zero will disable read buffer for
123 // a connection so data framer can access the underlying conn directly.
124 func WithReadBufferSize(s int) DialOption {
125 return newFuncDialOption(func(o *dialOptions) {
126 o.copts.ReadBufferSize = s
130 // WithInitialWindowSize returns a DialOption which sets the value for initial
131 // window size on a stream. The lower bound for window size is 64K and any value
132 // smaller than that will be ignored.
133 func WithInitialWindowSize(s int32) DialOption {
134 return newFuncDialOption(func(o *dialOptions) {
135 o.copts.InitialWindowSize = s
139 // WithInitialConnWindowSize returns a DialOption which sets the value for
140 // initial window size on a connection. The lower bound for window size is 64K
141 // and any value smaller than that will be ignored.
142 func WithInitialConnWindowSize(s int32) DialOption {
143 return newFuncDialOption(func(o *dialOptions) {
144 o.copts.InitialConnWindowSize = s
148 // WithMaxMsgSize returns a DialOption which sets the maximum message size the
149 // client can receive.
151 // Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead.
152 func WithMaxMsgSize(s int) DialOption {
153 return WithDefaultCallOptions(MaxCallRecvMsgSize(s))
156 // WithDefaultCallOptions returns a DialOption which sets the default
157 // CallOptions for calls over the connection.
158 func WithDefaultCallOptions(cos ...CallOption) DialOption {
159 return newFuncDialOption(func(o *dialOptions) {
160 o.callOptions = append(o.callOptions, cos...)
164 // WithCodec returns a DialOption which sets a codec for message marshaling and
167 // Deprecated: use WithDefaultCallOptions(CallCustomCodec(c)) instead.
168 func WithCodec(c Codec) DialOption {
169 return WithDefaultCallOptions(CallCustomCodec(c))
172 // WithCompressor returns a DialOption which sets a Compressor to use for
173 // message compression. It has lower priority than the compressor set by the
174 // UseCompressor CallOption.
176 // Deprecated: use UseCompressor instead.
177 func WithCompressor(cp Compressor) DialOption {
178 return newFuncDialOption(func(o *dialOptions) {
183 // WithDecompressor returns a DialOption which sets a Decompressor to use for
184 // incoming message decompression. If incoming response messages are encoded
185 // using the decompressor's Type(), it will be used. Otherwise, the message
186 // encoding will be used to look up the compressor registered via
187 // encoding.RegisterCompressor, which will then be used to decompress the
188 // message. If no compressor is registered for the encoding, an Unimplemented
189 // status error will be returned.
191 // Deprecated: use encoding.RegisterCompressor instead.
192 func WithDecompressor(dc Decompressor) DialOption {
193 return newFuncDialOption(func(o *dialOptions) {
198 // WithBalancer returns a DialOption which sets a load balancer with the v1 API.
199 // Name resolver will be ignored if this DialOption is specified.
201 // Deprecated: use the new balancer APIs in balancer package and
203 func WithBalancer(b Balancer) DialOption {
204 return newFuncDialOption(func(o *dialOptions) {
205 o.balancerBuilder = &balancerWrapperBuilder{
211 // WithBalancerName sets the balancer that the ClientConn will be initialized
212 // with. Balancer registered with balancerName will be used. This function
213 // panics if no balancer was registered by balancerName.
215 // The balancer cannot be overridden by balancer option specified by service
218 // This is an EXPERIMENTAL API.
219 func WithBalancerName(balancerName string) DialOption {
220 builder := balancer.Get(balancerName)
222 panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName))
224 return newFuncDialOption(func(o *dialOptions) {
225 o.balancerBuilder = builder
229 // withResolverBuilder is only for grpclb.
230 func withResolverBuilder(b resolver.Builder) DialOption {
231 return newFuncDialOption(func(o *dialOptions) {
232 o.resolverBuilder = b
236 // WithServiceConfig returns a DialOption which has a channel to read the
237 // service configuration.
239 // Deprecated: service config should be received through name resolver, as
241 // https://github.com/grpc/grpc/blob/master/doc/service_config.md
242 func WithServiceConfig(c <-chan ServiceConfig) DialOption {
243 return newFuncDialOption(func(o *dialOptions) {
248 // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
249 // when backing off after failed connection attempts.
250 func WithBackoffMaxDelay(md time.Duration) DialOption {
251 return WithBackoffConfig(BackoffConfig{MaxDelay: md})
254 // WithBackoffConfig configures the dialer to use the provided backoff
255 // parameters after connection failures.
257 // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
259 func WithBackoffConfig(b BackoffConfig) DialOption {
260 return withBackoff(backoff.Exponential{
261 MaxDelay: b.MaxDelay,
265 // withBackoff sets the backoff strategy used for connectRetryNum after a failed
266 // connection attempt.
268 // This can be exported if arbitrary backoff strategies are allowed by gRPC.
269 func withBackoff(bs backoff.Strategy) DialOption {
270 return newFuncDialOption(func(o *dialOptions) {
275 // WithBlock returns a DialOption which makes caller of Dial blocks until the
276 // underlying connection is up. Without this, Dial returns immediately and
277 // connecting the server happens in background.
278 func WithBlock() DialOption {
279 return newFuncDialOption(func(o *dialOptions) {
284 // WithInsecure returns a DialOption which disables transport security for this
285 // ClientConn. Note that transport security is required unless WithInsecure is
287 func WithInsecure() DialOption {
288 return newFuncDialOption(func(o *dialOptions) {
293 // WithTransportCredentials returns a DialOption which configures a connection
294 // level security credentials (e.g., TLS/SSL). This should not be used together
295 // with WithCredentialsBundle.
296 func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
297 return newFuncDialOption(func(o *dialOptions) {
298 o.copts.TransportCredentials = creds
302 // WithPerRPCCredentials returns a DialOption which sets credentials and places
303 // auth state on each outbound RPC.
304 func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
305 return newFuncDialOption(func(o *dialOptions) {
306 o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
310 // WithCredentialsBundle returns a DialOption to set a credentials bundle for
311 // the ClientConn.WithCreds. This should not be used together with
312 // WithTransportCredentials.
314 // This API is experimental.
315 func WithCredentialsBundle(b credentials.Bundle) DialOption {
316 return newFuncDialOption(func(o *dialOptions) {
317 o.copts.CredsBundle = b
321 // WithTimeout returns a DialOption that configures a timeout for dialing a
322 // ClientConn initially. This is valid if and only if WithBlock() is present.
324 // Deprecated: use DialContext and context.WithTimeout instead.
325 func WithTimeout(d time.Duration) DialOption {
326 return newFuncDialOption(func(o *dialOptions) {
331 func withContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption {
332 return newFuncDialOption(func(o *dialOptions) {
338 internal.WithContextDialer = withContextDialer
339 internal.WithResolverBuilder = withResolverBuilder
340 internal.WithHealthCheckFunc = withHealthCheckFunc
343 // WithDialer returns a DialOption that specifies a function to use for dialing
344 // network addresses. If FailOnNonTempDialError() is set to true, and an error
345 // is returned by f, gRPC checks the error's Temporary() method to decide if it
346 // should try to reconnect to the network address.
347 func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
348 return withContextDialer(
349 func(ctx context.Context, addr string) (net.Conn, error) {
350 if deadline, ok := ctx.Deadline(); ok {
351 return f(addr, deadline.Sub(time.Now()))
357 // WithStatsHandler returns a DialOption that specifies the stats handler for
358 // all the RPCs and underlying network connections in this ClientConn.
359 func WithStatsHandler(h stats.Handler) DialOption {
360 return newFuncDialOption(func(o *dialOptions) {
361 o.copts.StatsHandler = h
365 // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
366 // non-temporary dial errors. If f is true, and dialer returns a non-temporary
367 // error, gRPC will fail the connection to the network address and won't try to
368 // reconnect. The default value of FailOnNonTempDialError is false.
370 // FailOnNonTempDialError only affects the initial dial, and does not do
371 // anything useful unless you are also using WithBlock().
373 // This is an EXPERIMENTAL API.
374 func FailOnNonTempDialError(f bool) DialOption {
375 return newFuncDialOption(func(o *dialOptions) {
376 o.copts.FailOnNonTempDialError = f
380 // WithUserAgent returns a DialOption that specifies a user agent string for all
382 func WithUserAgent(s string) DialOption {
383 return newFuncDialOption(func(o *dialOptions) {
384 o.copts.UserAgent = s
388 // WithKeepaliveParams returns a DialOption that specifies keepalive parameters
389 // for the client transport.
390 func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
391 return newFuncDialOption(func(o *dialOptions) {
392 o.copts.KeepaliveParams = kp
396 // WithUnaryInterceptor returns a DialOption that specifies the interceptor for
398 func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
399 return newFuncDialOption(func(o *dialOptions) {
404 // WithStreamInterceptor returns a DialOption that specifies the interceptor for
406 func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
407 return newFuncDialOption(func(o *dialOptions) {
412 // WithAuthority returns a DialOption that specifies the value to be used as the
413 // :authority pseudo-header. This value only works with WithInsecure and has no
414 // effect if TransportCredentials are present.
415 func WithAuthority(a string) DialOption {
416 return newFuncDialOption(func(o *dialOptions) {
421 // WithChannelzParentID returns a DialOption that specifies the channelz ID of
422 // current ClientConn's parent. This function is used in nested channel creation
423 // (e.g. grpclb dial).
424 func WithChannelzParentID(id int64) DialOption {
425 return newFuncDialOption(func(o *dialOptions) {
426 o.channelzParentID = id
430 // WithDisableServiceConfig returns a DialOption that causes grpc to ignore any
431 // service config provided by the resolver and provides a hint to the resolver
432 // to not fetch service configs.
433 func WithDisableServiceConfig() DialOption {
434 return newFuncDialOption(func(o *dialOptions) {
435 o.disableServiceConfig = true
439 // WithDisableRetry returns a DialOption that disables retries, even if the
440 // service config enables them. This does not impact transparent retries, which
441 // will happen automatically if no data is written to the wire or if the RPC is
442 // unprocessed by the remote server.
444 // Retry support is currently disabled by default, but will be enabled by
445 // default in the future. Until then, it may be enabled by setting the
446 // environment variable "GRPC_GO_RETRY" to "on".
448 // This API is EXPERIMENTAL.
449 func WithDisableRetry() DialOption {
450 return newFuncDialOption(func(o *dialOptions) {
451 o.disableRetry = true
455 // WithMaxHeaderListSize returns a DialOption that specifies the maximum
456 // (uncompressed) size of header list that the client is prepared to accept.
457 func WithMaxHeaderListSize(s uint32) DialOption {
458 return newFuncDialOption(func(o *dialOptions) {
459 o.copts.MaxHeaderListSize = &s
463 // WithDisableHealthCheck disables the LB channel health checking for all SubConns of this ClientConn.
465 // This API is EXPERIMENTAL.
466 func WithDisableHealthCheck() DialOption {
467 return newFuncDialOption(func(o *dialOptions) {
468 o.disableHealthCheck = true
472 // withHealthCheckFunc replaces the default health check function with the provided one. It makes
473 // tests easier to change the health check function.
475 // For testing purpose only.
476 func withHealthCheckFunc(f internal.HealthChecker) DialOption {
477 return newFuncDialOption(func(o *dialOptions) {
478 o.healthCheckFunc = f
482 func defaultDialOptions() dialOptions {
484 disableRetry: !envconfig.Retry,
485 reqHandshake: envconfig.RequireHandshake,
486 healthCheckFunc: internal.HealthCheckFunc,
487 copts: transport.ConnectOptions{
488 WriteBufferSize: defaultWriteBufSize,
489 ReadBufferSize: defaultReadBufSize,