5
5
"fmt"
6
6
"os"
7
7
"strings"
8
+ "time"
8
9
10
+ "github.com/cenkalti/backoff/v4"
9
11
"github.com/go-errors/errors"
10
12
"github.com/jackc/pgconn"
11
13
"github.com/jackc/pgx/v4"
@@ -26,19 +28,31 @@ func Connect(ctx context.Context, connString string, options ...func(*pgx.ConnCo
26
28
config .OnNotice = func (pc * pgconn.PgConn , n * pgconn.Notice ) {
27
29
fmt .Fprintf (os .Stderr , "%s (%s): %s\n " , n .Severity , n .Code , n .Message )
28
30
}
31
+ maxRetries := uint64 (0 )
29
32
if strings .HasPrefix (config .User , CLI_LOGIN_ROLE ) {
30
33
config .AfterConnect = func (ctx context.Context , pgconn * pgconn.PgConn ) error {
31
34
return pgconn .Exec (ctx , SET_SESSION_ROLE ).Close ()
32
35
}
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
+ }
33
40
}
34
41
// Apply config overrides
35
42
for _ , op := range options {
36
43
op (config )
37
44
}
38
45
// 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
42
52
}
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 )
44
58
}
0 commit comments