lab2: postgres, sessions, redis, persistence, stale read
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
users repository.UserRepository
|
||||
sessions repository.SessionRepository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users repository.UserRepository, sessions repository.SessionRepository, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (*domain.Session, *domain.User, error) {
|
||||
u, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
_, _ = hashPassword("dummy-password-for-timing")
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := s.users.GetPasswordHash(ctx, u.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := verifyPassword(password, hash); err != nil {
|
||||
if errors.Is(err, ErrPasswordMismatch) {
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
sess := &domain.Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, sess); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sess, u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (*domain.User, error) {
|
||||
sess, err := s.sessions.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if nowUTC().After(sess.ExpiresAt) {
|
||||
_ = s.sessions.Delete(ctx, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
u, err := s.users.GetByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, token)
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats repository.ChatRepository
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats repository.ChatRepository, users repository.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, callerID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if !validateTitle(title) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerFound := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
if !callerFound {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit int) ([]*domain.Chat, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, callerID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.chats.ListByMember(ctx, callerID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if items == nil {
|
||||
items = []*domain.Chat{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(callerID, last.CreatedAt, last.ID)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
type chatFixture struct {
|
||||
users *UserService
|
||||
chats *ChatService
|
||||
aliceID string
|
||||
bobID string
|
||||
carolID string
|
||||
}
|
||||
|
||||
func newChatFixture(t *testing.T) *chatFixture {
|
||||
t.Helper()
|
||||
userRepo := memory.NewUserRepository()
|
||||
chatRepo := memory.NewChatRepository()
|
||||
userSvc := NewUserService(userRepo)
|
||||
chatSvc := NewChatService(chatRepo, userRepo)
|
||||
ctx := context.Background()
|
||||
|
||||
alice, err := userSvc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("register alice: %v", err)
|
||||
}
|
||||
bob, err := userSvc.Register(ctx, "bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("register bob: %v", err)
|
||||
}
|
||||
carol, err := userSvc.Register(ctx, "carol", "Кэрол")
|
||||
if err != nil {
|
||||
t.Fatalf("register carol: %v", err)
|
||||
}
|
||||
return &chatFixture{
|
||||
users: userSvc,
|
||||
chats: chatSvc,
|
||||
aliceID: alice.ID,
|
||||
bobID: bob.ID,
|
||||
carolID: carol.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_OK(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
if err != nil {
|
||||
t.Fatalf("Create failed: %v", err)
|
||||
}
|
||||
if len(c.MemberIDs) != 2 {
|
||||
t.Errorf("expected 2 members, got %d", len(c.MemberIDs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_CallerNotInMembers(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Alice создаёт чат, но в member_ids только Bob.
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.bobID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_UnknownMember(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, "nonexistent-uuid"})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_DuplicateMembers(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.aliceID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Create_InvalidTitle(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []string{"", " "}
|
||||
for _, title := range cases {
|
||||
_, err := f.chats.Create(ctx, f.aliceID, title, []string{f.aliceID})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("title %q: expected ErrInvalidInput, got %v", title, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Member(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, _ := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
|
||||
got, err := f.chats.Get(ctx, f.bobID, c.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
}
|
||||
if got.ID != c.ID {
|
||||
t.Errorf("id mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Stranger(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
c, _ := f.chats.Create(ctx, f.aliceID, "Project", []string{f.aliceID, f.bobID})
|
||||
|
||||
// Carol не член — должна получить ErrNotFound, не ErrForbidden.
|
||||
_, err := f.chats.Get(ctx, f.carolID, c.ID)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_Get_Nonexistent(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.chats.Get(ctx, f.aliceID, "nonexistent-chat")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_OnlyMemberChats(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = f.chats.Create(ctx, f.aliceID, "A-B", []string{f.aliceID, f.bobID})
|
||||
_, _ = f.chats.Create(ctx, f.aliceID, "A-C", []string{f.aliceID, f.carolID})
|
||||
_, _ = f.chats.Create(ctx, f.bobID, "B-C", []string{f.bobID, f.carolID})
|
||||
|
||||
items, _, err := f.chats.List(ctx, f.aliceID, "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Errorf("expected 2 chats for alice, got %d", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_InvalidLimit(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, limit := range []int{0, -1, 101} {
|
||||
_, _, err := f.chats.List(ctx, f.aliceID, "", limit)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("limit %d: expected ErrInvalidInput, got %v", limit, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatService_List_InvalidCursor(t *testing.T) {
|
||||
f := newChatFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _, err := f.chats.List(ctx, f.aliceID, "!!!bad-cursor!!!", 10)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// encodeCursor кодирует (scope, created_at, id) в base64.
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
// decodeCursor декодирует и проверяет scope.
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 || parts[0] != expectedScope {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// ErrInvalidInput — невалидные данные от клиента (не проходит валидацию).
|
||||
// Мапится в HTTP 400 invalid_request.
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
|
||||
// ErrUnauthorized — нет аутентификации или она недействительна.
|
||||
// Мапится в HTTP 401 unauthorized.
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
|
||||
// ErrNotFound — объект не существует или недоступен вызывающему.
|
||||
// README требует: чужой объект → 404, чтобы не раскрывать существование.
|
||||
// Мапится в HTTP 404 not_found.
|
||||
ErrNotFound = errors.New("not found")
|
||||
|
||||
// ErrConflict — нарушение уникальности (занятый username).
|
||||
// Мапится в HTTP 409 conflict.
|
||||
ErrConflict = errors.New("conflict")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// nowUTC возвращает время UTC с точностью до секунд.
|
||||
// PostgreSQL и Python-клиент тестов ожидают формат без наносекунд.
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
redisrepo "github.com/charawein/mtusi2026lab2/internal/repository/redis"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages repository.MessageRepository
|
||||
chats repository.ChatRepository
|
||||
cache *redisrepo.MessageCache
|
||||
invalidate bool // ВРЕМЕННЫЙ ФЛАГ для демонстрации stale read
|
||||
}
|
||||
|
||||
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache) *MessageService {
|
||||
return &MessageService{messages: messages, chats: chats, cache: cache, invalidate: false}
|
||||
}
|
||||
|
||||
func (s *MessageService) SetInvalidate(v bool) { s.invalidate = v }
|
||||
|
||||
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
|
||||
if !validateText(text) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ok, err := s.chats.IsMember(ctx, chatID, senderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
m := &domain.Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.messages.Create(ctx, m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Если invalidate=false — кэш НЕ сбрасывается, будет stale read.
|
||||
if s.invalidate && s.cache != nil {
|
||||
_ = s.cache.Invalidate(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
|
||||
// Попытка достать из кэша (только для первой страницы).
|
||||
if s.cache != nil && cursor == "" {
|
||||
if cached, hit := s.cache.Get(ctx, chatID, cursor); hit {
|
||||
return cached, "", nil
|
||||
}
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, chatID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if items == nil {
|
||||
items = []*domain.Message{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
||||
}
|
||||
|
||||
// Кэшируем только первую страницу.
|
||||
if s.cache != nil && cursor == "" {
|
||||
s.cache.Set(ctx, chatID, cursor, items)
|
||||
}
|
||||
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
type messageFixture struct {
|
||||
users *UserService
|
||||
chats *ChatService
|
||||
messages *MessageService
|
||||
|
||||
aliceID string
|
||||
bobID string
|
||||
carolID string
|
||||
chatID string
|
||||
}
|
||||
|
||||
func newMessageFixture(t *testing.T) *messageFixture {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
userRepo := memory.NewUserRepository()
|
||||
chatRepo := memory.NewChatRepository()
|
||||
msgRepo := memory.NewMessageRepository()
|
||||
|
||||
userSvc := NewUserService(userRepo)
|
||||
chatSvc := NewChatService(chatRepo, userRepo)
|
||||
msgSvc := NewMessageService(msgRepo, chatRepo)
|
||||
|
||||
alice, err := userSvc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("register alice: %v", err)
|
||||
}
|
||||
bob, err := userSvc.Register(ctx, "bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("register bob: %v", err)
|
||||
}
|
||||
carol, err := userSvc.Register(ctx, "carol", "Кэрол")
|
||||
if err != nil {
|
||||
t.Fatalf("register carol: %v", err)
|
||||
}
|
||||
|
||||
chat, err := chatSvc.Create(ctx, alice.ID, "Project", []string{alice.ID, bob.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
return &messageFixture{
|
||||
users: userSvc,
|
||||
chats: chatSvc,
|
||||
messages: msgSvc,
|
||||
aliceID: alice.ID,
|
||||
bobID: bob.ID,
|
||||
carolID: carol.ID,
|
||||
chatID: chat.ID,
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_OK(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
m, err := f.messages.Send(ctx, f.aliceID, f.chatID, "Привет, Боб!")
|
||||
if err != nil {
|
||||
t.Fatalf("Send failed: %v", err)
|
||||
}
|
||||
if m.Text != "Привет, Боб!" {
|
||||
t.Errorf("text mismatch: got %q", m.Text)
|
||||
}
|
||||
if m.SenderID != f.aliceID {
|
||||
t.Errorf("sender mismatch: got %q", m.SenderID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_Stranger(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.messages.Send(ctx, f.carolID, f.chatID, "Hello")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_NonexistentChat(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := f.messages.Send(ctx, f.aliceID, "nonexistent-chat", "Hello")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_EmptyText(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []string{"", " ", "\t\n"}
|
||||
for _, text := range cases {
|
||||
_, err := f.messages.Send(ctx, f.aliceID, f.chatID, text)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("text %q: expected ErrInvalidInput, got %v", text, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Send_TooLongText(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
text := strings.Repeat("я", 4001)
|
||||
_, err := f.messages.Send(ctx, f.aliceID, f.chatID, text)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput for 4001 code points, got %v", err)
|
||||
}
|
||||
|
||||
text = strings.Repeat("я", 4000)
|
||||
if _, err := f.messages.Send(ctx, f.aliceID, f.chatID, text); err != nil {
|
||||
t.Fatalf("expected OK for 4000 code points, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_OK(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, f.chatID, "one")
|
||||
_, _ = f.messages.Send(ctx, f.bobID, f.chatID, "two")
|
||||
|
||||
items, next, err := f.messages.List(ctx, f.aliceID, f.chatID, "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("expected 2 messages, got %d", len(items))
|
||||
}
|
||||
if next != "" {
|
||||
t.Errorf("expected empty cursor, got %q", next)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_Stranger(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _, err := f.messages.List(ctx, f.carolID, f.chatID, "", 10)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for stranger, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_InvalidLimit(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, limit := range []int{0, -1, 101} {
|
||||
_, _, err := f.messages.List(ctx, f.aliceID, f.chatID, "", limit)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("limit %d: expected ErrInvalidInput, got %v", limit, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_List_CursorFromAnotherChat(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chat2, err := f.chats.Create(ctx, f.aliceID, "Other", []string{f.aliceID, f.carolID})
|
||||
if err != nil {
|
||||
t.Fatalf("create second chat: %v", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, f.chatID, "in chat1")
|
||||
_, _ = f.messages.Send(ctx, f.aliceID, chat2.ID, "in chat2")
|
||||
}
|
||||
|
||||
// Получаем курсор из первого чата.
|
||||
_, cursor, err := f.messages.List(ctx, f.aliceID, f.chatID, "", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("List chat1 failed: %v", err)
|
||||
}
|
||||
if cursor == "" {
|
||||
t.Fatal("expected non-empty cursor")
|
||||
}
|
||||
|
||||
// Пытаемся использовать его во втором чате.
|
||||
_, _, err = f.messages.List(ctx, f.aliceID, chat2.ID, cursor, 2)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("expected ErrInvalidInput for cursor from another chat, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageService_Pagination_AllMessages(t *testing.T) {
|
||||
f := newMessageFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
const total = 10
|
||||
for i := 0; i < total; i++ {
|
||||
if _, err := f.messages.Send(ctx, f.aliceID, f.chatID, "msg"); err != nil {
|
||||
t.Fatalf("send %d failed: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
cursor := ""
|
||||
pages := 0
|
||||
for {
|
||||
items, next, err := f.messages.List(ctx, f.aliceID, f.chatID, cursor, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("List failed: %v", err)
|
||||
}
|
||||
for _, m := range items {
|
||||
if seen[m.ID] {
|
||||
t.Errorf("duplicate message: %q", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
}
|
||||
pages++
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
if pages > 10 {
|
||||
t.Fatal("too many pages")
|
||||
}
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Errorf("expected %d unique messages, got %d", total, len(seen))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Параметры Argon2id. Значения — стандартные рекомендации OWASP для интерактивного логина.
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024 // 64 MiB
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// ErrPasswordMismatch возвращается, если пароль не совпадает с хешем.
|
||||
// Не путать с "неверный формат хеша" — это тоже ошибка, но другая.
|
||||
var ErrPasswordMismatch = errors.New("password mismatch")
|
||||
|
||||
// hashPassword хеширует пароль через Argon2id и возвращает строку в формате
|
||||
// $argon2id$v=19$m=65536,t=1,p=4$<salt>$<hash>.
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
// verifyPassword сравнивает пароль с хешем, возвращённым hashPassword.
|
||||
// Возвращает ErrPasswordMismatch, если пароль не подходит.
|
||||
func verifyPassword(password, encoded string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return fmt.Errorf("invalid hash format")
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("incompatible version: %d", version)
|
||||
}
|
||||
|
||||
var mem uint32
|
||||
var iters uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
|
||||
return fmt.Errorf("parse params: %w", err)
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode hash: %w", err)
|
||||
}
|
||||
|
||||
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return ErrPasswordMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(users repository.UserRepository) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
// Register создаёт нового пользователя. Возвращает ErrInvalidInput при невалидных
|
||||
// данных и ErrConflict, если username занят.
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !validateUsername(username) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validateDisplayName(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validatePassword(password) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetByID возвращает пользователя. Возвращает ErrNotFound, если такого нет.
|
||||
// Используется middleware аутентификации для проверки X-User-Id.
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
u, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab2/internal/repository/memory"
|
||||
)
|
||||
|
||||
func newUserService() *UserService {
|
||||
return NewUserService(memory.NewUserRepository())
|
||||
}
|
||||
|
||||
func TestUserService_Register_OK(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
u, err := svc.Register(ctx, "alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("Register failed: %v", err)
|
||||
}
|
||||
if u.ID == "" {
|
||||
t.Error("expected non-empty ID")
|
||||
}
|
||||
if u.Username != "alice" {
|
||||
t.Errorf("username mismatch: got %q", u.Username)
|
||||
}
|
||||
if u.CreatedAt.IsZero() {
|
||||
t.Error("expected non-zero CreatedAt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_InvalidUsername(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
username string
|
||||
}{
|
||||
{"too short", "ab"},
|
||||
{"too long", strings.Repeat("a", 33)},
|
||||
{"uppercase", "Alice"},
|
||||
{"with dash", "al-ice"},
|
||||
{"with space", "al ice"},
|
||||
{"empty", ""},
|
||||
{"only spaces", " "},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := svc.Register(ctx, tc.username, "Test")
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_InvalidDisplayName(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
displayName string
|
||||
}{
|
||||
{"empty", ""},
|
||||
{"only spaces", " "},
|
||||
{"too long", strings.Repeat("я", 101)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := svc.Register(ctx, "alice", tc.displayName)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("expected ErrInvalidInput, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_UnicodeDisplayName_OK(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
// 100 code points ровно — должно пройти.
|
||||
name := strings.Repeat("я", 100)
|
||||
if _, err := svc.Register(ctx, "alice", name); err != nil {
|
||||
t.Fatalf("expected OK for 100 code points, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_Register_DuplicateUsername(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.Register(ctx, "alice", "Алиса"); err != nil {
|
||||
t.Fatalf("first Register failed: %v", err)
|
||||
}
|
||||
_, err := svc.Register(ctx, "alice", "Another")
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("expected ErrConflict, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserService_GetByID_NotFound(t *testing.T) {
|
||||
svc := newUserService()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.GetByID(ctx, "nonexistent")
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func validatePassword(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
// validateUsername проверяет формат username по README: строго [a-z0-9_]{3,32}.
|
||||
func validateUsername(s string) bool {
|
||||
return usernameRe.MatchString(s)
|
||||
}
|
||||
|
||||
// validateDisplayName проверяет display_name: 1–100 Unicode code points,
|
||||
// не состоит только из пробельных символов.
|
||||
func validateDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateTitle проверяет title чата: 1–100 code points, не только пробелы.
|
||||
func validateTitle(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateText проверяет text сообщения: 1–4000 code points, не только пробелы.
|
||||
// В lab4 появится возможность отправить пустой text, если есть attachment_ids.
|
||||
func validateText(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 4000
|
||||
}
|
||||
Reference in New Issue
Block a user