forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"flag"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"highload/db/migrations"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
)
|
||||
|
||||
// Migration errors retain their cause for classification, but deliberately do
|
||||
// not print connection strings, PostgreSQL DETAIL fields or raw SQL.
|
||||
type migrationError struct {
|
||||
stage string
|
||||
cause error
|
||||
}
|
||||
|
||||
func (e *migrationError) Error() string { return e.stage }
|
||||
func (e *migrationError) Unwrap() error { return e.cause }
|
||||
|
||||
type boundedSessionLocker struct {
|
||||
lock.SessionLocker
|
||||
}
|
||||
|
||||
func (l boundedSessionLocker) SessionUnlock(ctx context.Context, conn *sql.Conn) error {
|
||||
// Goose unlocks with a detached context; bound this cleanup separately.
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
return l.SessionLocker.SessionUnlock(ctx, conn)
|
||||
}
|
||||
|
||||
func main() {
|
||||
command := flag.String("command", "up", "migration action: up or status")
|
||||
timeout := flag.Duration("timeout", 2*time.Minute, "total migration/connection/lock budget")
|
||||
flag.Parse()
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
if flag.NArg() != 0 || (*command != "up" && *command != "status") || *timeout < time.Second {
|
||||
logger.Error("invalid migration arguments", "allowed_commands", "up,status",
|
||||
"minimum_timeout", "1s")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
signalCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
ctx, cancel := context.WithTimeout(signalCtx, *timeout)
|
||||
defer cancel()
|
||||
if err := run(ctx, *command, *timeout, logger); err != nil {
|
||||
fields := []any{"stage", err.Error(), "timeout", errors.Is(err, context.DeadlineExceeded),
|
||||
"cancelled", errors.Is(err, context.Canceled)}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
fields = append(fields, "sqlstate", pgErr.Code)
|
||||
}
|
||||
var partial *goose.PartialError
|
||||
if errors.As(err, &partial) && partial.Failed != nil && partial.Failed.Source != nil {
|
||||
fields = append(fields, "migration", partial.Failed.Source.Path,
|
||||
"version", partial.Failed.Source.Version)
|
||||
}
|
||||
logger.Error("migration failed", fields...)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context, command string, timeout time.Duration, logger *slog.Logger) error {
|
||||
fail := func(stage string, err error) error {
|
||||
return &migrationError{stage: stage, cause: err}
|
||||
}
|
||||
path := os.Getenv("DATABASE_URL_FILE")
|
||||
if path == "" {
|
||||
path = "/run/secrets/database_url"
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fail("read database secret file", err)
|
||||
}
|
||||
url := strings.TrimSpace(string(data))
|
||||
if url == "" {
|
||||
return fail("database secret file is empty", errors.New("empty database URL"))
|
||||
}
|
||||
cfg, err := pgx.ParseConfig(url)
|
||||
if err != nil {
|
||||
return fail("parse database secret", err)
|
||||
}
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
cfg.RuntimeParams["application_name"] = "highload-migrate"
|
||||
cfg.RuntimeParams["lock_timeout"] = "10000"
|
||||
cfg.RuntimeParams["statement_timeout"] = strconv.FormatInt(min(timeout.Milliseconds(), 2147483647), 10)
|
||||
db := stdlib.OpenDB(*cfg)
|
||||
db.SetMaxOpenConns(2)
|
||||
db.SetMaxIdleConns(2)
|
||||
db.SetConnMaxLifetime(5 * time.Minute)
|
||||
defer db.Close()
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
return fail("connect to PostgreSQL", err)
|
||||
}
|
||||
|
||||
locker, err := lock.NewPostgresSessionLocker(
|
||||
lock.WithLockTimeout(1, 120),
|
||||
lock.WithUnlockTimeout(1, 5),
|
||||
)
|
||||
if err != nil {
|
||||
return fail("configure migration lock", err)
|
||||
}
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.Files,
|
||||
goose.WithSessionLocker(boundedSessionLocker{locker}),
|
||||
goose.WithDisableGlobalRegistry(true),
|
||||
goose.WithSlog(logger),
|
||||
// Goose verbose logging includes SQL statements. Log only selected
|
||||
// migration metadata ourselves, even when a migration fails.
|
||||
goose.WithVerbose(false),
|
||||
)
|
||||
if err != nil {
|
||||
return fail("load embedded migrations", err)
|
||||
}
|
||||
if command == "status" {
|
||||
statuses, err := provider.Status(ctx)
|
||||
if err != nil {
|
||||
return fail("read migration status", err)
|
||||
}
|
||||
for _, status := range statuses {
|
||||
logger.Info("migration status", "file", status.Source.Path,
|
||||
"version", status.Source.Version, "state", status.State)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
started := time.Now()
|
||||
results, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return fail("apply pending migrations", err)
|
||||
}
|
||||
for _, result := range results {
|
||||
logger.Info("migration applied", "file", result.Source.Path,
|
||||
"version", result.Source.Version, "duration_seconds", result.Duration.Seconds())
|
||||
}
|
||||
logger.Info("migrations completed", "applied", len(results),
|
||||
"duration_seconds", time.Since(started).Seconds())
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user