Перенести пользователей в PostgreSQL и добавить пароли

This commit is contained in:
2026-10-06 14:54:34 +03:00
parent 46c00436a0
commit 618d3919d1
17 changed files with 482 additions and 219 deletions
-63
View File
@@ -1,63 +0,0 @@
// Package store holds the repository implementations of the users module.
// inmem.go is the in-process one: state lives only in this process and
// disappears with it by design of the lab.
package store
import (
"context"
"sync"
"github.com/google/uuid"
"messenger/internal/user"
)
type InMemUsers struct {
mu sync.RWMutex
byID map[uuid.UUID]user.User
byUsername map[string]struct{}
}
var _ user.Repository = (*InMemUsers)(nil)
func NewInMemUsers() *InMemUsers {
return &InMemUsers{
byID: make(map[uuid.UUID]user.User),
byUsername: make(map[string]struct{}),
}
}
// Create checks and inserts under the same write lock, so concurrent
// registrations of one username admit exactly one winner.
func (r *InMemUsers) Create(_ context.Context, u user.User) error {
r.mu.Lock()
defer r.mu.Unlock()
if _, taken := r.byUsername[u.Username]; taken {
return user.ErrUsernameTaken
}
r.byUsername[u.Username] = struct{}{}
r.byID[u.ID] = u
return nil
}
func (r *InMemUsers) GetByID(_ context.Context, id uuid.UUID) (user.User, error) {
r.mu.RLock()
defer r.mu.RUnlock()
u, ok := r.byID[id]
if !ok {
return user.User{}, user.ErrNotFound
}
return u, nil
}
func (r *InMemUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
r.mu.RLock()
defer r.mu.RUnlock()
found := make([]uuid.UUID, 0, len(ids))
for _, id := range ids {
if _, ok := r.byID[id]; ok {
found = append(found, id)
}
}
return found, nil
}
-97
View File
@@ -1,97 +0,0 @@
package store_test
import (
"context"
"errors"
"sync"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/user"
"messenger/internal/user/store"
)
func mustUser(t *testing.T, username string) user.User {
t.Helper()
u, err := user.New(ident.New(), username, "Display")
if err != nil {
t.Fatal(err)
}
return u
}
func TestCreateThenGetByID(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
u := mustUser(t, "alice")
if err := repo.Create(ctx, u); err != nil {
t.Fatalf("Create error: %v", err)
}
got, err := repo.GetByID(ctx, u.ID)
if err != nil {
t.Fatalf("GetByID error: %v", err)
}
if got != u {
t.Fatalf("GetByID = %+v, want %+v", got, u)
}
}
func TestGetByIDUnknownReturnsErrNotFound(t *testing.T) {
_, err := store.NewInMemUsers().GetByID(context.Background(), ident.New())
if !errors.Is(err, user.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
func TestCreateRejectsDuplicateUsername(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
if err := repo.Create(ctx, mustUser(t, "alice")); err != nil {
t.Fatal(err)
}
err := repo.Create(ctx, mustUser(t, "alice"))
if !errors.Is(err, user.ErrUsernameTaken) {
t.Fatalf("err = %v, want ErrUsernameTaken", err)
}
}
func TestCreateIsAtomicUnderConcurrency(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
const workers = 50
var wg sync.WaitGroup
var mu sync.Mutex
created := 0
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := repo.Create(ctx, mustUser(t, "same_name")); err == nil {
mu.Lock()
created++
mu.Unlock()
}
}()
}
wg.Wait()
if created != 1 {
t.Fatalf("exactly one Create must win, got %d", created)
}
}
func TestExistingIDsReturnsOnlyKnownIDs(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
alice, bob := mustUser(t, "alice"), mustUser(t, "bob")
_ = repo.Create(ctx, alice)
_ = repo.Create(ctx, bob)
got, err := repo.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID, bob.ID})
if err != nil {
t.Fatal(err)
}
if len(got) != 3 || got[0] != bob.ID || got[1] != alice.ID || got[2] != bob.ID {
t.Fatalf("ExistingIDs must keep input order and drop unknown ids, got %v", got)
}
}
+75
View File
@@ -0,0 +1,75 @@
// Package store holds the repository implementations of the users module.
package store
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/platform/postgres"
"messenger/internal/user"
)
const userColumns = `id, username, display_name, password_hash, created_at`
type Users struct {
pool *pgxpool.Pool
}
var _ user.Repository = (*Users)(nil)
func NewUsers(pool *pgxpool.Pool) *Users {
return &Users{pool: pool}
}
// Create relies on the unique constraint rather than a prior lookup, so two
// concurrent registrations of one username cannot both succeed.
func (r *Users) Create(ctx context.Context, u user.User) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO users (`+userColumns+`) VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Username, u.DisplayName, u.PasswordHash, u.CreatedAt)
if postgres.IsUniqueViolation(err, "users_username_key") {
return user.ErrUsernameTaken
}
if err != nil {
return fmt.Errorf("insert user: %w", err)
}
return nil
}
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1`, id)
}
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE username = $1`, username)
}
func (r *Users) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
rows, err := r.pool.Query(ctx, `SELECT id FROM users WHERE id = ANY($1)`, ids)
if err != nil {
return nil, fmt.Errorf("select user ids: %w", err)
}
found, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
if err != nil {
return nil, fmt.Errorf("read user ids: %w", err)
}
return found, nil
}
func (r *Users) one(ctx context.Context, query string, arg any) (user.User, error) {
var u user.User
err := r.pool.QueryRow(ctx, query, arg).Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return user.User{}, user.ErrNotFound
}
if err != nil {
return user.User{}, fmt.Errorf("select user: %w", err)
}
u.CreatedAt = u.CreatedAt.UTC()
return u, nil
}