Перенести решение лабораторной 1 как основу для лабораторной 2

This commit is contained in:
2026-10-06 11:54:05 +03:00
parent 65003b6119
commit 5c3f2bfad0
54 changed files with 4472 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/httpx"
)
type Handler struct {
users *Service
}
func NewHandler(users *Service) *Handler {
return &Handler{users: users}
}
// Register mounts registration on the public router and the current-user
// endpoint on the router guarded by RequireUser.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/users", h.register)
protected.GET("/users/me", auth.WithUser(h.me))
}
type createRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type Response struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
func ToResponse(u User) Response {
return Response{
ID: u.ID.String(),
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: httpx.Timestamp(u.CreatedAt),
}
}
func (h *Handler) register(c *gin.Context) {
var req createRequest
if err := httpx.DecodeJSON(c, &req); err != nil {
httpx.Error(c, err)
return
}
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, ToResponse(u))
}
func (h *Handler) me(c *gin.Context, actor uuid.UUID) {
u, err := h.users.GetByID(c.Request.Context(), actor)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, ToResponse(u))
}
+17
View File
@@ -0,0 +1,17 @@
package user
import (
"context"
"github.com/google/uuid"
)
type Repository interface {
// Create stores a new user or returns ErrUsernameTaken; the uniqueness
// check and the insert must be atomic.
Create(ctx context.Context, user User) error
GetByID(ctx context.Context, id uuid.UUID) (User, error)
// ExistingIDs returns the subset of ids that belong to registered users,
// in input order, in one round trip.
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
}
+55
View File
@@ -0,0 +1,55 @@
package user
import (
"context"
"fmt"
"github.com/google/uuid"
"messenger/internal/platform/ident"
)
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Register(ctx context.Context, username, displayName string) (User, error) {
u, err := New(ident.New(), username, displayName)
if err != nil {
return User{}, err
}
if err := s.repo.Create(ctx, u); err != nil {
return User{}, err
}
return u, nil
}
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (User, error) {
return s.repo.GetByID(ctx, id)
}
// Exists serves the identification middleware; it is the single-id form of
// ExistingIDs so existence is answered by one code path.
func (s *Service) Exists(ctx context.Context, id uuid.UUID) (bool, error) {
found, err := s.ExistingIDs(ctx, []uuid.UUID{id})
if err != nil {
return false, err
}
return len(found) == 1, nil
}
// ExistingIDs serves the chats module when it validates member lists.
func (s *Service) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
if len(ids) == 0 {
return []uuid.UUID{}, nil
}
found, err := s.repo.ExistingIDs(ctx, ids)
if err != nil {
return nil, fmt.Errorf("user lookup: %w", err)
}
return found, nil
}
+85
View File
@@ -0,0 +1,85 @@
package user_test
import (
"context"
"errors"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/user"
"messenger/internal/user/store"
)
func newService() *user.Service {
return user.NewService(store.NewInMemUsers())
}
func TestRegisterStoresUser(t *testing.T) {
svc := newService()
ctx := context.Background()
u, err := svc.Register(ctx, "alice", "Алиса")
if err != nil {
t.Fatalf("Register error: %v", err)
}
if u.ID.Version() != 7 {
t.Fatalf("id must be UUIDv7, got version %d", u.ID.Version())
}
got, err := svc.GetByID(ctx, u.ID)
if err != nil || got != u {
t.Fatalf("GetByID = %+v, %v; want %+v", got, err, u)
}
if ok, err := svc.Exists(ctx, u.ID); err != nil || !ok {
t.Fatalf("Exists = %v, %v; want true", ok, err)
}
}
func TestRegisterRejectsInvalidInput(t *testing.T) {
_, err := newService().Register(context.Background(), "Bad Name", "x")
if apperr.KindOf(err) != apperr.KindInvalid {
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
}
}
func TestRegisterReportsDuplicateAsConflict(t *testing.T) {
svc := newService()
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "A"); err != nil {
t.Fatal(err)
}
_, err := svc.Register(ctx, "alice", "B")
if !errors.Is(err, user.ErrUsernameTaken) || apperr.KindOf(err) != apperr.KindConflict {
t.Fatalf("err = %v, want ErrUsernameTaken with KindConflict", err)
}
}
func TestGetByIDUnknownIsNotFound(t *testing.T) {
svc := newService()
_, err := svc.GetByID(context.Background(), ident.New())
if !errors.Is(err, user.ErrNotFound) || apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("err = %v, want ErrNotFound with KindNotFound", err)
}
if ok, err := svc.Exists(context.Background(), ident.New()); err != nil || ok {
t.Fatalf("Exists = %v, %v; want false, nil", ok, err)
}
}
func TestExistingIDsFiltersInOneCall(t *testing.T) {
svc := newService()
ctx := context.Background()
alice, _ := svc.Register(ctx, "alice", "A")
bob, _ := svc.Register(ctx, "bob", "B")
unknown := ident.New()
got, err := svc.ExistingIDs(ctx, []uuid.UUID{unknown, bob.ID, alice.ID})
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != bob.ID || got[1] != alice.ID {
t.Fatalf("ExistingIDs = %v, want bob then alice", got)
}
if empty, err := svc.ExistingIDs(ctx, nil); err != nil || len(empty) != 0 {
t.Fatalf("ExistingIDs(nil) = %v, %v", empty, err)
}
}
+63
View File
@@ -0,0 +1,63 @@
// 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
@@ -0,0 +1,97 @@
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)
}
}
+51
View File
@@ -0,0 +1,51 @@
// Package user is the users module. The entity mirrors the future table row
// and carries no behaviour; New only enforces input invariants and CreatedAt
// derives from the UUIDv7 id.
package user
import (
"fmt"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const MaxDisplayNameCodePoints = 100
var (
ErrNotFound = apperr.NotFound("user not found")
ErrUsernameTaken = apperr.Conflict("username already taken")
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type User struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func New(id uuid.UUID, username, displayName string) (User, error) {
if !usernamePattern.MatchString(username) {
return User{}, apperr.Invalid("username must match [a-z0-9_]{3,32}")
}
if strings.TrimSpace(displayName) == "" {
return User{}, apperr.Invalid("display_name must not be blank")
}
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
}
return User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: ident.TimeOf(id),
}, nil
}
+56
View File
@@ -0,0 +1,56 @@
package user_test
import (
"strings"
"testing"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/user"
)
func TestNewDerivesCreatedAtFromID(t *testing.T) {
id := ident.New()
u, err := user.New(id, "alice", "Алиса")
if err != nil {
t.Fatalf("New error: %v", err)
}
if u.ID != id || u.Username != "alice" || u.DisplayName != "Алиса" {
t.Fatalf("unexpected user %+v", u)
}
if !u.CreatedAt.Equal(ident.TimeOf(id)) {
t.Fatalf("CreatedAt = %v, want %v", u.CreatedAt, ident.TimeOf(id))
}
}
func TestNewValidatesUsername(t *testing.T) {
valid := []string{"abc", "a_1", strings.Repeat("a", 32), "user_2026"}
for _, name := range valid {
if _, err := user.New(ident.New(), name, "ok"); err != nil {
t.Errorf("username %q must be accepted: %v", name, err)
}
}
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "al ice", "алиса", "a-b", "a.b", " abc", "abc\n"}
for _, name := range invalid {
_, err := user.New(ident.New(), name, "ok")
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "username") {
t.Errorf("username %q must be rejected as invalid naming the field, got %v", name, err)
}
}
}
func TestNewValidatesDisplayNameByCodePoints(t *testing.T) {
valid := []string{"A", "Алиса", strings.Repeat("я", 100), "👋 hi"}
for _, name := range valid {
if _, err := user.New(ident.New(), "alice", name); err != nil {
t.Errorf("display_name %q must be accepted: %v", name, err)
}
}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101)}
for _, name := range invalid {
_, err := user.New(ident.New(), "alice", name)
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "display_name") {
t.Errorf("display_name %q must be rejected as invalid naming the field, got %v", name, err)
}
}
}