Упростить ошибки сессий, логировать миграции и тестировать с рабочим клиентом Valkey
This commit is contained in:
+3
-1
@@ -42,9 +42,11 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
if err := postgres.Migrate(ctx, pool); err != nil {
|
applied, err := postgres.Migrate(ctx, pool)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
log.Info("schema ready", "applied_migrations", applied)
|
||||||
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
|
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -2,19 +2,16 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrSessionNotFound means the token is unknown, expired or revoked; the
|
|
||||||
// store cannot tell these apart, and the client must not either.
|
|
||||||
var ErrSessionNotFound = errors.New("session not found")
|
|
||||||
|
|
||||||
type Repository interface {
|
type Repository interface {
|
||||||
// Create stores the session until its absolute ExpiresAt.
|
// Create stores the session until its absolute ExpiresAt.
|
||||||
Create(ctx context.Context, s Session) error
|
Create(ctx context.Context, s Session) error
|
||||||
// UserID returns the owner of a live session or ErrSessionNotFound.
|
// UserID returns the owner of a live session, or ErrUnauthenticated when
|
||||||
|
// the token is unknown, expired or revoked: the store cannot tell these
|
||||||
|
// apart, and the client must not either.
|
||||||
UserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
UserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||||
// Delete revokes the session; deleting a missing one is not an error.
|
// Delete revokes the session; deleting a missing one is not an error.
|
||||||
Delete(ctx context.Context, tokenHash string) error
|
Delete(ctx context.Context, tokenHash string) error
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -53,15 +52,11 @@ func (s *Service) Login(ctx context.Context, username, password string) (Issued,
|
|||||||
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
|
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Authenticate returns the owner of the token's live session. A store
|
// Authenticate returns the owner of the token's live session or
|
||||||
// failure is returned as is, never as ErrUnauthenticated: an outage must not
|
// ErrUnauthenticated. A store failure stays an unavailability, never
|
||||||
// look like a bad token to the client.
|
// ErrUnauthenticated: an outage must not look like a bad token to the client.
|
||||||
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
||||||
id, err := s.sessions.UserID(ctx, HashToken(token))
|
return s.sessions.UserID(ctx, HashToken(token))
|
||||||
if errors.Is(err, ErrSessionNotFound) {
|
|
||||||
return uuid.Nil, ErrUnauthenticated
|
|
||||||
}
|
|
||||||
return id, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Logout(ctx context.Context, token string) error {
|
func (s *Service) Logout(ctx context.Context, token string) error {
|
||||||
|
|||||||
@@ -27,10 +27,10 @@ func NewSessions(client *redis.Client) *Sessions {
|
|||||||
return &Sessions{client: client}
|
return &Sessions{client: client}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create sets an absolute expiry (PXAT): a restart of the store replays it
|
// Create sets an absolute expiry (EXAT/PXAT): a restart of the store replays
|
||||||
// from the append-only file and does not extend the session.
|
// it from the append-only file and does not extend the session.
|
||||||
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
|
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
|
||||||
err := r.client.Do(ctx, "SET", keyPrefix+s.TokenHash, s.UserID.String(), "PXAT", s.ExpiresAt.UnixMilli()).Err()
|
err := r.client.SetArgs(ctx, keyPrefix+s.TokenHash, s.UserID.String(), redis.SetArgs{ExpireAt: s.ExpiresAt}).Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return unavailable(err)
|
return unavailable(err)
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
|
|||||||
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||||
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
|
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
|
||||||
if errors.Is(err, redis.Nil) {
|
if errors.Is(err, redis.Nil) {
|
||||||
return uuid.Nil, auth.ErrSessionNotFound
|
return uuid.Nil, auth.ErrUnauthenticated
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return uuid.Nil, unavailable(err)
|
return uuid.Nil, unavailable(err)
|
||||||
|
|||||||
@@ -54,24 +54,30 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
|||||||
return pool, nil
|
return pool, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Migrate applies pending migrations. A session advisory lock serialises
|
// Migrate applies pending migrations and returns the versions it applied. A
|
||||||
// concurrent starts, so several API replicas may call it at once; applied
|
// session advisory lock serialises concurrent starts, so several API
|
||||||
// versions are recorded, which makes a repeated run a no-op.
|
// replicas may call it at once; applied versions are recorded, which makes a
|
||||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
// repeated run a no-op.
|
||||||
|
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
|
||||||
db := stdlib.OpenDBFromPool(pool)
|
db := stdlib.OpenDBFromPool(pool)
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
locker, err := lock.NewPostgresSessionLocker()
|
locker, err := lock.NewPostgresSessionLocker()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("migration lock: %w", err)
|
return nil, fmt.Errorf("migration lock: %w", err)
|
||||||
}
|
}
|
||||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
|
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("load migrations: %w", err)
|
return nil, fmt.Errorf("load migrations: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := provider.Up(ctx); err != nil {
|
results, err := provider.Up(ctx)
|
||||||
return fmt.Errorf("apply migrations: %w", err)
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
applied := make([]int64, 0, len(results))
|
||||||
|
for _, r := range results {
|
||||||
|
applied = append(applied, r.Source.Version)
|
||||||
|
}
|
||||||
|
return applied, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
||||||
|
|||||||
@@ -32,9 +32,13 @@ func TestMain(m *testing.M) {
|
|||||||
|
|
||||||
func TestMigrateIsRepeatable(t *testing.T) {
|
func TestMigrateIsRepeatable(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
if err := postgres.Migrate(ctx, db.Pool); err != nil {
|
applied, err := postgres.Migrate(ctx, db.Pool)
|
||||||
|
if err != nil {
|
||||||
t.Fatalf("second migrate: %v", err)
|
t.Fatalf("second migrate: %v", err)
|
||||||
}
|
}
|
||||||
|
if len(applied) != 0 {
|
||||||
|
t.Fatalf("second migrate applied %v, want nothing", applied)
|
||||||
|
}
|
||||||
var version int64
|
var version int64
|
||||||
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
|
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
tcvalkey "github.com/testcontainers/testcontainers-go/modules/valkey"
|
tcvalkey "github.com/testcontainers/testcontainers-go/modules/valkey"
|
||||||
|
|
||||||
"messenger/internal/platform/postgres"
|
"messenger/internal/platform/postgres"
|
||||||
|
"messenger/internal/platform/valkey"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -66,7 +67,7 @@ func StartPostgres(ctx context.Context) (*DB, error) {
|
|||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := postgres.Migrate(ctx, db.Pool); err != nil {
|
if _, err := postgres.Migrate(ctx, db.Pool); err != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -150,12 +151,12 @@ func StartValkey(ctx context.Context) (*KV, error) {
|
|||||||
kv.Close()
|
kv.Close()
|
||||||
return nil, fmt.Errorf("valkey address: %w", err)
|
return nil, fmt.Errorf("valkey address: %w", err)
|
||||||
}
|
}
|
||||||
opts, err := redis.ParseURL(kv.URL)
|
// The production client, so outage tests see its fail-fast settings.
|
||||||
|
kv.Client, err = valkey.NewClient(ctx, kv.URL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
kv.Close()
|
kv.Close()
|
||||||
return nil, fmt.Errorf("valkey url: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
kv.Client = redis.NewClient(opts)
|
|
||||||
return kv, nil
|
return kv, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user