From 040b90898bc6b6a135357f96d9710b756c6c0406 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 25 Nov 2026 09:46:19 -0500 Subject: [PATCH] fix: Minstrel waits for its database at startup instead of exiting 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 --- cmd/minstrel/main.go | 3 ++ internal/db/wait.go | 70 ++++++++++++++++++++++++++++++++++++++++ internal/db/wait_test.go | 60 ++++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 internal/db/wait.go create mode 100644 internal/db/wait_test.go diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index cbd6c607..fe0d11aa 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -142,6 +142,9 @@ func run() error { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) 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 { return fmt.Errorf("migrate: %w", err) } diff --git a/internal/db/wait.go b/internal/db/wait.go new file mode 100644 index 00000000..19d45590 --- /dev/null +++ b/internal/db/wait.go @@ -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): + } + } +} diff --git a/internal/db/wait_test.go b/internal/db/wait_test.go new file mode 100644 index 00000000..1fa3bd53 --- /dev/null +++ b/internal/db/wait_test.go @@ -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") + } +}