fix: standardize startup database retries
This commit is contained in:
1 parent
668e9dd310
commit
d9e2d64535
6 files changed
+230
-44
No files matched your search
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -28,6 +29,87 @@ type Config struct {
|
||||
ConnectTimeout time.Duration
|
||||
}
|
||||
|
||||
// StartupRetryOptions controls retries while a service is waiting for
|
||||
// PostgreSQL to become reachable during startup.
|
||||
type StartupRetryOptions struct {
|
||||
Interval time.Duration
|
||||
MaxAttempts int64
|
||||
}
|
||||
|
||||
const (
|
||||
defaultStartupRetryInterval = 5 * time.Second
|
||||
defaultStartupRetryAttempts = 0 // 0 = retry indefinitely
|
||||
minimumStartupRetryInterval = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
// StartupRetryOptionsFromEnv loads the common startup retry policy. The
|
||||
// database has to be reachable before settings stored in it can be read, so
|
||||
// these options intentionally come from the environment.
|
||||
func StartupRetryOptionsFromEnv() StartupRetryOptions {
|
||||
intervalMs := config.Int("DB_INIT_RETRY_INTERVAL_MS", int(defaultStartupRetryInterval/time.Millisecond))
|
||||
if intervalMs < int(minimumStartupRetryInterval/time.Millisecond) {
|
||||
intervalMs = int(minimumStartupRetryInterval / time.Millisecond)
|
||||
}
|
||||
|
||||
maxAttempts := int64(config.Int("DB_INIT_RETRY_MAX_ATTEMPTS", defaultStartupRetryAttempts))
|
||||
if maxAttempts < 0 {
|
||||
maxAttempts = defaultStartupRetryAttempts
|
||||
}
|
||||
|
||||
return StartupRetryOptions{
|
||||
Interval: time.Duration(intervalMs) * time.Millisecond,
|
||||
MaxAttempts: maxAttempts,
|
||||
}
|
||||
}
|
||||
|
||||
// RetryStartup reruns fn until it succeeds, the configured attempt limit is
|
||||
// reached, or ctx is canceled.
|
||||
func RetryStartup(ctx context.Context, fn func() error) error {
|
||||
return RetryStartupWithOptions(ctx, StartupRetryOptionsFromEnv(), fn)
|
||||
}
|
||||
|
||||
// RetryStartupWithOptions is the configurable form of RetryStartup, useful
|
||||
// when a caller has already loaded the startup options.
|
||||
func RetryStartupWithOptions(ctx context.Context, options StartupRetryOptions, fn func() error) error {
|
||||
if fn == nil {
|
||||
return errors.New("startup retry callback is nil")
|
||||
}
|
||||
if options.Interval < minimumStartupRetryInterval {
|
||||
options.Interval = minimumStartupRetryInterval
|
||||
}
|
||||
if options.MaxAttempts < 0 {
|
||||
options.MaxAttempts = defaultStartupRetryAttempts
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := fn(); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
|
||||
if options.MaxAttempts > 0 && attempt >= options.MaxAttempts {
|
||||
return lastErr
|
||||
}
|
||||
|
||||
log.Printf("[postgres] startup attempt %d failed: %v; retrying in %s", attempt, lastErr, options.Interval)
|
||||
timer := time.NewTimer(options.Interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !timer.Stop() {
|
||||
<-timer.C
|
||||
}
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultConfig returns sensible defaults for a small self-hosted service.
|
||||
func DefaultConfig(url string) Config {
|
||||
return Config{
|
||||
@@ -111,6 +193,25 @@ func Open(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// OpenWithRetry opens and verifies a PostgreSQL pool using the common startup
|
||||
// retry policy.
|
||||
func OpenWithRetry(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
var pool *pgxpool.Pool
|
||||
err := RetryStartup(ctx, func() error {
|
||||
if pool != nil {
|
||||
pool.Close()
|
||||
pool = nil
|
||||
}
|
||||
var err error
|
||||
pool, err = Open(ctx, cfg)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// WithTx runs fn in a transaction and rolls back on all error paths.
|
||||
func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
|
||||
if pool == nil {
|
||||
|
||||
Reference in new issue
Block a user