fix: Minstrel waits for its database at startup instead of exiting
release / web (push) Successful in 1m12s
release / go (push) Failing after 1m12s
release / govulncheck (push) Successful in 16s
release / integration (push) Successful in 3m49s
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 5m54s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
release / web (push) Successful in 1m12s
release / go (push) Failing after 1m12s
release / govulncheck (push) Successful in 16s
release / integration (push) Successful in 3m49s
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 5m54s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
A first docker compose up starts Minstrel and a new Postgres together, and the database spends several seconds initialising before it takes connections. Minstrel tried once and exited, and with no restart policy in the quick-start compose it stayed down. It now retries every two seconds for up to two minutes, logging each attempt, and only then exits with the last connection error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -142,6 +142,9 @@ func run() error {
|
|||||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
|
if err := db.WaitReady(ctx, cfg.Database.URL, logger); err != nil {
|
||||||
|
return fmt.Errorf("database: %w", err)
|
||||||
|
}
|
||||||
if err := db.Migrate(cfg.Database.URL, logger); err != nil {
|
if err := db.Migrate(cfg.Database.URL, logger); err != nil {
|
||||||
return fmt.Errorf("migrate: %w", err)
|
return fmt.Errorf("migrate: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
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 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):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var quietLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
|
|
||||||
|
func TestWaitFor_RetriesUntilTheDatabaseAnswers(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
err := waitFor(context.Background(), quietLogger, time.Millisecond, time.Second, func(context.Context) error {
|
||||||
|
calls++
|
||||||
|
if calls < 3 {
|
||||||
|
return errors.New("connection refused")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("waitFor = %v, want nil once the third attempt connects", err)
|
||||||
|
}
|
||||||
|
if calls != 3 {
|
||||||
|
t.Errorf("attempts = %d, want 3 (two refusals, then success)", calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWaitFor_GivesUpWithTheLastError(t *testing.T) {
|
||||||
|
refused := errors.New("password authentication failed")
|
||||||
|
err := waitFor(context.Background(), quietLogger, time.Millisecond, 20*time.Millisecond, func(context.Context) error {
|
||||||
|
return refused
|
||||||
|
})
|
||||||
|
if !errors.Is(err, refused) {
|
||||||
|
t.Fatalf("waitFor = %v, want it to carry the last connection error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWaitFor_StopsWhenShutdownBegins(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
start := time.Now()
|
||||||
|
err := waitFor(ctx, quietLogger, time.Hour, time.Hour, func(context.Context) error {
|
||||||
|
return errors.New("connection refused")
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("waitFor = %v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
if time.Since(start) > time.Second {
|
||||||
|
t.Errorf("waitFor took %s after cancel, want an immediate return", time.Since(start))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWaitReady_EmptyURLIsAnErrorNotAWait(t *testing.T) {
|
||||||
|
if err := WaitReady(context.Background(), "", quietLogger); err == nil {
|
||||||
|
t.Fatal("WaitReady(\"\") = nil, want an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user