ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
+155
@@ -0,0 +1,155 @@
|
||||
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"
|
||||
"highload/internal/storage/s3"
|
||||
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()
|
||||
if os.Getenv("PG_POOL_DIAGNOSTICS") == "1" {
|
||||
diagnosticsCtx, stopDiagnostics := context.WithCancel(context.Background())
|
||||
defer stopDiagnostics()
|
||||
go logPoolStats(diagnosticsCtx, pool)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
s3Storage, err := s3.NewStorage(context.Background(), &cfg.S3)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("cannot create new storage", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userRepo := postgres.NewUserRepository(queries)
|
||||
chatRepo := postgres.NewChatRepository(queries, pool)
|
||||
messageRepo := postgres.NewMessageRepository(queries, pool)
|
||||
sessionRepo := redis.NewSessionRepository(redisClient)
|
||||
attachmentRepo := postgres.NewAttachmentRepository(queries, pool, int32(cfg.JobMaxAttempts))
|
||||
|
||||
authService := service.NewAuthService(userRepo, sessionRepo, cfg.Session.TTL)
|
||||
userService := service.NewUserService(userRepo)
|
||||
chatService := service.NewChatService(chatRepo, userRepo, userService)
|
||||
messageService := service.NewMessageService(messageRepo, chatService, userService)
|
||||
attachmentService := service.NewAttachmentService(attachmentRepo, chatService, s3Storage)
|
||||
|
||||
healthHandler := handler.NewHealthHandler(pool, redisClient, s3Storage)
|
||||
authHandler := handler.NewAuthHandler(authService)
|
||||
userHandler := handler.NewUserHandler(userService)
|
||||
chatHandler := handler.NewChatHandler(chatService)
|
||||
messageHandler := handler.NewMessageHandler(messageService)
|
||||
attachmentHandler := handler.NewAttachmentHandler(attachmentService)
|
||||
|
||||
mid := middleware.NewMiddleware(authService, instanceID)
|
||||
router := httpdeliver.NewRouter(mid, authHandler, healthHandler, chatHandler, userHandler, messageHandler, attachmentHandler)
|
||||
|
||||
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,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// logPoolStats is opt-in diagnostics for the isolated scaling experiment.
|
||||
// It contains only aggregate counters, never connection strings or SQL values.
|
||||
func logPoolStats(ctx context.Context, pool *pgxpool.Pool) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s := pool.Stat()
|
||||
slog.Info("pg_pool_stats", "max_conns", s.MaxConns(),
|
||||
"acquired", s.AcquiredConns(), "idle", s.IdleConns(),
|
||||
"acquire_count", s.AcquireCount(), "empty_count", s.EmptyAcquireCount(),
|
||||
"empty_wait_ns", s.EmptyAcquireWaitTime().Nanoseconds(),
|
||||
"canceled_count", s.CanceledAcquireCount())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage/s3"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type cleanupConfig struct {
|
||||
once bool
|
||||
dryRun bool
|
||||
gracePeriod time.Duration
|
||||
interval time.Duration
|
||||
passTimeout time.Duration
|
||||
reconcile bool
|
||||
restoreID string
|
||||
backupFile string
|
||||
}
|
||||
|
||||
func main() {
|
||||
var cfg cleanupConfig
|
||||
|
||||
flag.BoolVar(&cfg.once, "once", false, "Run once and exit")
|
||||
flag.BoolVar(&cfg.dryRun, "dry-run", true, "Do not actually delete files")
|
||||
flag.DurationVar(&cfg.gracePeriod, "grace-period", 10*time.Minute, "Grace period for old files")
|
||||
flag.DurationVar(&cfg.interval, "interval", 5*time.Minute, "Interval between runs")
|
||||
flag.DurationVar(&cfg.passTimeout, "pass-timeout", 2*time.Minute, "Timeout for a single pass")
|
||||
flag.BoolVar(&cfg.reconcile, "reconcile", false, "Scan both stores once and print JSON observations")
|
||||
flag.StringVar(&cfg.restoreID, "restore-id", "", "Restore the missing original for this attachment ID")
|
||||
flag.StringVar(&cfg.backupFile, "backup-file", "", "Path to the original backup used for restore")
|
||||
flag.Parse()
|
||||
|
||||
if cfg.gracePeriod <= 0 || cfg.interval <= 0 || cfg.passTimeout <= 0 {
|
||||
slog.Error("all duration flags must be positive")
|
||||
os.Exit(1)
|
||||
}
|
||||
if (cfg.restoreID == "") != (cfg.backupFile == "") || (cfg.reconcile && cfg.restoreID != "") {
|
||||
slog.Error("use -reconcile alone, or supply both -restore-id and -backup-file")
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := run(cfg); err != nil {
|
||||
slog.Error("attachment cleanup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg cleanupConfig) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
databaseURL, s3Config, err := config.LoadAttachmentCleanup()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load cleanup configuration: %w", err)
|
||||
}
|
||||
|
||||
startupCtx, cancelStartup := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancelStartup()
|
||||
|
||||
pool, err := database.NewPostgres(startupCtx, databaseURL)
|
||||
if err != nil {
|
||||
var configErr *pgconn.ParseConfigError
|
||||
if errors.As(err, &configErr) {
|
||||
return errors.New("invalid PostgreSQL connection string")
|
||||
}
|
||||
return fmt.Errorf("connect to PostgreSQL: %w", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
s3Storage, err := s3.NewStorage(startupCtx, &s3Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create S3 client: %w", err)
|
||||
}
|
||||
cancelStartup()
|
||||
|
||||
attachmentRepo := postgres.NewAttachmentRepository(sqlc.New(pool), pool)
|
||||
options := &service.AttachmentCleanupOptions{
|
||||
GracePeriod: cfg.gracePeriod,
|
||||
DryRun: cfg.dryRun,
|
||||
ListTimeout: 5 * time.Second,
|
||||
}
|
||||
attachmentCleanupService := service.NewAttachmentCleanupService(attachmentRepo, s3Storage, options)
|
||||
|
||||
if cfg.reconcile || cfg.restoreID != "" {
|
||||
passCtx, cancel := context.WithTimeout(ctx, cfg.passTimeout)
|
||||
defer cancel()
|
||||
reconciler := service.NewAttachmentReconciler(attachmentRepo, s3Storage, *options)
|
||||
start := time.Now()
|
||||
report := struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
Complete bool `json:"complete"`
|
||||
Orphans *service.OrphanReport `json:"orphan_scan,omitempty"`
|
||||
Missing *service.MissingReport `json:"missing_scan,omitempty"`
|
||||
Restore string `json:"restore,omitempty"`
|
||||
}{DryRun: cfg.dryRun}
|
||||
var actionErr error
|
||||
if cfg.reconcile {
|
||||
missing, err := reconciler.ScanMissing(passCtx)
|
||||
report.Missing = &missing
|
||||
actionErr = err
|
||||
if err == nil {
|
||||
orphans, err := attachmentCleanupService.ScanOrphans(passCtx)
|
||||
report.Orphans = &orphans
|
||||
actionErr = err
|
||||
}
|
||||
} else {
|
||||
file, err := os.Open(cfg.backupFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open backup original: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
report.Restore, actionErr = reconciler.Restore(passCtx, cfg.restoreID, file)
|
||||
}
|
||||
report.DurationMS = time.Since(start).Milliseconds()
|
||||
report.Complete = actionErr == nil
|
||||
return errors.Join(actionErr, json.NewEncoder(os.Stdout).Encode(report))
|
||||
}
|
||||
|
||||
runPass := func() error {
|
||||
passCtx, cancelPass := context.WithTimeout(ctx, cfg.passTimeout)
|
||||
defer cancelPass()
|
||||
return attachmentCleanupService.RunOnce(passCtx)
|
||||
}
|
||||
|
||||
if cfg.once {
|
||||
return runPass()
|
||||
}
|
||||
|
||||
if err := runPass(); err != nil && ctx.Err() == nil {
|
||||
slog.Error("attachment cleanup pass failed", "error", err)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(cfg.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
if err := runPass(); err != nil && ctx.Err() == nil {
|
||||
slog.Error("attachment cleanup pass failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/pipeline"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/storage/s3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := run(ctx, os.Args[1:]); err != nil {
|
||||
slog.Error("attachment jobs command failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context, args []string) error {
|
||||
const usage = "usage: jobs failed | replay | upgrade | cleanup"
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
|
||||
job := flags.String("job-id", "", "failed job ID")
|
||||
request := flags.String("request-id", "", "unique operator request UUID")
|
||||
operator := flags.String("operator", "", "operator ID")
|
||||
reason := flags.String("reason", "", "replay reason")
|
||||
extra := flags.Int("extra-attempts", 1, "budget for replay (1–5)")
|
||||
attachment := flags.String("attachment-id", "", "attachment ID to upgrade")
|
||||
version := flags.Int("to-version", 0, "target pipeline version (2)")
|
||||
dry := flags.Bool("dry-run", false, "report eligible objects without deleting")
|
||||
once := flags.Bool("once", false, "execute one cleanup pass")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
command := args[0]
|
||||
if command != "failed" && command != "cleanup" && command != "replay" && command != "upgrade" {
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
if command == "replay" && (*job == "" || *request == "" || strings.TrimSpace(*operator) == "" ||
|
||||
strings.TrimSpace(*reason) == "" || *extra < 1 || *extra > 5) {
|
||||
return fmt.Errorf("replay needs job-id, request-id, operator, reason and 1–5 extra-attempts")
|
||||
}
|
||||
if command == "upgrade" && (*attachment == "" || *version != 2) {
|
||||
return fmt.Errorf("upgrade needs attachment-id and to-version=2")
|
||||
}
|
||||
attemptLimit := 5
|
||||
if command == "upgrade" {
|
||||
var err error
|
||||
attemptLimit, err = config.EnvInt("JOB_MAX_ATTEMPTS", 5, 1, 20)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
url, storageConfig, err := config.LoadAttachmentCleanup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.NewPostgres(ctx, url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("PostgreSQL unavailable")
|
||||
}
|
||||
defer pool.Close()
|
||||
repo := postgres.NewAttachmentRepository(sqlc.New(pool), pool, int32(attemptLimit))
|
||||
if command == "failed" {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
rows, err := repo.ListFailedJobs(dbCtx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type failed struct {
|
||||
JobID string `json:"job_id"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Attempts int32 `json:"attempts"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
result := make([]failed, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
result = append(result, failed{row.ID.String(), row.AttachmentID.String(), row.ErrorCode.String, row.AttemptsStarted, row.UpdatedAt.Time})
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(result)
|
||||
}
|
||||
objects, err := s3.NewStorage(ctx, &storageConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if command == "replay" {
|
||||
changed, err := repo.ReplayFailed(ctx, *job, *request, *operator, *reason, int32(*extra), objects.Head)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(map[string]any{"job_id": *job, "replayed": changed})
|
||||
}
|
||||
if command == "upgrade" {
|
||||
jobID, queued, err := repo.UpgradePipeline(ctx, *attachment, objects.Head)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(map[string]any{
|
||||
"attachment_id": *attachment, "pipeline_version": *version, "job_id": jobID, "queued": queued,
|
||||
})
|
||||
}
|
||||
cfg, err := config.LoadPipeline()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cleanup := pipeline.Cleanup{Repo: repo, Objects: objects, Grace: cfg.CleanupGrace, Retention: cfg.Retention, DryRun: *dry}
|
||||
if *once {
|
||||
count, err := cleanup.RunOnce(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(map[string]any{"objects": count, "dry_run": *dry})
|
||||
}
|
||||
cleanup.Serve(ctx, cfg.CleanupPeriod)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/db/migrations"
|
||||
"highload/internal/database/sqlc"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
func TestAsyncAttachmentsMigrationAndJobTransitions(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(err)
|
||||
}
|
||||
if _, err := provider.UpTo(ctx, 6); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const original = "attachments/step-two-original"
|
||||
_, err = db.ExecContext(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash) VALUES
|
||||
('00000000-0000-4000-8000-000000000001', 'step_two', 'Step two', 'synthetic');
|
||||
INSERT INTO chats (id, title) VALUES ('00000000-0000-4000-8000-000000000002', 'Step two');
|
||||
INSERT INTO chat_members VALUES
|
||||
('00000000-0000-4000-8000-000000000002', '00000000-0000-4000-8000-000000000001');
|
||||
INSERT INTO messages (id, chat_id, sender_id, text) VALUES
|
||||
('00000000-0000-4000-8000-000000000003', '00000000-0000-4000-8000-000000000002',
|
||||
'00000000-0000-4000-8000-000000000001', 'Old message');
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256) VALUES
|
||||
('00000000-0000-4000-8000-000000000004', '00000000-0000-4000-8000-000000000002',
|
||||
'00000000-0000-4000-8000-000000000001', 'old.png', 'attachments/step-two-original',
|
||||
'image/png', 123, repeat('a', 64));
|
||||
INSERT INTO messages_attachments (message_id, attachment_id, chat_id, position) VALUES
|
||||
('00000000-0000-4000-8000-000000000003', '00000000-0000-4000-8000-000000000004',
|
||||
'00000000-0000-4000-8000-000000000002', 0);
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := provider.UpTo(ctx, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := provider.Down(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var preservedKey string
|
||||
if err := db.QueryRowContext(ctx, "SELECT object_key FROM attachments JOIN messages_attachments ON attachment_id = id").Scan(&preservedKey); err != nil || preservedKey != original {
|
||||
t.Fatalf("rollback lost the legacy attachment reference: %v", err)
|
||||
}
|
||||
if _, err := provider.UpTo(ctx, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := provider.UpTo(ctx, lab5MigrationCount); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dsn, err := os.ReadFile(os.Getenv("DATABASE_URL_FILE"))
|
||||
if err != nil {
|
||||
t.Fatal("cannot read test connection configuration")
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, string(dsn))
|
||||
if err != nil {
|
||||
t.Fatal("cannot configure test pool")
|
||||
}
|
||||
defer pool.Close()
|
||||
q := sqlc.New(pool)
|
||||
|
||||
var jobID, attachmentID pgtype.UUID
|
||||
var payload []byte
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT j.id, a.id, o.payload
|
||||
FROM messages_attachments AS m
|
||||
JOIN attachments AS a ON a.id = m.attachment_id
|
||||
JOIN attachment_jobs AS j ON j.attachment_id = a.id
|
||||
JOIN outbox AS o ON o.job_id = j.id
|
||||
WHERE a.status = 'queued' AND a.object_key = $1 AND a.staging_key = $1
|
||||
AND o.dedup_key = 'initial/' || j.id
|
||||
`, original).Scan(&jobID, &attachmentID, &payload)
|
||||
if err != nil {
|
||||
t.Fatalf("legacy attachment was not queued with its initial event: %v", err)
|
||||
}
|
||||
var event struct {
|
||||
JobID string `json:"job_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &event); err != nil || event.JobID != jobID.String() ||
|
||||
event.Attempt != 1 || event.CreatedAt.IsZero() {
|
||||
t.Fatalf("invalid backfill payload: %v", err)
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
claim := sqlc.ClaimJobParams{
|
||||
JobID: jobID, NewLeaseUntil: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
|
||||
}
|
||||
for range 2 {
|
||||
go func() {
|
||||
<-start
|
||||
_, err := q.ClaimJob(ctx, claim)
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
winners := 0
|
||||
for range 2 {
|
||||
switch err := <-results; {
|
||||
case err == nil:
|
||||
winners++
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
default:
|
||||
t.Fatalf("concurrent claim failed: %v", err)
|
||||
}
|
||||
}
|
||||
if winners != 1 {
|
||||
t.Fatalf("gave the lease to %d workers", winners)
|
||||
}
|
||||
|
||||
exec := func(query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, query, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
exec("UPDATE attachment_jobs SET lease_until = clock_timestamp() - interval '1 second' WHERE id = $1", jobID)
|
||||
for _, want := range []int{1, 0} {
|
||||
recovery, err := q.EnqueueExpiredLeases(ctx, 10)
|
||||
if err != nil || len(recovery) != want {
|
||||
t.Fatalf("recovery events = %d, want %d: %v", len(recovery), want, err)
|
||||
}
|
||||
if want == 1 {
|
||||
exec("UPDATE outbox SET sent_at = now() WHERE id = $1", recovery[0].ID)
|
||||
}
|
||||
}
|
||||
row, err := q.ClaimJob(ctx, claim)
|
||||
if err != nil || row.LeaseGeneration != 2 || row.AttemptsStarted != 2 {
|
||||
t.Fatalf("expired lease was not replaced correctly: %v", err)
|
||||
}
|
||||
fail := sqlc.FailJobParams{JobID: jobID, LeaseGeneration: 1, ErrorCode: "invalid_image"}
|
||||
if n, err := q.FailJob(ctx, fail); err != nil || n != 0 {
|
||||
t.Fatalf("stale worker could fail attachment: rows=%d, err=%v", n, err)
|
||||
}
|
||||
retry := sqlc.ScheduleRetryParams{
|
||||
JobID: jobID, LeaseGeneration: 2, ErrorCode: "s3_unavailable",
|
||||
AvailableAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},
|
||||
}
|
||||
if n, err := q.ScheduleRetry(ctx, retry); err != nil || n != 1 {
|
||||
t.Fatalf("retry could not be scheduled: rows=%d, err=%v", n, err)
|
||||
}
|
||||
if _, err := q.ClaimJob(ctx, claim); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("worker bypassed the retry delay: %v", err)
|
||||
}
|
||||
exec("UPDATE attachment_jobs SET next_attempt_at = now(), max_attempts = 3 WHERE id = $1", jobID)
|
||||
row, err = q.ClaimJob(ctx, claim)
|
||||
if err != nil || row.LeaseGeneration != 3 {
|
||||
t.Fatalf("due retry could not claim job: %v", err)
|
||||
}
|
||||
exec("UPDATE attachment_jobs SET lease_until = clock_timestamp() - interval '1 second' WHERE id = $1", jobID)
|
||||
if _, err := q.ClaimJob(ctx, claim); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("worker bypassed the attempt limit: %v", err)
|
||||
}
|
||||
fail.LeaseGeneration = 3
|
||||
fail.ErrorCode = "retry_exhausted"
|
||||
if n, err := q.FailJob(ctx, fail); err != nil || n != 1 {
|
||||
t.Fatalf("exhausted job could not be failed: rows=%d, err=%v", n, err)
|
||||
}
|
||||
var requestID pgtype.UUID
|
||||
if err := requestID.Scan("00000000-0000-4000-8000-000000000005"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay := sqlc.ReplayFailedParams{
|
||||
JobID: jobID, RequestID: requestID, OperatorID: "operator", Reason: "test replay", ExtraAttempts: 1,
|
||||
}
|
||||
for _, want := range []int64{1, 0} {
|
||||
if n, err := q.ReplayFailed(ctx, replay); err != nil || n != want {
|
||||
t.Fatalf("replay changed %d rows, want %d: %v", n, want, err)
|
||||
}
|
||||
}
|
||||
row, err = q.ClaimJob(ctx, claim)
|
||||
if err != nil || row.AttemptsStarted != 4 || row.LeaseGeneration != 4 {
|
||||
t.Fatalf("replay did not preserve attempt and lease counters: %v", err)
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
locked := q.WithTx(tx)
|
||||
if _, err := locked.LockActiveAttachmentJob(ctx, sqlc.LockActiveAttachmentJobParams{JobID: jobID, LeaseGeneration: 4}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
complete := sqlc.CompleteJobParams{JobID: jobID, LeaseGeneration: 4, ObjectKey: "results/original"}
|
||||
if n, err := locked.CompleteJob(ctx, complete); err != nil || n != 0 {
|
||||
t.Fatalf("published result without variants: rows=%d, err=%v", n, err)
|
||||
}
|
||||
variant := sqlc.CreateAttachmentVariantParams{
|
||||
AttachmentID: attachmentID, PipelineVersion: 1, Name: "thumbnail", ObjectKey: "results/thumb",
|
||||
ContentType: "image/jpeg", SizeBytes: 123, Width: 16, Height: 10, Sha256: strings.Repeat("a", 64),
|
||||
}
|
||||
if err := locked.CreateAttachmentVariant(ctx, variant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := locked.CompleteJob(ctx, complete); err != nil || n != 0 {
|
||||
t.Fatalf("published result without crop and optimized: rows=%d, err=%v", n, err)
|
||||
}
|
||||
variant.Name, variant.ObjectKey = "crop", "results/crop"
|
||||
if err := locked.CreateAttachmentVariant(ctx, variant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
variant.Name, variant.ObjectKey, variant.ContentType = "optimized", "results/webp", "image/webp"
|
||||
if err := locked.CreateAttachmentVariant(ctx, variant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := locked.CompleteJob(ctx, complete); err != nil || n != 1 {
|
||||
t.Fatalf("current owner could not publish result: rows=%d, err=%v", n, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := q.ClaimJob(ctx, claim); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("worker claimed a ready job: %v", err)
|
||||
}
|
||||
published, err := q.GetPublishedOriginalKey(ctx, sqlc.GetPublishedOriginalKeyParams{
|
||||
AttachmentID: attachmentID, PipelineVersion: 1,
|
||||
})
|
||||
if err != nil || published.String != complete.ObjectKey {
|
||||
t.Fatalf("published original not recorded for its version: %v", err)
|
||||
}
|
||||
|
||||
var attempts, events, replays int
|
||||
err = pool.QueryRow(ctx, `
|
||||
SELECT (SELECT count(*) FROM attachment_attempts WHERE job_id = $1 AND finished_at IS NOT NULL),
|
||||
(SELECT count(*) FROM outbox WHERE job_id = $1),
|
||||
(SELECT count(*) FROM attachment_replays WHERE job_id = $1)
|
||||
`, jobID).Scan(&attempts, &events, &replays)
|
||||
if err != nil || attempts != 4 || events != 4 || replays != 1 {
|
||||
t.Fatalf("unexpected history: attempts=%d, events=%d, replays=%d: %v", attempts, events, replays, 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,212 @@
|
||||
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
|
||||
}
|
||||
|
||||
const lab5MigrationCount = 8
|
||||
|
||||
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 != lab5MigrationCount {
|
||||
t.Fatalf("empty schema: applied %d migrations, want %d", count, lab5MigrationCount)
|
||||
}
|
||||
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 != lab5MigrationCount {
|
||||
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) != lab5MigrationCount {
|
||||
t.Fatal("status did not report all seven 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 != lab5MigrationCount {
|
||||
t.Fatalf("concurrent runners applied %d migrations in total, want %d", applied, lab5MigrationCount)
|
||||
}
|
||||
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 != lab5MigrationCount || distinctVersions != lab5MigrationCount {
|
||||
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 latest version")
|
||||
}
|
||||
assertVersion(lab5MigrationCount)
|
||||
assertAbsent()
|
||||
if _, err = provider.DownTo(ctx, 2); err != nil {
|
||||
t.Fatal("latest -> 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.Up(ctx); err != nil {
|
||||
t.Fatal("1 -> latest reapplication failed")
|
||||
}
|
||||
assertVersion(lab5MigrationCount)
|
||||
assertAbsent()
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"highload/internal/broker"
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/fault"
|
||||
"highload/internal/repository/postgres"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := run(ctx); err != nil {
|
||||
slog.Error("relay startup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context) error {
|
||||
cfg, err := config.LoadPipeline()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.BrokerURL == "" {
|
||||
return fmt.Errorf("BROKER_URL_FILE must contain an AMQP URL")
|
||||
}
|
||||
url, err := config.LoadPostgresURL()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.NewPostgres(ctx, url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("PostgreSQL unavailable")
|
||||
}
|
||||
defer pool.Close()
|
||||
repo := postgres.NewAttachmentRepository(sqlc.New(pool), pool)
|
||||
|
||||
recovered := make(chan struct{})
|
||||
go func() {
|
||||
defer close(recovered)
|
||||
for ctx.Err() == nil {
|
||||
if n, err := repo.EnqueueExpiredLeases(ctx, 32); err != nil && ctx.Err() == nil {
|
||||
slog.Warn("lease recovery failed", "error", err)
|
||||
} else if n > 0 {
|
||||
slog.Info("expired leases enqueued", "count", n)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}()
|
||||
for ctx.Err() == nil {
|
||||
if err := publish(ctx, repo, cfg.BrokerURL); err != nil && ctx.Err() == nil {
|
||||
slog.Warn("relay reconnecting", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
<-recovered
|
||||
return nil
|
||||
}
|
||||
|
||||
func publish(ctx context.Context, repo *postgres.AttachmentRepository, url string) error {
|
||||
conn, ch, err := broker.Connect(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer broker.Close(conn)
|
||||
publisher, err := broker.NewPublisher(ch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
sent, err := repo.PublishPending(ctx, func(txCtx context.Context, event sqlc.Outbox) error {
|
||||
if err := fault.Pause(txCtx, "before_publish", event.JobID.String()); err != nil {
|
||||
return err
|
||||
}
|
||||
confirmCtx, cancel := context.WithTimeout(txCtx, 5*time.Second)
|
||||
err := publisher.Publish(confirmCtx, event.ID.String(), event.Payload)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fault.Pause(txCtx, "after_publish", event.JobID.String())
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !sent {
|
||||
if conn.IsClosed() {
|
||||
return fmt.Errorf("RabbitMQ connection closed")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(150 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/pipeline"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/storage/s3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := run(ctx); err != nil {
|
||||
slog.Error("worker startup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context) error {
|
||||
cfg, err := config.LoadPipeline()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.BrokerURL == "" {
|
||||
return fmt.Errorf("BROKER_URL_FILE must contain an AMQP URL")
|
||||
}
|
||||
url, storageConfig, err := config.LoadAttachmentCleanup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.NewPostgres(ctx, url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("PostgreSQL unavailable")
|
||||
}
|
||||
defer pool.Close()
|
||||
objects, err := s3.NewStorage(ctx, &storageConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("S3 configuration invalid")
|
||||
}
|
||||
worker := pipeline.Worker{Repo: postgres.NewAttachmentRepository(sqlc.New(pool), pool), Objects: objects, Config: cfg}
|
||||
slog.Info("worker started", "concurrency", cfg.Concurrency, "prefetch_per_consumer", cfg.Prefetch)
|
||||
var lanes sync.WaitGroup
|
||||
for range cfg.Concurrency {
|
||||
lanes.Go(func() { worker.Serve(ctx) })
|
||||
}
|
||||
lanes.Wait()
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user