forked from mtusi2026/mtusi2026lab2
Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход, opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON, keyset-пагинацию по индексу, миграции, compose-стенд и собственные проверки уровня 3/4. Трек 5 — план запроса и восстановление.
140 lines
3.8 KiB
Go
140 lines
3.8 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"embed"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var migrationFiles embed.FS
|
|
|
|
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
|
|
// concurrent API replicas that start at the same time; it is released when the
|
|
// dedicated connection is returned or the session ends.
|
|
const advisoryLockKey int64 = 0x6d74756c616232 // "mtulab2"
|
|
|
|
type migration struct {
|
|
version int
|
|
name string
|
|
checksum string
|
|
sql string
|
|
}
|
|
|
|
// Migrate applies every embedded migration exactly once and records its
|
|
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
|
|
// A changed migration file is a startup error rather than a silent divergence.
|
|
func (s *Store) Migrate(ctx context.Context) error {
|
|
conn, err := s.pool.Acquire(ctx)
|
|
if err != nil {
|
|
return s.classify(err)
|
|
}
|
|
defer conn.Release()
|
|
|
|
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
|
|
return s.classify(err)
|
|
}
|
|
defer func() {
|
|
// Use a background context: the request context may already be
|
|
// cancelled when a startup timeout fires, but the lock still has to be
|
|
// released explicitly before the connection is returned to the pool.
|
|
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
|
|
}()
|
|
|
|
if _, err := conn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version integer PRIMARY KEY,
|
|
name text NOT NULL,
|
|
checksum text NOT NULL,
|
|
applied_at timestamptz NOT NULL DEFAULT now()
|
|
)`); err != nil {
|
|
return s.classify(err)
|
|
}
|
|
|
|
migrations, err := loadMigrations()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, item := range migrations {
|
|
var existing string
|
|
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
|
|
switch {
|
|
case err == nil:
|
|
if existing != item.checksum {
|
|
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
|
|
}
|
|
continue
|
|
case !errors.Is(err, pgx.ErrNoRows):
|
|
return s.classify(err)
|
|
}
|
|
|
|
tx, err := conn.Begin(ctx)
|
|
if err != nil {
|
|
return s.classify(err)
|
|
}
|
|
if _, err := tx.Exec(ctx, item.sql); err != nil {
|
|
_ = tx.Rollback(context.Background())
|
|
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
|
|
}
|
|
if _, err := tx.Exec(ctx,
|
|
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
|
|
item.version, item.name, item.checksum,
|
|
); err != nil {
|
|
_ = tx.Rollback(context.Background())
|
|
return s.classify(err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return s.classify(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func loadMigrations() ([]migration, error) {
|
|
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
items := make([]migration, 0, len(entries))
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
|
continue
|
|
}
|
|
name := entry.Name()
|
|
if len(name) < 9 {
|
|
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
|
|
}
|
|
version, err := strconv.Atoi(name[:4])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
|
|
}
|
|
data, err := migrationFiles.ReadFile("migrations/" + name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
items = append(items, migration{
|
|
version: version,
|
|
name: strings.TrimSuffix(name[5:], ".sql"),
|
|
checksum: hex.EncodeToString(sum[:]),
|
|
sql: string(data),
|
|
})
|
|
}
|
|
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
|
|
for i := 1; i < len(items); i++ {
|
|
if items[i].version == items[i-1].version {
|
|
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
|
|
}
|
|
}
|
|
return items, nil
|
|
}
|