From 03ac6bedb475645b51b0fc44106f71ae2ed8ec0d Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Mon, 23 Nov 2020 14:04:33 +0300 Subject: [PATCH] [#205] v2/client: Replace WithGRPCDialContext option with WithDialTimeout There is a need to set dial timeout in v2 client that is used in case of internal connection opening. Add DialTimeout option constructor to support this feature. Remove unused and no longer needed WithGRPCDialContext function. Signed-off-by: Leonard Lyubich --- v2/client/options.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/v2/client/options.go b/v2/client/options.go index 3dcdff1..1c9e60a 100644 --- a/v2/client/options.go +++ b/v2/client/options.go @@ -3,6 +3,7 @@ package client import ( "context" "net" + "time" "google.golang.org/grpc" ) @@ -15,24 +16,26 @@ type cfg struct { conn net.Conn gRPC cfgGRPC + + dialTimeout time.Duration } type cfgGRPC struct { - dialCtx context.Context - dialOpts []grpc.DialOption conn *grpc.ClientConn } +const defaultDialTimeout = 5 * time.Second + func defaultCfg() *cfg { return &cfg{ gRPC: cfgGRPC{ - dialCtx: context.Background(), dialOpts: []grpc.DialOption{ grpc.WithInsecure(), }, }, + dialTimeout: defaultDialTimeout, } } @@ -58,7 +61,11 @@ func NewGRPCClientConn(opts ...Option) (*grpc.ClientConn, error) { ) } - cfg.gRPC.conn, err = grpc.DialContext(cfg.gRPC.dialCtx, cfg.addr, cfg.gRPC.dialOpts...) + dialCtx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout) + + cfg.gRPC.conn, err = grpc.DialContext(dialCtx, cfg.addr, cfg.gRPC.dialOpts...) + + cancel() if err != nil { return nil, err } @@ -83,10 +90,10 @@ func WithNetConn(v net.Conn) Option { } } -func WithGRPCDialContext(v context.Context) Option { +func WithDialTimeout(v time.Duration) Option { return func(c *cfg) { - if v != nil { - c.gRPC.dialCtx = v + if v > 0 { + c.dialTimeout = v } } }