From f47f0cf823320f1022d7dde8a799052393355bcd Mon Sep 17 00:00:00 2001 From: smaher-edb Date: Thu, 13 Jul 2023 16:08:22 +0530 Subject: [PATCH] connect_timeout is not obeyed for sslmode=allow|prefer connect_timeout given in conn string was not obeyed if sslmode is not specified (default is prefer) or equals sslmode=allow|prefer. It took twice the amount of time specified by connect_timeout in conn string. While this behavior is correct if multi-host is provided in conn string, it doesn't look correct in case of single host. This behavior was also not matching with libpq. The root cause was to implement sslmode=allow|prefer conn are tried twice. First with TLSConfig and if that doesn't work then without TLSConfig. The fix for this issue now uses the same context if same host is being tried out. This change won't affect the existing multi-host behavior. This PR goal is to close issue [jackc/pgx/issues/1672](https://github.com/jackc/pgx/issues/1672) --- pgconn/pgconn.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pgconn/pgconn.go b/pgconn/pgconn.go index 12357751..49ff0118 100644 --- a/pgconn/pgconn.go +++ b/pgconn/pgconn.go @@ -154,12 +154,15 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er foundBestServer := false var fallbackConfig *FallbackConfig - for _, fc := range fallbackConfigs { + for i, fc := range fallbackConfigs { // ConnectTimeout restricts the whole connection process. if config.ConnectTimeout != 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(octx, config.ConnectTimeout) - defer cancel() + // create new context first time or when previous host was different + if i == 0 || (fallbackConfigs[i].Host != fallbackConfigs[i-1].Host) { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(octx, config.ConnectTimeout) + defer cancel() + } } else { ctx = octx }