Implement lab 3 level 4 failover and idempotency
This commit is contained in:
+139
@@ -0,0 +1,139 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/repository/redis"
|
||||
"highload/internal/service"
|
||||
httpdeliver "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
cfg, err := config.Load()
|
||||
|
||||
if err != nil {
|
||||
slog.Error("invalid configuration", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
sessionStore := cfg.Session.Store
|
||||
|
||||
if sessionStore != "redis" {
|
||||
slog.Error("session store is "+sessionStore+"must redis", "error", nil)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
databaseURL := cfg.Database.PostgresURL
|
||||
pool, err := database.NewPostgres(context.Background(), databaseURL)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("postgres error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
queries := sqlc.New(pool)
|
||||
|
||||
redisAddr := cfg.Database.RedisAddr
|
||||
|
||||
redisClient, err := database.NewRedis(context.Background(), redisAddr)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("redis error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
defer redisClient.Close()
|
||||
|
||||
instanceID, err := os.Hostname()
|
||||
if err != nil || instanceID == "" {
|
||||
slog.Error("cannot get instance ID", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userRepo := postgres.NewUserRepository(queries)
|
||||
chatRepo := postgres.NewChatRepository(queries, pool)
|
||||
messageRepo := postgres.NewMessageRepository(queries, pool)
|
||||
sessionRepo := redis.NewSessionRepository(redisClient)
|
||||
|
||||
authService := service.NewAuthService(userRepo, sessionRepo, cfg.Session.TTL)
|
||||
userService := service.NewUserService(userRepo)
|
||||
chatService := service.NewChatService(chatRepo, userRepo, userService)
|
||||
messageService := service.NewMessageService(messageRepo, chatService, userService)
|
||||
|
||||
healthHandler := handler.NewHealthHandler(pool, redisClient)
|
||||
authHandler := handler.NewAuthHandler(authService)
|
||||
userHandler := handler.NewUserHandler(userService)
|
||||
chatHandler := handler.NewChatHandler(chatService)
|
||||
messageHandler := handler.NewMessageHandler(messageService)
|
||||
|
||||
mid := middleware.NewMiddleware(authService, instanceID)
|
||||
router := httpdeliver.NewRouter(mid, authHandler, healthHandler, chatHandler, userHandler, messageHandler)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(cfg.HTTP.Host, cfg.HTTP.Port),
|
||||
Handler: router.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
listener, err := net.Listen("tcp", server.Addr)
|
||||
if err != nil {
|
||||
slog.Error("server failed to start", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
slog.Info("server started", "addr", server.Addr)
|
||||
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
err := server.Serve(listener)
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
serverErr <- err
|
||||
slog.Error("server failed", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, stop := signal.NotifyContext(
|
||||
context.Background(),
|
||||
os.Interrupt,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
defer stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
slog.Info("shutdown signal received")
|
||||
|
||||
case err := <-serverErr:
|
||||
slog.Error("server failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
15*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
slog.Error("shutdown failed", "error", err)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/db/migrations"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
func TestConnectionSecretErrorsAreSafe(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
content string
|
||||
missing bool
|
||||
}{
|
||||
{name: "missing", missing: true},
|
||||
{name: "empty", content: " \n\t"},
|
||||
{name: "malformed", content: "postgres://synthetic:fixture-password@localhost/%zz"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "database_url")
|
||||
if !test.missing {
|
||||
if err := os.WriteFile(path, []byte(test.content), 0600); err != nil {
|
||||
t.Fatal("cannot create test secret")
|
||||
}
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
logger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
err := run(context.Background(), "up", time.Second, logger)
|
||||
if err == nil {
|
||||
t.Fatal("invalid connection secret was accepted")
|
||||
}
|
||||
if strings.Contains(err.Error(), "fixture-password") ||
|
||||
strings.Contains(err.Error(), "postgres://") {
|
||||
t.Fatal("migration error exposed a connection secret")
|
||||
}
|
||||
var classified *migrationError
|
||||
if !errors.As(err, &classified) || classified.Unwrap() == nil {
|
||||
t.Fatal("migration error lost its classification/cause")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedMigrationsAreVersionedAndCollectable(t *testing.T) {
|
||||
cfg, err := pgx.ParseConfig("postgres://synthetic@localhost/synthetic?sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatal("cannot configure test driver")
|
||||
}
|
||||
db := stdlib.OpenDB(*cfg)
|
||||
defer db.Close()
|
||||
// NewProvider collects sources without connecting to PostgreSQL.
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.Files)
|
||||
if err != nil {
|
||||
t.Fatal("embedded migration names/versions cannot be collected by Goose")
|
||||
}
|
||||
sources := provider.ListSources()
|
||||
if len(sources) == 0 {
|
||||
t.Fatal("migrator build contains no SQL")
|
||||
}
|
||||
var previous int64
|
||||
for _, source := range sources {
|
||||
if source.Version <= previous {
|
||||
t.Fatal("embedded versions are not unique and increasing")
|
||||
}
|
||||
previous = source.Version
|
||||
data, err := migrations.Files.ReadFile(source.Path)
|
||||
if err != nil || !strings.Contains(string(data), "-- +goose Up") {
|
||||
t.Fatal("embedded migration is unavailable or has no Up section")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type deadlineProbe struct {
|
||||
deadline time.Time
|
||||
cancel error
|
||||
}
|
||||
|
||||
func (*deadlineProbe) SessionLock(context.Context, *sql.Conn) error { return nil }
|
||||
func (p *deadlineProbe) SessionUnlock(ctx context.Context, _ *sql.Conn) error {
|
||||
p.deadline, _ = ctx.Deadline()
|
||||
p.cancel = ctx.Err()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUnlockHasBudgetEvenWithDetachedContext(t *testing.T) {
|
||||
original, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
probe := &deadlineProbe{}
|
||||
locker := boundedSessionLocker{probe}
|
||||
started := time.Now()
|
||||
if err := locker.SessionUnlock(context.WithoutCancel(original), nil); err != nil {
|
||||
t.Fatal("unlock delegation failed")
|
||||
}
|
||||
if probe.cancel != nil || probe.deadline.IsZero() ||
|
||||
probe.deadline.Before(started) || probe.deadline.After(started.Add(6*time.Second)) {
|
||||
t.Fatal("detached cleanup did not receive a bounded, live context")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// These tests need an explicitly supplied disposable PostgreSQL database.
|
||||
// Each test creates and drops only its own randomly named schema.
|
||||
func migrationPostgresFixture(t *testing.T) (*sql.DB, context.Context) {
|
||||
t.Helper()
|
||||
connectionURL := os.Getenv("MIGRATE_TEST_DATABASE_URL")
|
||||
if connectionURL == "" {
|
||||
t.Skip("set MIGRATE_TEST_DATABASE_URL to run PostgreSQL integration tests")
|
||||
}
|
||||
cfg, err := pgx.ParseConfig(connectionURL)
|
||||
if err != nil {
|
||||
t.Fatal("invalid test database configuration")
|
||||
}
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
admin := stdlib.OpenDB(*cfg)
|
||||
t.Cleanup(func() { admin.Close() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
schema := "migration_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
quoted := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.ExecContext(ctx, "CREATE SCHEMA "+quoted); err != nil {
|
||||
t.Fatal("cannot create isolated migration test schema")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := admin.ExecContext(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
|
||||
t.Error("cannot remove isolated migration test schema")
|
||||
}
|
||||
})
|
||||
cfg.RuntimeParams["search_path"] = schema
|
||||
// ConnString retains the original parsed URL; changing RuntimeParams alone
|
||||
// would not pass search_path to the separate migrator connection.
|
||||
scopedURL, err := url.Parse(connectionURL)
|
||||
if err != nil || (scopedURL.Scheme != "postgres" && scopedURL.Scheme != "postgresql") {
|
||||
t.Fatal("MIGRATE_TEST_DATABASE_URL must be a PostgreSQL URL")
|
||||
}
|
||||
query := scopedURL.Query()
|
||||
query.Set("search_path", schema)
|
||||
scopedURL.RawQuery = query.Encode()
|
||||
path := filepath.Join(t.TempDir(), "database_url")
|
||||
if err := os.WriteFile(path, []byte(scopedURL.String()), 0600); err != nil {
|
||||
t.Fatal("cannot write test connection secret")
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
db := stdlib.OpenDB(*cfg)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
return db, ctx
|
||||
}
|
||||
|
||||
func migrationLogRecords(t *testing.T, output *bytes.Buffer) []map[string]any {
|
||||
t.Helper()
|
||||
var records []map[string]any
|
||||
for _, line := range bytes.Split(bytes.TrimSpace(output.Bytes()), []byte("\n")) {
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var record map[string]any
|
||||
if err := json.Unmarshal(line, &record); err != nil {
|
||||
t.Fatal("migrator emitted a non-JSON log record")
|
||||
}
|
||||
for key := range record {
|
||||
switch key {
|
||||
case "time", "level", "msg", "file", "version", "state", "applied", "duration_seconds":
|
||||
default:
|
||||
t.Fatalf("unexpected log field %q; SQL or connection details must not be logged", key)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(line), "CREATE TABLE") || strings.Contains(string(line), "postgres://") {
|
||||
t.Fatal("migration log contains SQL or a connection URL")
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
func completedMigrationCount(t *testing.T, output *bytes.Buffer) int {
|
||||
t.Helper()
|
||||
for _, record := range migrationLogRecords(t, output) {
|
||||
if record["msg"] == "migrations completed" {
|
||||
count, ok := record["applied"].(float64)
|
||||
if !ok {
|
||||
t.Fatal("migration completion log has no numeric applied count")
|
||||
}
|
||||
return int(count)
|
||||
}
|
||||
}
|
||||
t.Fatal("successful migration run has no completion log")
|
||||
return 0
|
||||
}
|
||||
|
||||
func TestPostgresMigrationsRepeatWithoutChangingDataOrLoggingSQL(t *testing.T) {
|
||||
db, ctx := migrationPostgresFixture(t)
|
||||
var output bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&output, nil))
|
||||
if err := run(ctx, "up", time.Minute, logger); err != nil {
|
||||
t.Fatal("migration of empty schema failed")
|
||||
}
|
||||
if count := completedMigrationCount(t, &output); count != 4 {
|
||||
t.Fatalf("empty schema: applied %d migrations, want 4", count)
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, "INSERT INTO users (username, display_name, password_hash) VALUES ($1, $2, $3)",
|
||||
"migration_fixture", "Migration fixture", "synthetic-test-only-hash"); err != nil {
|
||||
t.Fatal("cannot insert persistent migration fixture")
|
||||
}
|
||||
output.Reset()
|
||||
if err := run(ctx, "up", time.Minute, logger); err != nil {
|
||||
t.Fatal("repeat migration failed")
|
||||
}
|
||||
if count := completedMigrationCount(t, &output); count != 0 {
|
||||
t.Fatalf("repeat run: applied %d migrations, want 0", count)
|
||||
}
|
||||
var users, versions int
|
||||
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM users WHERE username = $1", "migration_fixture").Scan(&users); err != nil || users != 1 {
|
||||
t.Fatal("repeat migration lost or duplicated existing data")
|
||||
}
|
||||
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM goose_db_version WHERE version_id > 0 AND is_applied").Scan(&versions); err != nil || versions != 4 {
|
||||
t.Fatal("repeat migration changed version history")
|
||||
}
|
||||
output.Reset()
|
||||
if err := run(ctx, "status", time.Minute, logger); err != nil {
|
||||
t.Fatal("migration status failed")
|
||||
}
|
||||
records := migrationLogRecords(t, &output)
|
||||
if len(records) != 4 {
|
||||
t.Fatal("status did not report all four migrations")
|
||||
}
|
||||
for _, record := range records {
|
||||
if record["state"] != "applied" {
|
||||
t.Fatal("status did not report applied migrations")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresConcurrentMigratorsApplyEachVersionOnce(t *testing.T) {
|
||||
db, ctx := migrationPostgresFixture(t)
|
||||
var outputs [2]bytes.Buffer
|
||||
var runErrors [2]error
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := range outputs {
|
||||
workers.Add(1)
|
||||
go func(i int) {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
runErrors[i] = run(ctx, "up", time.Minute, slog.New(slog.NewJSONHandler(&outputs[i], nil)))
|
||||
}(i)
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
var applied int
|
||||
for i, err := range runErrors {
|
||||
if err != nil {
|
||||
t.Fatal("concurrent migration run failed")
|
||||
}
|
||||
applied += completedMigrationCount(t, &outputs[i])
|
||||
}
|
||||
if applied != 4 {
|
||||
t.Fatalf("concurrent runners applied %d migrations in total, want 4", applied)
|
||||
}
|
||||
var versions, distinctVersions int
|
||||
if err := db.QueryRowContext(ctx, "SELECT count(*), count(DISTINCT version_id) FROM goose_db_version WHERE version_id > 0 AND is_applied").Scan(&versions, &distinctVersions); err != nil || versions != 4 || distinctVersions != 4 {
|
||||
t.Fatal("concurrent runners duplicated or lost version history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresMigrationFailureRollsBackAndPreservesCause(t *testing.T) {
|
||||
db, ctx := migrationPostgresFixture(t)
|
||||
// The first migration creates users, then conflicts with this chats table.
|
||||
if _, err := db.ExecContext(ctx, "CREATE TABLE chats (marker text)"); err != nil {
|
||||
t.Fatal("cannot create conflicting test table")
|
||||
}
|
||||
var output bytes.Buffer
|
||||
err := run(ctx, "up", time.Minute, slog.New(slog.NewJSONHandler(&output, nil)))
|
||||
var pgErr *pgconn.PgError
|
||||
if err == nil || err.Error() != "apply pending migrations" || !errors.As(err, &pgErr) || pgErr.Code != "42P07" {
|
||||
t.Fatal("migration failure did not retain a safely reportable duplicate-table error")
|
||||
}
|
||||
migrationLogRecords(t, &output)
|
||||
var usersAbsent bool
|
||||
if err := db.QueryRowContext(ctx, "SELECT to_regclass('users') IS NULL").Scan(&usersAbsent); err != nil || !usersAbsent {
|
||||
t.Fatal("failed migration left a partially applied users table")
|
||||
}
|
||||
var versions int
|
||||
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM goose_db_version WHERE version_id > 0 AND is_applied").Scan(&versions); err != nil || versions != 0 {
|
||||
t.Fatal("failed migration was recorded as applied")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
"highload/db/migrations"
|
||||
)
|
||||
|
||||
func sessionSchema(t *testing.T, db *sql.DB, ctx context.Context) []string {
|
||||
t.Helper()
|
||||
rows, err := db.QueryContext(ctx, `
|
||||
SELECT 'column:'||attname||':'||format_type(atttypid,atttypmod)||':'||attnotnull||':'||
|
||||
COALESCE(pg_get_expr(d.adbin,d.adrelid),'')
|
||||
FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum
|
||||
WHERE a.attrelid='sessions'::regclass AND a.attnum>0 AND NOT a.attisdropped
|
||||
UNION ALL SELECT 'constraint:'||conname||':'||pg_get_constraintdef(oid)
|
||||
FROM pg_constraint WHERE conrelid='sessions'::regclass
|
||||
UNION ALL SELECT 'index:'||indexname||':'||indexdef
|
||||
FROM pg_indexes WHERE schemaname=current_schema() AND tablename='sessions'
|
||||
ORDER BY 1`)
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect restored session columns/defaults/constraints/indexes")
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []string
|
||||
for rows.Next() {
|
||||
var s string
|
||||
if rows.Scan(&s) != nil {
|
||||
t.Fatal("schema scan failed")
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
if rows.Err() != nil || len(result) < 10 {
|
||||
t.Fatal("incomplete session structure snapshot")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func businessData(t *testing.T, db *sql.DB, ctx context.Context) []string {
|
||||
t.Helper()
|
||||
result := []string{}
|
||||
for _, table := range []string{"users", "chats", "chat_members", "messages"} {
|
||||
rows, err := db.QueryContext(ctx, "SELECT row_to_json(t)::text FROM "+table+" t ORDER BY row_to_json(t)::text")
|
||||
if err != nil {
|
||||
t.Fatal("business table disappeared during migration")
|
||||
}
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if rows.Scan(&value) != nil {
|
||||
t.Fatal("data scan failed")
|
||||
}
|
||||
result = append(result, table+value)
|
||||
count++
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil || count == 0 {
|
||||
t.Fatal("business fixture missing during migration")
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func equalStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func TestPostgresMigrationThreeDownTwoDownOneAndReapply(t *testing.T) {
|
||||
db, ctx := migrationPostgresFixture(t)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.Files,
|
||||
goose.WithDisableGlobalRegistry(true), goose.WithSlog(slog.New(slog.NewTextHandler(io.Discard, nil))))
|
||||
if err != nil {
|
||||
t.Fatal("cannot load actual embedded migrations")
|
||||
}
|
||||
if _, err = provider.UpTo(ctx, 1); err != nil {
|
||||
t.Fatal("cannot apply version 1")
|
||||
}
|
||||
v1 := sessionSchema(t, db, ctx)
|
||||
if _, err = db.ExecContext(ctx, `
|
||||
INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES
|
||||
('00000000-0000-4000-8000-000000000001','roundtrip_user','Roundtrip','synthetic-hash','2026-01-01T00:00:00Z');
|
||||
INSERT INTO chats(id,title,created_at) VALUES
|
||||
('00000000-0000-4000-8000-000000000002','Roundtrip','2026-01-01T00:00:00Z');
|
||||
INSERT INTO chat_members VALUES('00000000-0000-4000-8000-000000000002','00000000-0000-4000-8000-000000000001');
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES
|
||||
('00000000-0000-4000-8000-000000000003','00000000-0000-4000-8000-000000000002','00000000-0000-4000-8000-000000000001','Keep this message','2026-01-01T00:00:00Z');
|
||||
INSERT INTO sessions VALUES(decode(repeat('ab',32),'hex'),'00000000-0000-4000-8000-000000000001','2026-01-01T00:00:00Z','2026-01-02T00:00:00Z',NULL);
|
||||
`); err != nil {
|
||||
t.Fatal("cannot create migration preservation fixtures")
|
||||
}
|
||||
original := businessData(t, db, ctx)
|
||||
if _, err = provider.UpTo(ctx, 2); err != nil {
|
||||
t.Fatal("cannot apply version 2")
|
||||
}
|
||||
v2 := sessionSchema(t, db, ctx)
|
||||
assertVersion := func(want int64) {
|
||||
t.Helper()
|
||||
got, e := provider.GetDBVersion(ctx)
|
||||
if e != nil || got != want {
|
||||
t.Fatalf("want migration version %d, got %d", want, got)
|
||||
}
|
||||
if !equalStrings(original, businessData(t, db, ctx)) {
|
||||
t.Fatal("migration changed unrelated users/chats/members/messages")
|
||||
}
|
||||
}
|
||||
assertAbsent := func() {
|
||||
t.Helper()
|
||||
var absent bool
|
||||
if db.QueryRowContext(ctx, "SELECT to_regclass('sessions') IS NULL").Scan(&absent) != nil || !absent {
|
||||
t.Fatal("version 3 must remove SQL sessions")
|
||||
}
|
||||
}
|
||||
if _, err = provider.Up(ctx); err != nil {
|
||||
t.Fatal("cannot migrate to 4")
|
||||
}
|
||||
assertVersion(4)
|
||||
assertAbsent()
|
||||
if _, err = provider.DownTo(ctx, 2); err != nil {
|
||||
t.Fatal("3 -> 2 failed")
|
||||
}
|
||||
assertVersion(2)
|
||||
if !equalStrings(v2, sessionSchema(t, db, ctx)) {
|
||||
t.Fatal("3 -> 2 did not restore exact version-2 session columns, defaults, keys, FK, CHECK and indexes")
|
||||
}
|
||||
var count int
|
||||
if db.QueryRowContext(ctx, "SELECT count(*) FROM sessions").Scan(&count) != nil || count != 0 {
|
||||
t.Fatal("rollback must restore an empty sessions table; deleted credentials cannot be resurrected")
|
||||
}
|
||||
if _, err = db.ExecContext(ctx, `INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(decode(repeat('cd',32),'hex'),'00000000-0000-4000-8000-000000000001',now()+interval '1 hour')`); err != nil {
|
||||
t.Fatal("restored table/default/FK cannot accept a valid session")
|
||||
}
|
||||
for _, statement := range []string{
|
||||
`INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(decode(repeat('ef',32),'hex'),'00000000-0000-4000-8000-000000000099',now()+interval '1 hour')`,
|
||||
`INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(decode(repeat('ef',32),'hex'),'00000000-0000-4000-8000-000000000001',now()-interval '1 hour')`,
|
||||
`INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(decode(repeat('cd',32),'hex'),'00000000-0000-4000-8000-000000000001',now()+interval '1 hour')`,
|
||||
} {
|
||||
if _, err = db.ExecContext(ctx, statement); err == nil {
|
||||
t.Fatal("restored table lost FK, expiry CHECK or primary key")
|
||||
}
|
||||
}
|
||||
if _, err = provider.DownTo(ctx, 1); err != nil {
|
||||
t.Fatal("2 -> 1 failed")
|
||||
}
|
||||
assertVersion(1)
|
||||
if !equalStrings(v1, sessionSchema(t, db, ctx)) {
|
||||
t.Fatal("2 -> 1 did not restore original sessions structure without created_at default")
|
||||
}
|
||||
if _, err = provider.UpTo(ctx, 4); err != nil {
|
||||
t.Fatal("1 -> 4 reapplication failed")
|
||||
}
|
||||
assertVersion(4)
|
||||
assertAbsent()
|
||||
}
|
||||
Reference in New Issue
Block a user