Skip to content

Commit 2b6e22b

Browse files
authored
fix: retry pooler connection after password change (#3949)
1 parent a1ce2e7 commit 2b6e22b

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

pkg/pgxv5/connect.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ import (
55
"fmt"
66
"os"
77
"strings"
8+
"time"
89

10+
"github.com/cenkalti/backoff/v4"
911
"github.com/go-errors/errors"
1012
"github.com/jackc/pgconn"
1113
"github.com/jackc/pgx/v4"
@@ -26,19 +28,31 @@ func Connect(ctx context.Context, connString string, options ...func(*pgx.ConnCo
2628
config.OnNotice = func(pc *pgconn.PgConn, n *pgconn.Notice) {
2729
fmt.Fprintf(os.Stderr, "%s (%s): %s\n", n.Severity, n.Code, n.Message)
2830
}
31+
maxRetries := uint64(0)
2932
if strings.HasPrefix(config.User, CLI_LOGIN_ROLE) {
3033
config.AfterConnect = func(ctx context.Context, pgconn *pgconn.PgConn) error {
3134
return pgconn.Exec(ctx, SET_SESSION_ROLE).Close()
3235
}
36+
// Add retry to allow enough time for password change to propagate to pooler
37+
if len(config.User) > len(CLI_LOGIN_ROLE) {
38+
maxRetries = 3
39+
}
3340
}
3441
// Apply config overrides
3542
for _, op := range options {
3643
op(config)
3744
}
3845
// Connect to database
39-
conn, err := pgx.ConnectConfig(ctx, config)
40-
if err != nil {
41-
return nil, errors.Errorf("failed to connect to postgres: %w", err)
46+
connect := func() (*pgx.Conn, error) {
47+
conn, err := pgx.ConnectConfig(ctx, config)
48+
if err != nil {
49+
return nil, errors.Errorf("failed to connect to postgres: %w", err)
50+
}
51+
return conn, nil
4252
}
43-
return conn, nil
53+
policy := backoff.WithContext(backoff.WithMaxRetries(backoff.NewExponentialBackOff(
54+
backoff.WithInitialInterval(3*time.Second)),
55+
maxRetries),
56+
ctx)
57+
return backoff.RetryWithData(connect, policy)
4458
}

0 commit comments

Comments
 (0)