The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
3 changed files with 133 additions and 0 deletions
Showing only changes of commit 040b90898b - Show all commits
+3
View File
@@ -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)
}
+70
View File
@@ -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):
}
}
}
+60
View File
@@ -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")
}
}