package db import ( "context" "errors" "fmt" "log/slog" "time" "github.com/jackc/pgx/v5" ) // A database started alongside Minstrel (one compose file, one stack) is // often still initialising when Minstrel starts, and a first start of the // official Postgres image takes several seconds before it accepts // connections. Minstrel waits for it rather than exiting, so no healthcheck // or restart policy is needed to bring the pair up. Two minutes covers a slow // first initialisation; past that the address or credentials are wrong and // the last error says which. const ( readyEvery = 2 * time.Second readyLimit = 2 * time.Minute readyAttemptTimeout = 5 * time.Second ) // WaitReady blocks until the database at dsn accepts a connection, retrying // while it is unreachable and logging each failed attempt. It returns the last // connection error once readyLimit has passed, or ctx's error if ctx ends // first. func WaitReady(ctx context.Context, dsn string, logger *slog.Logger) error { if dsn == "" { return errors.New("db: database URL is empty") } return waitFor(ctx, logger, readyEvery, readyLimit, func(ctx context.Context) error { actx, cancel := context.WithTimeout(ctx, readyAttemptTimeout) defer cancel() conn, err := pgx.Connect(actx, dsn) if err != nil { return err } defer func() { _ = conn.Close(context.WithoutCancel(ctx)) }() return conn.Ping(actx) }) } // waitFor calls try until it succeeds, every `every`, for at most `limit`. func waitFor(ctx context.Context, logger *slog.Logger, every, limit time.Duration, try func(context.Context) error) error { deadline := time.Now().Add(limit) for attempt := 1; ; attempt++ { err := try(ctx) if err == nil { if attempt > 1 { logger.Info("database is ready", "attempts", attempt) } return nil } if ctx.Err() != nil { return ctx.Err() } if !time.Now().Add(every).Before(deadline) { return fmt.Errorf("db: not reachable after %s: %w", limit, err) } logger.Info("waiting for the database", "attempt", attempt, "err", err) select { case <-ctx.Done(): return ctx.Err() case <-time.After(every): } } }