From 3f69970b05b8031822b4ff2c633b645c741fb5ec Mon Sep 17 00:00:00 2001 From: d1frend Date: Tue, 20 Oct 2026 21:44:59 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B8=D0=BB=20=D0=BF=D1=80=D0=B8=D0=BB=D0=BE=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B0=20domain=20application=20adap?= =?UTF-8?q?ters=20=D0=B8=20HTTP=20DTO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 1 + REPORT.md | 49 +++- cmd/server/main.go | 29 +- compose.yaml | 4 + .../cache/repository.go} | 19 +- .../cache/repository_test.go} | 16 +- internal/adapter/memory/errors.go | 8 + .../memory/repository.go} | 17 +- .../memory.go => adapter/memory/store.go} | 88 +----- .../postgres/chats.go} | 52 +--- internal/adapter/postgres/contract.go | 5 + internal/adapter/postgres/errors.go | 8 + .../postgres/messages.go} | 56 +--- .../postgres/sessions.go} | 2 +- .../postgres.go => adapter/postgres/store.go} | 2 +- .../postgres/users.go} | 2 +- .../chat.go => adapter/redis/chat_cache.go} | 14 +- internal/application/chats.go | 55 ++++ internal/application/commands.go | 24 ++ internal/application/cursor.go | 121 +++++++++ internal/application/cursor_test.go | 70 +++++ internal/application/errors.go | 10 + internal/application/messages.go | 52 ++++ internal/application/ports.go | 37 +++ internal/application/service.go | 31 +++ internal/application/sessions.go | 57 ++++ internal/application/users.go | 29 ++ internal/config/config.go | 18 +- internal/domain/chat.go | 21 ++ internal/domain/errors.go | 8 + internal/domain/message.go | 22 ++ internal/domain/models.go | 256 ------------------ internal/domain/session.go | 10 + internal/domain/user.go | 11 + internal/domain/validation.go | 77 ++++++ internal/store/errors.go | 9 - internal/store/repository.go | 80 ------ internal/transport/http/dto/chat.go | 38 +++ internal/transport/http/dto/message.go | 39 +++ internal/transport/http/dto/session.go | 21 ++ internal/transport/http/dto/user.go | 26 ++ internal/transport/http/handlers/chats.go | 168 ------------ .../transport/http/handlers/create_chat.go | 44 +++ .../transport/http/handlers/create_message.go | 50 ++++ .../transport/http/handlers/delete_session.go | 19 ++ internal/transport/http/handlers/get_chat.go | 36 +++ internal/transport/http/handlers/get_me.go | 15 + internal/transport/http/handlers/handler.go | 16 +- .../transport/http/handlers/list_chats.go | 32 +++ .../transport/http/handlers/list_messages.go | 45 +++ internal/transport/http/handlers/messages.go | 159 ----------- .../transport/http/handlers/pagination.go | 29 ++ internal/transport/http/handlers/sessions.go | 105 +------ internal/transport/http/handlers/users.go | 70 +---- internal/transport/http/middleware/auth.go | 16 +- student_tests/application_helper_test.go | 32 +++ student_tests/auth_test.go | 24 +- student_tests/cursor_concurrency_test.go | 23 +- student_tests/messenger_test.go | 34 ++- 59 files changed, 1324 insertions(+), 1087 deletions(-) rename internal/{store/cached_repository.go => adapter/cache/repository.go} (84%) rename internal/{store/cached_repository_test.go => adapter/cache/repository_test.go} (92%) create mode 100644 internal/adapter/memory/errors.go rename internal/{store/memory_repository.go => adapter/memory/repository.go} (93%) rename internal/{store/memory.go => adapter/memory/store.go} (78%) rename internal/{store/postgres_chats.go => adapter/postgres/chats.go} (85%) create mode 100644 internal/adapter/postgres/contract.go create mode 100644 internal/adapter/postgres/errors.go rename internal/{store/postgres_messages.go => adapter/postgres/messages.go} (74%) rename internal/{store/postgres_sessions.go => adapter/postgres/sessions.go} (99%) rename internal/{store/postgres.go => adapter/postgres/store.go} (97%) rename internal/{store/postgres_users.go => adapter/postgres/users.go} (99%) rename internal/{cache/chat.go => adapter/redis/chat_cache.go} (93%) create mode 100644 internal/application/chats.go create mode 100644 internal/application/commands.go create mode 100644 internal/application/cursor.go create mode 100644 internal/application/cursor_test.go create mode 100644 internal/application/errors.go create mode 100644 internal/application/messages.go create mode 100644 internal/application/ports.go create mode 100644 internal/application/service.go create mode 100644 internal/application/sessions.go create mode 100644 internal/application/users.go create mode 100644 internal/domain/chat.go create mode 100644 internal/domain/errors.go create mode 100644 internal/domain/message.go delete mode 100644 internal/domain/models.go create mode 100644 internal/domain/session.go create mode 100644 internal/domain/user.go create mode 100644 internal/domain/validation.go delete mode 100644 internal/store/errors.go delete mode 100644 internal/store/repository.go create mode 100644 internal/transport/http/dto/chat.go create mode 100644 internal/transport/http/dto/message.go create mode 100644 internal/transport/http/dto/session.go create mode 100644 internal/transport/http/dto/user.go delete mode 100644 internal/transport/http/handlers/chats.go create mode 100644 internal/transport/http/handlers/create_chat.go create mode 100644 internal/transport/http/handlers/create_message.go create mode 100644 internal/transport/http/handlers/delete_session.go create mode 100644 internal/transport/http/handlers/get_chat.go create mode 100644 internal/transport/http/handlers/get_me.go create mode 100644 internal/transport/http/handlers/list_chats.go create mode 100644 internal/transport/http/handlers/list_messages.go delete mode 100644 internal/transport/http/handlers/messages.go create mode 100644 internal/transport/http/handlers/pagination.go create mode 100644 student_tests/application_helper_test.go diff --git a/.env.example b/.env.example index b5f876f..4e64314 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,7 @@ POSTGRES_DB=messenger SESSION_TTL_SECONDS=3600 SESSION_STORE=postgres +CURSOR_SIGNING_KEY_FILE=/run/secrets/cursor_signing_key API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 diff --git a/REPORT.md b/REPORT.md index c267900..70ab308 100644 --- a/REPORT.md +++ b/REPORT.md @@ -7,11 +7,56 @@ ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Локальные секреты не входят в Git. Перед первым запуском оператор создаёт каталог +`secrets/`, генерирует пароль PostgreSQL и общий для всех API-реплик ключ подписи +курсоров длиной не менее 32 байт. Значение `database_url` должно использовать имя +Compose-сервиса `postgres`, а не `localhost`. Пример генерации синтетических +локальных значений без их вывода в терминал: + +```bash +mkdir -p secrets +openssl rand -hex 32 > secrets/postgres_password.txt +openssl rand -base64 48 > secrets/cursor_signing_key.txt +printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' \ + "$(cat secrets/postgres_password.txt)" > secrets/database_url.txt +chmod 600 secrets/*.txt +cp .env.example .env +``` + +Полная последовательность запуска, проверки LB и безопасной остановки будет +зафиксирована после завершения новой Compose-топологии lab3. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Перенесённая основа lab2 разделена на явные слои: + +- `internal/domain` — сущности и бизнес-инварианты без HTTP/JSON-зависимостей; +- `internal/application` — сценарии, команды и узкие порты репозиториев; +- `internal/adapter/postgres`, `memory`, `redis`, `cache` — реализации внешних + зависимостей и кэширующий декоратор; +- `internal/transport/http/dto` — wire-модели HTTP-контракта и преобразование + domain → response DTO; +- `internal/transport/http/handlers` — тонкие обработчики, по одному + нетривиальному endpoint на файл; +- `cmd/server` — composition root, единственное место сборки зависимостей. + +PostgreSQL остаётся источником истины для пользователей, сессий, чатов и +сообщений. Redis содержит только удаляемую производную копию неизменяемых данных +чата; его отказ не делает API неготовым и не отменяет подтверждённую запись в +PostgreSQL. + +Пагинационный курсор теперь формируется в application-слое из канонических +полей границы `(created_at, id, scope_id)` и подписывается HMAC-SHA-256. Подпись +не скрывает payload, но обнаруживает подмену. В scope входит пользователь для +списка чатов и чат для истории сообщений. Все реплики обязаны использовать один +`CURSOR_SIGNING_KEY` или `CURSOR_SIGNING_KEY_FILE`; в Compose используется Docker +secret `cursor_signing_key`. Репозитории получают только уже проверенную +типизированную границу и ничего не знают о формате HTTP-курсора. + +`.env.example` перечисляет реально читаемые приложением параметры PostgreSQL, +пула, readiness/shutdown, Redis-кэша и ключа курсора. `API_REPLICAS` и +`IDEMPOTENCY_TTL_SECONDS` зарезервированы для следующих этапов lab3. Секретных +значений в шаблоне нет: там указаны только пути внутри контейнера. ## Доказательства критериев diff --git a/cmd/server/main.go b/cmd/server/main.go index 6fea252..342f6d0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -10,10 +10,12 @@ import ( "syscall" "time" - applicationCache "mtusi2026lab3/internal/cache" + cacheadapter "mtusi2026lab3/internal/adapter/cache" + "mtusi2026lab3/internal/adapter/postgres" + redisadapter "mtusi2026lab3/internal/adapter/redis" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/config" "mtusi2026lab3/internal/database" - "mtusi2026lab3/internal/store" "mtusi2026lab3/internal/transport/http/handlers" "mtusi2026lab3/internal/transport/http/middleware" ) @@ -37,15 +39,15 @@ func main() { } defer databasePool.Close() - postgresStore := store.NewPostgreSQLStore( + postgresStore := postgres.NewPostgreSQLStore( databasePool, cfg.DatabaseQueryTimeout, ) - var applicationStore store.Repository = postgresStore + var applicationStore application.Repository = postgresStore if cfg.RedisURL != "" { - redisChatCache, cacheError := applicationCache.NewRedisChatCache( + redisChatCache, cacheError := redisadapter.NewRedisChatCache( cfg.RedisURL, cfg.RedisCacheTTL, cfg.RedisOperationTimeout, @@ -71,20 +73,29 @@ func main() { } cacheCancel() - applicationStore = store.NewCachedRepository( + applicationStore = cacheadapter.NewCachedRepository( postgresStore, redisChatCache, log.Default(), ) } + cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey) + if err != nil { + log.Fatalf("[FATAL] Invalid cursor configuration: %v", err) + } + + service, err := application.NewService(applicationStore, cursorCodec, cfg.SessionTTL) + if err != nil { + log.Fatalf("[FATAL] Application initialization failed: %v", err) + } + handler := handlers.NewHandler( - applicationStore, + service, handlers.WithReadiness( databasePool, cfg.ReadinessTimeout, ), - handlers.WithSessionTTL(cfg.SessionTTL), ) mux := http.NewServeMux() @@ -100,7 +111,7 @@ func main() { mux.HandleFunc("POST /api/v1/users", handler.CreateUser) requireAuth := func(next http.HandlerFunc) http.HandlerFunc { - return middleware.RequireAuth(postgresStore, next) + return middleware.RequireAuth(service, next) } mux.HandleFunc( diff --git a/compose.yaml b/compose.yaml index 5d8c855..55036c4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -73,6 +73,7 @@ services: SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_STORE: ${SESSION_STORE:-postgres} + CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key} CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} CACHE_TTL: ${CACHE_TTL:-5m} @@ -93,6 +94,7 @@ services: SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s} secrets: - database_url + - cursor_signing_key ports: - "${APP_PORT:-8080}:${APP_PORT:-8080}" depends_on: @@ -158,3 +160,5 @@ secrets: file: ./secrets/postgres_password.txt database_url: file: ./secrets/database_url.txt + cursor_signing_key: + file: ./secrets/cursor_signing_key.txt diff --git a/internal/store/cached_repository.go b/internal/adapter/cache/repository.go similarity index 84% rename from internal/store/cached_repository.go rename to internal/adapter/cache/repository.go index 10d3f30..213ae72 100644 --- a/internal/store/cached_repository.go +++ b/internal/adapter/cache/repository.go @@ -1,25 +1,26 @@ -package store +package cache import ( "context" "errors" "log" - applicationCache "mtusi2026lab3/internal/cache" + "mtusi2026lab3/internal/adapter/redis" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/domain" ) // CachedRepository декорирует основной Repository. Все операции, кроме чтения // и создания чата, автоматически делегируются встроенному Repository. type CachedRepository struct { - Repository - chatCache applicationCache.ChatCache + application.Repository + chatCache redis.ChatCache logger *log.Logger } func NewCachedRepository( - repository Repository, - chatCache applicationCache.ChatCache, + repository application.Repository, + chatCache redis.ChatCache, logger *log.Logger, ) *CachedRepository { if logger == nil { @@ -60,13 +61,13 @@ func (r *CachedRepository) GetChatByID( chat, err := r.chatCache.Get(ctx, chatID) if err == nil { if !containsMember(chat.MemberIDs, callerID) { - return domain.Chat{}, ErrNotFound + return domain.Chat{}, domain.ErrNotFound } return chat, nil } - shouldFillCache := errors.Is(err, applicationCache.ErrMiss) + shouldFillCache := errors.Is(err, redis.ErrMiss) if !shouldFillCache { r.logger.Printf("[WARN] Redis chat cache read failed: %v", err) } @@ -95,4 +96,4 @@ func containsMember(memberIDs []string, callerID string) bool { return false } -var _ Repository = (*CachedRepository)(nil) +var _ application.Repository = (*CachedRepository)(nil) diff --git a/internal/store/cached_repository_test.go b/internal/adapter/cache/repository_test.go similarity index 92% rename from internal/store/cached_repository_test.go rename to internal/adapter/cache/repository_test.go index ba13f50..a1c313d 100644 --- a/internal/store/cached_repository_test.go +++ b/internal/adapter/cache/repository_test.go @@ -1,4 +1,4 @@ -package store +package cache import ( "context" @@ -7,7 +7,9 @@ import ( "log" "testing" - applicationCache "mtusi2026lab3/internal/cache" + "mtusi2026lab3/internal/adapter/memory" + "mtusi2026lab3/internal/adapter/redis" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/domain" ) @@ -28,7 +30,7 @@ func (c *fakeChatCache) Get( chat, exists := c.chats[chatID] if !exists { - return domain.Chat{}, applicationCache.ErrMiss + return domain.Chat{}, redis.ErrMiss } return chat, nil @@ -48,7 +50,7 @@ func (c *fakeChatCache) Set( } type countingRepository struct { - Repository + application.Repository getChatCalls int } @@ -66,7 +68,7 @@ func cachedRepositoryFixture( ) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) { t.Helper() - legacy := NewMemoryStore() + legacy := memory.NewMemoryStore() member, err := legacy.CreateUser("cache_member", "Участник") if err != nil { t.Fatalf("create member: %v", err) @@ -81,7 +83,7 @@ func cachedRepositoryFixture( } repository := &countingRepository{ - Repository: NewMemoryRepository(legacy), + Repository: memory.NewMemoryRepository(legacy), } chatCache := &fakeChatCache{ chats: make(map[string]domain.Chat), @@ -150,7 +152,7 @@ func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) { ) _, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID) - if !errors.Is(err, ErrNotFound) { + if !errors.Is(err, domain.ErrNotFound) { t.Fatalf("expected ErrNotFound for outsider, got %v", err) } if repository.getChatCalls != 0 { diff --git a/internal/adapter/memory/errors.go b/internal/adapter/memory/errors.go new file mode 100644 index 0000000..423c43a --- /dev/null +++ b/internal/adapter/memory/errors.go @@ -0,0 +1,8 @@ +package memory + +import "mtusi2026lab3/internal/domain" + +var ( + ErrNotFound = domain.ErrNotFound + ErrConflict = domain.ErrConflict +) diff --git a/internal/store/memory_repository.go b/internal/adapter/memory/repository.go similarity index 93% rename from internal/store/memory_repository.go rename to internal/adapter/memory/repository.go index 72c330f..ad11c60 100644 --- a/internal/store/memory_repository.go +++ b/internal/adapter/memory/repository.go @@ -1,4 +1,4 @@ -package store +package memory import ( "context" @@ -6,6 +6,7 @@ import ( "sync" "time" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/domain" ) @@ -119,10 +120,10 @@ func (r *MemoryRepository) GetChatsForUser( ctx context.Context, userID string, limit int, - cursor string, -) (domain.ChatPage, error) { + cursor *domain.ChatCursor, +) ([]domain.Chat, bool, error) { if err := ctx.Err(); err != nil { - return domain.ChatPage{}, err + return nil, false, err } return r.legacy.GetChatsForUser(userID, limit, cursor) @@ -146,10 +147,10 @@ func (r *MemoryRepository) GetMessages( chatID string, callerID string, limit int, - cursor string, -) (domain.MessagePage, error) { + cursor *domain.MessageCursor, +) ([]domain.Message, bool, error) { if err := ctx.Err(); err != nil { - return domain.MessagePage{}, err + return nil, false, err } return r.legacy.GetMessages( @@ -244,4 +245,4 @@ func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) { return key, nil } -var _ Repository = (*MemoryRepository)(nil) +var _ application.Repository = (*MemoryRepository)(nil) diff --git a/internal/store/memory.go b/internal/adapter/memory/store.go similarity index 78% rename from internal/store/memory.go rename to internal/adapter/memory/store.go index 405efd1..9a53080 100644 --- a/internal/store/memory.go +++ b/internal/adapter/memory/store.go @@ -1,4 +1,4 @@ -package store +package memory import ( "fmt" @@ -124,20 +124,8 @@ func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) func (s *MemoryStore) GetChatsForUser( userID string, limit int, - cursorStr string, -) (domain.ChatPage, error) { - var cursorData *domain.ChatCursorData - - if cursorStr != "" { - decodedCursor, err := domain.DecodeChatCursor(cursorStr, userID) - if err != nil { - return domain.ChatPage{}, - fmt.Errorf("%w: %v", ErrInvalidCursor, err) - } - - cursorData = decodedCursor - } - + cursorData *domain.ChatCursor, +) ([]domain.Chat, bool, error) { s.mu.RLock() defer s.mu.RUnlock() @@ -175,13 +163,8 @@ func (s *MemoryStore) GetChatsForUser( }) } - page := domain.ChatPage{ - Items: make([]domain.Chat, 0), - NextCursor: nil, - } - if start >= len(chats) { - return page, nil + return make([]domain.Chat, 0), false, nil } end := start + limit @@ -189,20 +172,9 @@ func (s *MemoryStore) GetChatsForUser( end = len(chats) } - page.Items = make([]domain.Chat, end-start) - copy(page.Items, chats[start:end]) - - if end < len(chats) { - lastChat := page.Items[len(page.Items)-1] - nextCursor := domain.EncodeChatCursor( - lastChat.CreatedAt, - lastChat.ID, - userID, - ) - page.NextCursor = &nextCursor - } - - return page, nil + items := make([]domain.Chat, end-start) + copy(items, chats[start:end]) + return items, end < len(chats), nil } // ---Сообщения--- @@ -259,14 +231,14 @@ func (s *MemoryStore) CreateMessage( func (s *MemoryStore) GetMessages( chatID, callerID string, limit int, - cursorStr string, -) (domain.MessagePage, error) { + cursorData *domain.MessageCursor, +) ([]domain.Message, bool, error) { s.mu.RLock() defer s.mu.RUnlock() chat, exists := s.chatsByID[chatID] if !exists { - return domain.MessagePage{}, ErrNotFound + return nil, false, ErrNotFound } isMember := false @@ -277,21 +249,7 @@ func (s *MemoryStore) GetMessages( } } if !isMember { - return domain.MessagePage{}, ErrNotFound - } - - var cursorData *domain.CursorData - if cursorStr != "" { - decodedCursor, err := domain.DecodeCursor(cursorStr, chatID) - if err != nil { - return domain.MessagePage{}, fmt.Errorf( - "%w: %v", - ErrInvalidCursor, - err, - ) - } - - cursorData = decodedCursor + return nil, false, ErrNotFound } messages := s.messagesByChatID[chatID] @@ -313,13 +271,8 @@ func (s *MemoryStore) GetMessages( }) } - page := domain.MessagePage{ - Items: make([]domain.Message, 0), - NextCursor: nil, - } - if start >= len(messages) { - return page, nil + return make([]domain.Message, 0), false, nil } end := len(messages) @@ -328,18 +281,7 @@ func (s *MemoryStore) GetMessages( } // копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез - page.Items = make([]domain.Message, end-start) - copy(page.Items, messages[start:end]) - - if end < len(messages) { - lastItem := page.Items[len(page.Items)-1] - nextCursor := domain.EncodeCursor( - lastItem.CreatedAt, - lastItem.ID, - chatID, - ) - page.NextCursor = &nextCursor - } - - return page, nil + items := make([]domain.Message, end-start) + copy(items, messages[start:end]) + return items, end < len(messages), nil } diff --git a/internal/store/postgres_chats.go b/internal/adapter/postgres/chats.go similarity index 85% rename from internal/store/postgres_chats.go rename to internal/adapter/postgres/chats.go index 8f5b568..afb30ba 100644 --- a/internal/store/postgres_chats.go +++ b/internal/adapter/postgres/chats.go @@ -1,4 +1,4 @@ -package store +package postgres import ( "context" @@ -160,26 +160,8 @@ func (s *PostgreSQLStore) GetChatsForUser( ctx context.Context, userID string, limit int, - cursorString string, -) (domain.ChatPage, error) { - var cursor *domain.ChatCursorData - - if cursorString != "" { - decodedCursor, err := domain.DecodeChatCursor( - cursorString, - userID, - ) - if err != nil { - return domain.ChatPage{}, fmt.Errorf( - "%w: %v", - ErrInvalidCursor, - err, - ) - } - - cursor = decodedCursor - } - + cursor *domain.ChatCursor, +) ([]domain.Chat, bool, error) { queryContext, cancel := s.withTimeout(ctx) defer cancel() @@ -254,16 +236,14 @@ func (s *PostgreSQLStore) GetChatsForUser( } if err != nil { - return domain.ChatPage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "query chats for user: %w", err, ) } defer rows.Close() - page := domain.ChatPage{ - Items: make([]domain.Chat, 0, limit), - } + items := make([]domain.Chat, 0, limit+1) for rows.Next() { var chat domain.Chat @@ -274,33 +254,25 @@ func (s *PostgreSQLStore) GetChatsForUser( &chat.CreatedAt, &chat.MemberIDs, ); err != nil { - return domain.ChatPage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "scan chat page: %w", err, ) } - page.Items = append(page.Items, chat) + items = append(items, chat) } if err := rows.Err(); err != nil { - return domain.ChatPage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "iterate chat page: %w", err, ) } - if len(page.Items) > limit { - page.Items = page.Items[:limit] - - lastChat := page.Items[len(page.Items)-1] - nextCursor := domain.EncodeChatCursor( - lastChat.CreatedAt, - lastChat.ID, - userID, - ) - page.NextCursor = &nextCursor + hasMore := len(items) > limit + if hasMore { + items = items[:limit] } - - return page, nil + return items, hasMore, nil } diff --git a/internal/adapter/postgres/contract.go b/internal/adapter/postgres/contract.go new file mode 100644 index 0000000..285d65f --- /dev/null +++ b/internal/adapter/postgres/contract.go @@ -0,0 +1,5 @@ +package postgres + +import "mtusi2026lab3/internal/application" + +var _ application.Repository = (*PostgreSQLStore)(nil) diff --git a/internal/adapter/postgres/errors.go b/internal/adapter/postgres/errors.go new file mode 100644 index 0000000..e91259a --- /dev/null +++ b/internal/adapter/postgres/errors.go @@ -0,0 +1,8 @@ +package postgres + +import "mtusi2026lab3/internal/domain" + +var ( + ErrNotFound = domain.ErrNotFound + ErrConflict = domain.ErrConflict +) diff --git a/internal/store/postgres_messages.go b/internal/adapter/postgres/messages.go similarity index 74% rename from internal/store/postgres_messages.go rename to internal/adapter/postgres/messages.go index fda090c..f988e2a 100644 --- a/internal/store/postgres_messages.go +++ b/internal/adapter/postgres/messages.go @@ -1,4 +1,4 @@ -package store +package postgres import ( "context" @@ -70,8 +70,8 @@ func (s *PostgreSQLStore) GetMessages( chatID string, callerID string, limit int, - cursorString string, -) (domain.MessagePage, error) { + cursor *domain.MessageCursor, +) ([]domain.Message, bool, error) { queryContext, cancel := s.withTimeout(ctx) defer cancel() @@ -91,32 +91,14 @@ func (s *PostgreSQLStore) GetMessages( callerID, ).Scan(&isMember) if err != nil { - return domain.MessagePage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "check chat membership: %w", err, ) } if !isMember { - return domain.MessagePage{}, ErrNotFound - } - - var cursor *domain.CursorData - - if cursorString != "" { - decodedCursor, err := domain.DecodeCursor( - cursorString, - chatID, - ) - if err != nil { - return domain.MessagePage{}, fmt.Errorf( - "%w: %v", - ErrInvalidCursor, - err, - ) - } - - cursor = decodedCursor + return nil, false, ErrNotFound } var rows pgx.Rows @@ -167,16 +149,14 @@ func (s *PostgreSQLStore) GetMessages( } if err != nil { - return domain.MessagePage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "query messages: %w", err, ) } defer rows.Close() - page := domain.MessagePage{ - Items: make([]domain.Message, 0, limit), - } + items := make([]domain.Message, 0, limit+1) for rows.Next() { var message domain.Message @@ -188,33 +168,25 @@ func (s *PostgreSQLStore) GetMessages( &message.Text, &message.CreatedAt, ); err != nil { - return domain.MessagePage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "scan message page: %w", err, ) } - page.Items = append(page.Items, message) + items = append(items, message) } if err := rows.Err(); err != nil { - return domain.MessagePage{}, fmt.Errorf( + return nil, false, fmt.Errorf( "iterate message page: %w", err, ) } - if len(page.Items) > limit { - page.Items = page.Items[:limit] - - lastMessage := page.Items[len(page.Items)-1] - nextCursor := domain.EncodeCursor( - lastMessage.CreatedAt, - lastMessage.ID, - chatID, - ) - page.NextCursor = &nextCursor + hasMore := len(items) > limit + if hasMore { + items = items[:limit] } - - return page, nil + return items, hasMore, nil } diff --git a/internal/store/postgres_sessions.go b/internal/adapter/postgres/sessions.go similarity index 99% rename from internal/store/postgres_sessions.go rename to internal/adapter/postgres/sessions.go index 050b0e1..4c59165 100644 --- a/internal/store/postgres_sessions.go +++ b/internal/adapter/postgres/sessions.go @@ -1,4 +1,4 @@ -package store +package postgres import ( "context" diff --git a/internal/store/postgres.go b/internal/adapter/postgres/store.go similarity index 97% rename from internal/store/postgres.go rename to internal/adapter/postgres/store.go index a40f5ad..66a9e8e 100644 --- a/internal/store/postgres.go +++ b/internal/adapter/postgres/store.go @@ -1,4 +1,4 @@ -package store +package postgres import ( "context" diff --git a/internal/store/postgres_users.go b/internal/adapter/postgres/users.go similarity index 99% rename from internal/store/postgres_users.go rename to internal/adapter/postgres/users.go index 3bf9da4..a0d0950 100644 --- a/internal/store/postgres_users.go +++ b/internal/adapter/postgres/users.go @@ -1,4 +1,4 @@ -package store +package postgres import ( "context" diff --git a/internal/cache/chat.go b/internal/adapter/redis/chat_cache.go similarity index 93% rename from internal/cache/chat.go rename to internal/adapter/redis/chat_cache.go index 780abae..044d4ec 100644 --- a/internal/cache/chat.go +++ b/internal/adapter/redis/chat_cache.go @@ -1,4 +1,4 @@ -package cache +package redis import ( "context" @@ -11,10 +11,10 @@ import ( "mtusi2026lab3/internal/domain" "github.com/google/uuid" - "github.com/redis/go-redis/v9" + goredis "github.com/redis/go-redis/v9" ) -const chatKeyPrefix = "chat:v1:" +const chatKeyPrefix = "chat:v2:" var ErrMiss = errors.New("cache miss") @@ -26,7 +26,7 @@ type ChatCache interface { } type RedisChatCache struct { - client *redis.Client + client *goredis.Client ttl time.Duration operationTimeout time.Duration } @@ -37,7 +37,7 @@ func NewRedisChatCache( operationTimeout time.Duration, poolSize int, ) (*RedisChatCache, error) { - options, err := redis.ParseURL(strings.TrimSpace(redisURL)) + options, err := goredis.ParseURL(strings.TrimSpace(redisURL)) if err != nil { return nil, fmt.Errorf("parse Redis URL: %w", err) } @@ -50,7 +50,7 @@ func NewRedisChatCache( options.MaxRetries = -1 return &RedisChatCache{ - client: redis.NewClient(options), + client: goredis.NewClient(options), ttl: ttl, operationTimeout: operationTimeout, }, nil @@ -82,7 +82,7 @@ func (c *RedisChatCache) Get( operationContext, chatKey(chatID), ).Bytes() - if errors.Is(err, redis.Nil) { + if errors.Is(err, goredis.Nil) { return domain.Chat{}, ErrMiss } if err != nil { diff --git a/internal/application/chats.go b/internal/application/chats.go new file mode 100644 index 0000000..b25a524 --- /dev/null +++ b/internal/application/chats.go @@ -0,0 +1,55 @@ +package application + +import ( + "context" + "fmt" + + "mtusi2026lab3/internal/domain" +) + +func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) { + if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil { + return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + return s.repository.CreateChat(ctx, command.Title, command.MemberIDs) +} + +func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) { + return s.repository.GetChatByID(ctx, chatID, actorID) +} + +func (s *Service) ListChats( + ctx context.Context, + actorID string, + limit int, + cursorToken string, +) (domain.ChatPage, error) { + var cursor *domain.ChatCursor + if cursorToken != "" { + decoded, err := s.cursors.DecodeChat(cursorToken, actorID) + if err != nil { + return domain.ChatPage{}, ErrInvalidCursor + } + cursor = decoded + } + + items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor) + if err != nil { + return domain.ChatPage{}, err + } + page := domain.ChatPage{Items: items} + if page.Items == nil { + page.Items = make([]domain.Chat, 0) + } + if hasMore { + last := page.Items[len(page.Items)-1] + next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{ + CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID, + }) + if encodeErr != nil { + return domain.ChatPage{}, encodeErr + } + page.NextCursor = &next + } + return page, nil +} diff --git a/internal/application/commands.go b/internal/application/commands.go new file mode 100644 index 0000000..eeb369e --- /dev/null +++ b/internal/application/commands.go @@ -0,0 +1,24 @@ +package application + +type CreateUserCommand struct { + Username string + DisplayName string + Password string +} + +type CreateSessionCommand struct { + Username string + Password string +} + +type CreateChatCommand struct { + ActorID string + Title string + MemberIDs []string +} + +type SendMessageCommand struct { + ActorID string + ChatID string + Text string +} diff --git a/internal/application/cursor.go b/internal/application/cursor.go new file mode 100644 index 0000000..3edd0f3 --- /dev/null +++ b/internal/application/cursor.go @@ -0,0 +1,121 @@ +package application + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "strings" + "time" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" +) + +const cursorVersion = 1 + +type CursorCodec struct { + key []byte +} + +type cursorPayload struct { + Version int `json:"v"` + Kind string `json:"kind"` + CreatedAt string `json:"created_at"` + ID string `json:"id"` + ScopeID string `json:"scope_id"` +} + +func NewCursorCodec(key string) (*CursorCodec, error) { + if len(key) < 32 { + return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes") + } + return &CursorCodec{key: []byte(key)}, nil +} + +func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) { + return c.encode(cursorPayload{ + Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano), + ID: cursor.ChatID, ScopeID: cursor.UserID, + }) +} + +func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) { + payload, err := c.decode(token, "chat", expectedUserID) + if err != nil { + return nil, err + } + return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil +} + +func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) { + return c.encode(cursorPayload{ + Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano), + ID: cursor.MessageID, ScopeID: cursor.ChatID, + }) +} + +func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) { + payload, err := c.decode(token, "message", expectedChatID) + if err != nil { + return nil, err + } + return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil +} + +func (c *CursorCodec) encode(payload cursorPayload) (string, error) { + encodedPayload, err := json.Marshal(payload) + if err != nil { + return "", fmt.Errorf("encode cursor payload: %w", err) + } + mac := hmac.New(sha256.New, c.key) + _, _ = mac.Write(encodedPayload) + return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." + + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil +} + +type decodedCursor struct { + createdAt time.Time + id string + scopeID string +} + +func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) { + parts := strings.Split(token, ".") + if len(parts) != 2 { + return decodedCursor{}, ErrInvalidCursor + } + payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + signature, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + mac := hmac.New(sha256.New, c.key) + _, _ = mac.Write(payloadBytes) + if !hmac.Equal(signature, mac.Sum(nil)) { + return decodedCursor{}, ErrInvalidCursor + } + + var payload cursorPayload + if err = json.Unmarshal(payloadBytes, &payload); err != nil || + payload.Version != cursorVersion || payload.Kind != expectedKind || + payload.ScopeID != expectedScopeID { + return decodedCursor{}, ErrInvalidCursor + } + createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt) + if err != nil { + return decodedCursor{}, ErrInvalidCursor + } + if _, err = uuid.Parse(payload.ID); err != nil { + return decodedCursor{}, ErrInvalidCursor + } + if _, err = uuid.Parse(payload.ScopeID); err != nil { + return decodedCursor{}, ErrInvalidCursor + } + return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil +} diff --git a/internal/application/cursor_test.go b/internal/application/cursor_test.go new file mode 100644 index 0000000..aa4faba --- /dev/null +++ b/internal/application/cursor_test.go @@ -0,0 +1,70 @@ +package application + +import ( + "errors" + "testing" + "time" + + "mtusi2026lab3/internal/domain" +) + +const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes" + +func TestCursorCodecRoundTrip(t *testing.T) { + codec, err := NewCursorCodec(cursorTestKey) + if err != nil { + t.Fatal(err) + } + expected := domain.MessageCursor{ + CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC), + MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf", + ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf", + } + token, err := codec.EncodeMessage(expected) + if err != nil { + t.Fatal(err) + } + actual, err := codec.DecodeMessage(token, expected.ChatID) + if err != nil { + t.Fatal(err) + } + if *actual != expected { + t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected) + } +} + +func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) { + codec, err := NewCursorCodec(cursorTestKey) + if err != nil { + t.Fatal(err) + } + token, err := codec.EncodeChat(domain.ChatCursor{ + CreatedAt: time.Now().UTC(), + ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf", + UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf", + }) + if err != nil { + t.Fatal(err) + } + + replacement := "A" + if token[len(token)-1:] == replacement { + replacement = "B" + } + tampered := token[:len(token)-1] + replacement + if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err) + } + if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err) + } + if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) { + t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err) + } +} + +func TestCursorCodecRequiresStrongSharedKey(t *testing.T) { + if _, err := NewCursorCodec("too-short"); err == nil { + t.Fatal("expected short cursor signing key to be rejected") + } +} diff --git a/internal/application/errors.go b/internal/application/errors.go new file mode 100644 index 0000000..d042742 --- /dev/null +++ b/internal/application/errors.go @@ -0,0 +1,10 @@ +package application + +import "errors" + +var ( + ErrInvalidCursor = errors.New("invalid cursor") + ErrInvalidCredentials = errors.New("invalid credentials") + ErrInvalidInput = errors.New("invalid input") + ErrCredentialState = errors.New("invalid stored credential state") +) diff --git a/internal/application/messages.go b/internal/application/messages.go new file mode 100644 index 0000000..256fa45 --- /dev/null +++ b/internal/application/messages.go @@ -0,0 +1,52 @@ +package application + +import ( + "context" + "fmt" + + "mtusi2026lab3/internal/domain" +) + +func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) { + if err := domain.ValidateMessageText(command.Text); err != nil { + return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + return s.repository.CreateMessage(ctx, command.ChatID, command.ActorID, command.Text) +} + +func (s *Service) ListMessages( + ctx context.Context, + actorID string, + chatID string, + limit int, + cursorToken string, +) (domain.MessagePage, error) { + var cursor *domain.MessageCursor + if cursorToken != "" { + decoded, err := s.cursors.DecodeMessage(cursorToken, chatID) + if err != nil { + return domain.MessagePage{}, ErrInvalidCursor + } + cursor = decoded + } + + items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor) + if err != nil { + return domain.MessagePage{}, err + } + page := domain.MessagePage{Items: items} + if page.Items == nil { + page.Items = make([]domain.Message, 0) + } + if hasMore { + last := page.Items[len(page.Items)-1] + next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{ + CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID, + }) + if encodeErr != nil { + return domain.MessagePage{}, encodeErr + } + page.NextCursor = &next + } + return page, nil +} diff --git a/internal/application/ports.go b/internal/application/ports.go new file mode 100644 index 0000000..e866cd6 --- /dev/null +++ b/internal/application/ports.go @@ -0,0 +1,37 @@ +package application + +import ( + "context" + "time" + + "mtusi2026lab3/internal/domain" +) + +type UserRepository interface { + CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) + GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) +} + +type SessionRepository interface { + CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error + GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error) + DeleteSession(ctx context.Context, tokenHash []byte) error +} + +type ChatRepository interface { + CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error) + GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error) + GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error) +} + +type MessageRepository interface { + CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error) + GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error) +} + +type Repository interface { + UserRepository + SessionRepository + ChatRepository + MessageRepository +} diff --git a/internal/application/service.go b/internal/application/service.go new file mode 100644 index 0000000..35a3251 --- /dev/null +++ b/internal/application/service.go @@ -0,0 +1,31 @@ +package application + +import ( + "fmt" + "time" +) + +type Service struct { + repository Repository + cursors *CursorCodec + sessionTTL time.Duration + now func() time.Time +} + +func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration) (*Service, error) { + if repository == nil { + return nil, fmt.Errorf("repository is required") + } + if cursors == nil { + return nil, fmt.Errorf("cursor codec is required") + } + if sessionTTL <= 0 { + return nil, fmt.Errorf("session TTL must be positive") + } + return &Service{ + repository: repository, + cursors: cursors, + sessionTTL: sessionTTL, + now: func() time.Time { return time.Now().UTC() }, + }, nil +} diff --git a/internal/application/sessions.go b/internal/application/sessions.go new file mode 100644 index 0000000..a55bf09 --- /dev/null +++ b/internal/application/sessions.go @@ -0,0 +1,57 @@ +package application + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" +) + +const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" + + "AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + +func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) { + user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username) + userNotFound := errors.Is(err, domain.ErrNotFound) + if userNotFound { + passwordHash = dummyPasswordHash + } else if err != nil { + return domain.Session{}, err + } + + passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash) + if verifyErr != nil { + return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr) + } + if userNotFound || !passwordMatches { + return domain.Session{}, ErrInvalidCredentials + } + + token, tokenHash, err := security.GenerateSessionToken() + if err != nil { + return domain.Session{}, fmt.Errorf("generate session token: %w", err) + } + expiresAt := s.now().Add(s.sessionTTL) + if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil { + return domain.Session{}, err + } + return domain.Session{ + Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user, + }, nil +} + +func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) { + tokenHash := security.HashSessionToken(token) + user, err := s.repository.GetUserBySession(ctx, tokenHash) + if err != nil { + return domain.User{}, nil, err + } + return user, tokenHash, nil +} + +func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error { + return s.repository.DeleteSession(ctx, tokenHash) +} diff --git a/internal/application/users.go b/internal/application/users.go new file mode 100644 index 0000000..8c35c66 --- /dev/null +++ b/internal/application/users.go @@ -0,0 +1,29 @@ +package application + +import ( + "context" + "fmt" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" +) + +func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) { + if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil { + return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + if err := security.ValidatePassword(command.Password); err != nil { + return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + + passwordHash, err := security.HashPassword(command.Password) + if err != nil { + return domain.User{}, fmt.Errorf("hash password: %w", err) + } + return s.repository.CreateUser( + ctx, + command.Username, + command.DisplayName, + passwordHash, + ) +} diff --git a/internal/config/config.go b/internal/config/config.go index a02b1e9..9b10852 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,7 +14,8 @@ type Config struct { HTTPHost string HTTPPort string - SessionTTL time.Duration + SessionTTL time.Duration + CursorSigningKey string DatabaseURL string DatabaseMaxConns int32 @@ -51,6 +52,14 @@ func Load() (Config, error) { return Config{}, err } + cursorSigningKey, err := requiredValueOrFile( + "CURSOR_SIGNING_KEY", + "CURSOR_SIGNING_KEY_FILE", + ) + if err != nil { + return Config{}, err + } + databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1) if err != nil { return Config{}, err @@ -150,9 +159,10 @@ func Load() (Config, error) { } return Config{ - HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"), - HTTPPort: envOrDefault("APP_PORT", "8080"), - SessionTTL: sessionTTL, + HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"), + HTTPPort: envOrDefault("APP_PORT", "8080"), + SessionTTL: sessionTTL, + CursorSigningKey: cursorSigningKey, DatabaseURL: databaseURL, DatabaseMaxConns: databaseMaxConns, diff --git a/internal/domain/chat.go b/internal/domain/chat.go new file mode 100644 index 0000000..fe0c594 --- /dev/null +++ b/internal/domain/chat.go @@ -0,0 +1,21 @@ +package domain + +import "time" + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} + +type ChatCursor struct { + CreatedAt time.Time + ChatID string + UserID string +} + +type ChatPage struct { + Items []Chat + NextCursor *string +} diff --git a/internal/domain/errors.go b/internal/domain/errors.go new file mode 100644 index 0000000..38a7599 --- /dev/null +++ b/internal/domain/errors.go @@ -0,0 +1,8 @@ +package domain + +import "errors" + +var ( + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") +) diff --git a/internal/domain/message.go b/internal/domain/message.go new file mode 100644 index 0000000..ec4fe47 --- /dev/null +++ b/internal/domain/message.go @@ -0,0 +1,22 @@ +package domain + +import "time" + +type Message struct { + ID string + ChatID string + SenderID string + Text string + CreatedAt time.Time +} + +type MessageCursor struct { + CreatedAt time.Time + MessageID string + ChatID string +} + +type MessagePage struct { + Items []Message + NextCursor *string +} diff --git a/internal/domain/models.go b/internal/domain/models.go deleted file mode 100644 index b32c5a0..0000000 --- a/internal/domain/models.go +++ /dev/null @@ -1,256 +0,0 @@ -package domain - -import ( - "encoding/base64" - "fmt" - "regexp" - "strings" - "time" - "unicode/utf8" - - "github.com/google/uuid" -) - -var ( - //регулярка по контракту - usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) -) - -type User struct { - ID string `json:"id"` - Username string `json:"username"` - DisplayName string `json:"display_name"` - CreatedAt time.Time `json:"created_at"` -} - -type Session struct { - Token string `json:"token"` - TokenType string `json:"token_type"` - ExpiresAt time.Time `json:"expires_at"` - User User `json:"user"` -} - -type Chat struct { - ID string `json:"id"` - Title string `json:"title"` - MemberIDs []string `json:"member_ids"` - CreatedAt time.Time `json:"created_at"` -} - -type Message struct { - ID string `json:"id"` - ChatID string `json:"chat_id"` - SenderID string `json:"sender_id"` - Text string `json:"text"` - CreatedAt time.Time `json:"created_at"` -} - -// страница выдачи истории сообщений -type MessagePage struct { - Items []Message `json:"items"` - NextCursor *string `json:"next_cursor"` -} - -func (u *User) Validate() error { - if !usernameRegex.MatchString(u.Username) { - return fmt.Errorf("username must match [a-z0-9_]{3,32}") - } - - nameRunes := utf8.RuneCountInString(u.DisplayName) - if nameRunes < 1 || nameRunes > 100 { - return fmt.Errorf("display_name length must be between 1 and 100 code points") - } - - if strings.TrimSpace(u.DisplayName) == "" { - return fmt.Errorf("display_name cannot be only whitespace") - } - - return nil -} - -func ValidateChatInput(title string, memberIDs []string, callerID string) error { - titleRunes := utf8.RuneCountInString(title) - if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" { - return fmt.Errorf("invalid chat title") - } - - if len(memberIDs) == 0 { - return fmt.Errorf("member_ids cannot be empty") - } - - if len(memberIDs) > 100 { - return fmt.Errorf("member_ids must contain at most 100 users") - } - - hasCaller := false - seen := make(map[string]bool) - - for _, id := range memberIDs { - if _, err := uuid.Parse(id); err != nil { - return fmt.Errorf("invalid member uuid: %s", id) - } - - if seen[id] { - return fmt.Errorf("duplicate member_id: %s", id) - } - seen[id] = true - - if id == callerID { - hasCaller = true - } - } - - if !hasCaller { - return fmt.Errorf("caller must be in member_ids") - } - - return nil -} - -func ValidateMessageText(text string) error { - textRunes := utf8.RuneCountInString(text) - if textRunes < 1 || textRunes > 4000 { - return fmt.Errorf("message text length must be between 1 and 4000 code points") - } - if strings.TrimSpace(text) == "" { - return fmt.Errorf("message text cannot be only whitespace") - } - return nil -} - -type CursorData struct { - CreatedAt time.Time - MessageID string - ChatID string -} - -const messageCursorVersion = "v1" - -func EncodeCursor(createdAt time.Time, messageID, chatID string) string { - raw := fmt.Sprintf( - "%s|%s|%s|%s", - messageCursorVersion, - createdAt.UTC().Format(time.RFC3339Nano), - messageID, - chatID, - ) - - return base64.RawURLEncoding.EncodeToString([]byte(raw)) -} - -func DecodeCursor( - cursorStr string, - expectedChatID string, -) (*CursorData, error) { - raw, err := base64.RawURLEncoding.DecodeString(cursorStr) - if err != nil { - return nil, fmt.Errorf("invalid base64 cursor") - } - - parts := strings.Split(string(raw), "|") - if len(parts) != 4 { - return nil, fmt.Errorf("malformed cursor") - } - - if parts[0] != messageCursorVersion { - return nil, fmt.Errorf("unsupported cursor version") - } - - createdAt, err := time.Parse(time.RFC3339Nano, parts[1]) - if err != nil { - return nil, fmt.Errorf("invalid cursor timestamp") - } - - messageID := parts[2] - chatID := parts[3] - - if _, err := uuid.Parse(messageID); err != nil { - return nil, fmt.Errorf("invalid cursor message_id") - } - if _, err := uuid.Parse(chatID); err != nil { - return nil, fmt.Errorf("invalid cursor chat_id") - } - if chatID != expectedChatID { - return nil, fmt.Errorf("cursor belongs to another chat") - } - - return &CursorData{ - CreatedAt: createdAt.UTC(), - MessageID: messageID, - ChatID: chatID, - }, nil -} - -// страница со списком чатов пользователя -type ChatPage struct { - Items []Chat `json:"items"` - NextCursor *string `json:"next_cursor"` -} - -const chatCursorVersion = "v1" - -type ChatCursorData struct { - CreatedAt time.Time - ChatID string - UserID string -} - -// EncodeChatCursor создаёт непрозрачную границу списка чатов. -// Версия позволяет в будущем изменить внутренний формат курсора. -func EncodeChatCursor(createdAt time.Time, chatID, userID string) string { - raw := fmt.Sprintf( - "%s|%s|%s|%s", - chatCursorVersion, - createdAt.UTC().Format(time.RFC3339Nano), - chatID, - userID, - ) - - // RawURLEncoding не использует символы +, / и завершающий =, - // поэтому курсор безопаснее передавать в query string. - return base64.RawURLEncoding.EncodeToString([]byte(raw)) -} - -func DecodeChatCursor( - cursorStr string, - expectedUserID string, -) (*ChatCursorData, error) { - decoded, err := base64.RawURLEncoding.DecodeString(cursorStr) - if err != nil { - return nil, fmt.Errorf("invalid base64 chat cursor") - } - - parts := strings.Split(string(decoded), "|") - if len(parts) != 4 { - return nil, fmt.Errorf("malformed chat cursor") - } - - if parts[0] != chatCursorVersion { - return nil, fmt.Errorf("unsupported chat cursor version") - } - - createdAt, err := time.Parse(time.RFC3339Nano, parts[1]) - if err != nil { - return nil, fmt.Errorf("invalid chat cursor timestamp") - } - - chatID := parts[2] - if _, err = uuid.Parse(chatID); err != nil { - return nil, fmt.Errorf("invalid chat cursor chat_id") - } - - userID := parts[3] - if _, err = uuid.Parse(userID); err != nil { - return nil, fmt.Errorf("invalid chat cursor user_id") - } - - if userID != expectedUserID { - return nil, fmt.Errorf("chat cursor belongs to another user") - } - - return &ChatCursorData{ - CreatedAt: createdAt, - ChatID: chatID, - UserID: userID, - }, nil -} diff --git a/internal/domain/session.go b/internal/domain/session.go new file mode 100644 index 0000000..420c04b --- /dev/null +++ b/internal/domain/session.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type Session struct { + Token string + TokenType string + ExpiresAt time.Time + User User +} diff --git a/internal/domain/user.go b/internal/domain/user.go new file mode 100644 index 0000000..090c349 --- /dev/null +++ b/internal/domain/user.go @@ -0,0 +1,11 @@ +package domain + +import "time" + +// User is the transport-independent representation of a messenger user. +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/internal/domain/validation.go b/internal/domain/validation.go new file mode 100644 index 0000000..6ec3b33 --- /dev/null +++ b/internal/domain/validation.go @@ -0,0 +1,77 @@ +package domain + +import ( + "fmt" + "regexp" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func ValidateUser(username, displayName string) error { + if !usernameRegex.MatchString(username) { + return fmt.Errorf("username must match [a-z0-9_]{3,32}") + } + + nameRunes := utf8.RuneCountInString(displayName) + if nameRunes < 1 || nameRunes > 100 { + return fmt.Errorf("display_name length must be between 1 and 100 code points") + } + if strings.TrimSpace(displayName) == "" { + return fmt.Errorf("display_name cannot be only whitespace") + } + + return nil +} + +// Validate remains as a compatibility convenience for existing callers. +func (u User) Validate() error { + return ValidateUser(u.Username, u.DisplayName) +} + +func ValidateChatInput(title string, memberIDs []string, callerID string) error { + titleRunes := utf8.RuneCountInString(title) + if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" { + return fmt.Errorf("invalid chat title") + } + if len(memberIDs) == 0 { + return fmt.Errorf("member_ids cannot be empty") + } + if len(memberIDs) > 100 { + return fmt.Errorf("member_ids must contain at most 100 users") + } + + hasCaller := false + seen := make(map[string]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, err := uuid.Parse(id); err != nil { + return fmt.Errorf("invalid member uuid: %s", id) + } + if _, exists := seen[id]; exists { + return fmt.Errorf("duplicate member_id: %s", id) + } + seen[id] = struct{}{} + if id == callerID { + hasCaller = true + } + } + + if !hasCaller { + return fmt.Errorf("caller must be in member_ids") + } + return nil +} + +func ValidateMessageText(text string) error { + textRunes := utf8.RuneCountInString(text) + if textRunes < 1 || textRunes > 4000 { + return fmt.Errorf("message text length must be between 1 and 4000 code points") + } + if strings.TrimSpace(text) == "" { + return fmt.Errorf("message text cannot be only whitespace") + } + return nil +} diff --git a/internal/store/errors.go b/internal/store/errors.go deleted file mode 100644 index 939a2b2..0000000 --- a/internal/store/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package store - -import "errors" - -var ( - ErrNotFound = errors.New("not found") - ErrConflict = errors.New("conflict") - ErrInvalidCursor = errors.New("invalid cursor") -) diff --git a/internal/store/repository.go b/internal/store/repository.go deleted file mode 100644 index e400069..0000000 --- a/internal/store/repository.go +++ /dev/null @@ -1,80 +0,0 @@ -package store - -import ( - "context" - "time" - - "mtusi2026lab3/internal/domain" -) - -type Repository interface { - CreateUser( - ctx context.Context, - username string, - displayName string, - passwordHash string, - ) (domain.User, error) - - GetUserByID( - ctx context.Context, - userID string, - ) (domain.User, error) - - GetUserByUsername( - ctx context.Context, - username string, - ) (domain.User, string, error) - - CreateChat( - ctx context.Context, - title string, - memberIDs []string, - ) (domain.Chat, error) - - GetChatByID( - ctx context.Context, - chatID string, - callerID string, - ) (domain.Chat, error) - - GetChatsForUser( - ctx context.Context, - userID string, - limit int, - cursor string, - ) (domain.ChatPage, error) - - CreateMessage( - ctx context.Context, - chatID string, - senderID string, - text string, - ) (domain.Message, error) - - GetMessages( - ctx context.Context, - chatID string, - callerID string, - limit int, - cursor string, - ) (domain.MessagePage, error) - - CreateSession( - ctx context.Context, - tokenHash []byte, - userID string, - expiresAt time.Time, - ) error - - GetUserBySession( - ctx context.Context, - tokenHash []byte, - ) (domain.User, error) - - DeleteSession( - ctx context.Context, - tokenHash []byte, - ) error -} - -var _ Repository = (*PostgreSQLStore)(nil) diff --git a/internal/transport/http/dto/chat.go b/internal/transport/http/dto/chat.go new file mode 100644 index 0000000..56e35a4 --- /dev/null +++ b/internal/transport/http/dto/chat.go @@ -0,0 +1,38 @@ +package dto + +import ( + "time" + + "mtusi2026lab3/internal/domain" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func ChatFromDomain(chat domain.Chat) ChatResponse { + return ChatResponse{ + ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt, + } +} + +func ChatPageFromDomain(page domain.ChatPage) ChatPageResponse { + items := make([]ChatResponse, len(page.Items)) + for index, chat := range page.Items { + items[index] = ChatFromDomain(chat) + } + return ChatPageResponse{Items: items, NextCursor: page.NextCursor} +} diff --git a/internal/transport/http/dto/message.go b/internal/transport/http/dto/message.go new file mode 100644 index 0000000..bd0fe58 --- /dev/null +++ b/internal/transport/http/dto/message.go @@ -0,0 +1,39 @@ +package dto + +import ( + "time" + + "mtusi2026lab3/internal/domain" +) + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func MessageFromDomain(message domain.Message) MessageResponse { + return MessageResponse{ + ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID, + Text: message.Text, CreatedAt: message.CreatedAt, + } +} + +func MessagePageFromDomain(page domain.MessagePage) MessagePageResponse { + items := make([]MessageResponse, len(page.Items)) + for index, message := range page.Items { + items[index] = MessageFromDomain(message) + } + return MessagePageResponse{Items: items, NextCursor: page.NextCursor} +} diff --git a/internal/transport/http/dto/session.go b/internal/transport/http/dto/session.go new file mode 100644 index 0000000..36c808c --- /dev/null +++ b/internal/transport/http/dto/session.go @@ -0,0 +1,21 @@ +package dto + +import ( + "time" + + "mtusi2026lab3/internal/domain" +) + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User UserResponse `json:"user"` +} + +func SessionFromDomain(session domain.Session) SessionResponse { + return SessionResponse{ + Token: session.Token, TokenType: session.TokenType, ExpiresAt: session.ExpiresAt, + User: UserFromDomain(session.User), + } +} diff --git a/internal/transport/http/dto/user.go b/internal/transport/http/dto/user.go new file mode 100644 index 0000000..3aa34a1 --- /dev/null +++ b/internal/transport/http/dto/user.go @@ -0,0 +1,26 @@ +package dto + +import ( + "time" + + "mtusi2026lab3/internal/domain" +) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +func UserFromDomain(user domain.User) UserResponse { + return UserResponse{ + ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt, + } +} diff --git a/internal/transport/http/handlers/chats.go b/internal/transport/http/handlers/chats.go deleted file mode 100644 index 988aba9..0000000 --- a/internal/transport/http/handlers/chats.go +++ /dev/null @@ -1,168 +0,0 @@ -package handlers - -import ( - "errors" - "net/http" - "strconv" - - "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/store" - "mtusi2026lab3/internal/transport/http/middleware" - "mtusi2026lab3/internal/transport/http/response" - - "github.com/google/uuid" -) - -type CreateChatRequest struct { - Title string `json:"title"` - MemberIDs []string `json:"member_ids"` -} - -func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { - reqID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - - var req CreateChatRequest - if err := decodeJSON(r, &req); err != nil { - writeDecodeJSONError(w, reqID, err) - return - } - - //вызывающий есть в списке, нет дубликатов, валидные UUID - if err := domain.ValidateChatInput(req.Title, req.MemberIDs, currentUser.ID); err != nil { - response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) - return - } - - chat, err := h.store.CreateChat( - r.Context(), - req.Title, - req.MemberIDs, - ) - if errors.Is(err, store.ErrNotFound) { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "one or more members do not exist", - reqID, - ) - return - } - if err != nil { - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - reqID, - ) - return - } - - response.WriteJSON(w, http.StatusCreated, chat, reqID) -} - -// инфа о чате -func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { - reqID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - - chatID := r.PathValue("chat_id") - if _, err := uuid.Parse(chatID); err != nil { - response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) - return - } - - chat, err := h.store.GetChatByID( - r.Context(), - chatID, - currentUser.ID, - ) - if err != nil { - if errors.Is(err, store.ErrNotFound) { - //посторонний или несуществующий чат -> 404 - response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) - return - } - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - reqID, - ) - return - } - - response.WriteJSON(w, http.StatusOK, chat, reqID) -} - -// список всех чатов текущего пользователя -func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { - reqID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - query := r.URL.Query() - - limit := 50 - - if query.Has("limit") { - limitStr := query.Get("limit") - val, err := strconv.Atoi(limitStr) - - if err != nil || val < 1 || val > 100 { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "limit must be an integer between 1 and 100", - reqID, - ) - return - } - - limit = val - } - - cursor := query.Get("cursor") - if query.Has("cursor") && cursor == "" { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "cursor must not be empty", - reqID, - ) - return - } - - page, err := h.store.GetChatsForUser( - r.Context(), - currentUser.ID, - limit, - cursor, - ) - if err != nil { - if errors.Is(err, store.ErrInvalidCursor) { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "invalid cursor", - reqID, - ) - return - } - - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - reqID, - ) - return - } - - response.WriteJSON(w, http.StatusOK, page, reqID) -} diff --git a/internal/transport/http/handlers/create_chat.go b/internal/transport/http/handlers/create_chat.go new file mode 100644 index 0000000..eb6a454 --- /dev/null +++ b/internal/transport/http/handlers/create_chat.go @@ -0,0 +1,44 @@ +package handlers + +import ( + "errors" + "net/http" + "strings" + + "mtusi2026lab3/internal/application" + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + var request dto.CreateChatRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + + chat, err := h.service.CreateChat(r.Context(), application.CreateChatCommand{ + ActorID: currentUser.ID, Title: request.Title, MemberIDs: request.MemberIDs, + }) + if errors.Is(err, application.ErrInvalidInput) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID) + return + } + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "one or more members do not exist", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusCreated, dto.ChatFromDomain(chat), requestID) +} diff --git a/internal/transport/http/handlers/create_message.go b/internal/transport/http/handlers/create_message.go new file mode 100644 index 0000000..636b1d9 --- /dev/null +++ b/internal/transport/http/handlers/create_message.go @@ -0,0 +1,50 @@ +package handlers + +import ( + "errors" + "net/http" + "strings" + + "mtusi2026lab3/internal/application" + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + + var request dto.CreateMessageRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{ + ActorID: currentUser.ID, ChatID: chatID, Text: request.Text, + }) + if errors.Is(err, application.ErrInvalidInput) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID) + return + } + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusCreated, dto.MessageFromDomain(message), requestID) +} diff --git a/internal/transport/http/handlers/delete_session.go b/internal/transport/http/handlers/delete_session.go new file mode 100644 index 0000000..d6c556b --- /dev/null +++ b/internal/transport/http/handlers/delete_session.go @@ -0,0 +1,19 @@ +package handlers + +import ( + "net/http" + + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + tokenHash := middleware.GetCurrentSessionTokenHash(r.Context()) + if err := h.service.DeleteSession(r.Context(), tokenHash); err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusNoContent, nil, requestID) +} diff --git a/internal/transport/http/handlers/get_chat.go b/internal/transport/http/handlers/get_chat.go new file mode 100644 index 0000000..a59e39c --- /dev/null +++ b/internal/transport/http/handlers/get_chat.go @@ -0,0 +1,36 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + + chat, err := h.service.GetChat(r.Context(), currentUser.ID, chatID) + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.ChatFromDomain(chat), requestID) +} diff --git a/internal/transport/http/handlers/get_me.go b/internal/transport/http/handlers/get_me.go new file mode 100644 index 0000000..307a1b2 --- /dev/null +++ b/internal/transport/http/handlers/get_me.go @@ -0,0 +1,15 @@ +package handlers + +import ( + "net/http" + + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + response.WriteJSON(w, http.StatusOK, dto.UserFromDomain(currentUser), requestID) +} diff --git a/internal/transport/http/handlers/handler.go b/internal/transport/http/handlers/handler.go index dbb1764..f775c55 100644 --- a/internal/transport/http/handlers/handler.go +++ b/internal/transport/http/handlers/handler.go @@ -12,7 +12,7 @@ import ( "time" "unicode/utf8" - "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/transport/http/response" ) @@ -30,20 +30,18 @@ type ReadinessChecker interface { type Option func(*Handler) type Handler struct { - store store.Repository + service *application.Service readinessChecker ReadinessChecker readinessTimeout time.Duration - sessionTTL time.Duration } func NewHandler( - repository store.Repository, + service *application.Service, options ...Option, ) *Handler { handler := &Handler{ - store: repository, + service: service, readinessTimeout: 2 * time.Second, - sessionTTL: time.Hour, } for _, option := range options { @@ -63,12 +61,6 @@ func WithReadiness( } } -func WithSessionTTL(ttl time.Duration) Option { - return func(handler *Handler) { - handler.sessionTTL = ttl - } -} - func decodeJSON(r *http.Request, destination any) error { mediaType, parameters, err := mime.ParseMediaType( r.Header.Get("Content-Type"), diff --git a/internal/transport/http/handlers/list_chats.go b/internal/transport/http/handlers/list_chats.go new file mode 100644 index 0000000..c8308a0 --- /dev/null +++ b/internal/transport/http/handlers/list_chats.go @@ -0,0 +1,32 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab3/internal/application" + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + limit, cursor, ok := parsePagination(w, r, requestID) + if !ok { + return + } + + page, err := h.service.ListChats(r.Context(), currentUser.ID, limit, cursor) + if errors.Is(err, application.ErrInvalidCursor) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.ChatPageFromDomain(page), requestID) +} diff --git a/internal/transport/http/handlers/list_messages.go b/internal/transport/http/handlers/list_messages.go new file mode 100644 index 0000000..bd0026d --- /dev/null +++ b/internal/transport/http/handlers/list_messages.go @@ -0,0 +1,45 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab3/internal/application" + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/transport/http/dto" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" + + "github.com/google/uuid" +) + +func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "invalid chat_id uuid", requestID) + return + } + limit, cursor, ok := parsePagination(w, r, requestID) + if !ok { + return + } + + page, err := h.service.ListMessages(r.Context(), currentUser.ID, chatID, limit, cursor) + if errors.Is(err, domain.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID) + return + } + if errors.Is(err, application.ErrInvalidCursor) { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID) + return + } + if err != nil { + response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, + "service is temporarily unavailable", requestID) + return + } + response.WriteJSON(w, http.StatusOK, dto.MessagePageFromDomain(page), requestID) +} diff --git a/internal/transport/http/handlers/messages.go b/internal/transport/http/handlers/messages.go deleted file mode 100644 index 25bdd9c..0000000 --- a/internal/transport/http/handlers/messages.go +++ /dev/null @@ -1,159 +0,0 @@ -package handlers - -import ( - "errors" - "net/http" - "strconv" - - "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/store" - "mtusi2026lab3/internal/transport/http/middleware" - "mtusi2026lab3/internal/transport/http/response" - - "github.com/google/uuid" -) - -type CreateMessageRequest struct { - Text string `json:"text"` -} - -// CreateMessage отправляет сообщение в чат -func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) { - reqID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - - chatID := r.PathValue("chat_id") - if _, err := uuid.Parse(chatID); err != nil { - response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) - return - } - - var req CreateMessageRequest - if err := decodeJSON(r, &req); err != nil { - writeDecodeJSONError(w, reqID, err) - return - } - - //не пустой, не только пробелы, до 4000 рун - if err := domain.ValidateMessageText(req.Text); err != nil { - response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) - return - } - - //автор сообщения строго выводится из сессии (currentUser.ID) - msg, err := h.store.CreateMessage( - r.Context(), - chatID, - currentUser.ID, - req.Text, - ) - if err != nil { - if errors.Is(err, store.ErrNotFound) { - // чата нет/пользователь не участник -> 404 - response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) - return - } - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - reqID, - ) - return - } - - response.WriteJSON(w, http.StatusCreated, msg, reqID) -} - -// GetMessages возвращает историю сообщений чата с пагинацией по курсору -func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) { - reqID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - - chatID := r.PathValue("chat_id") - if _, err := uuid.Parse(chatID); err != nil { - response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) - return - } - - query := r.URL.Query() - - limit := 50 - if query.Has("limit") { - limitString := query.Get("limit") - - parsedLimit, err := strconv.Atoi(limitString) - if err != nil || parsedLimit < 1 || parsedLimit > 100 { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "limit must be an integer between 1 and 100", - reqID, - ) - return - } - - limit = parsedLimit - } - - cursor := query.Get("cursor") - if query.Has("cursor") && cursor == "" { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "cursor must not be empty", - reqID, - ) - return - } - - page, err := h.store.GetMessages( - r.Context(), - chatID, - currentUser.ID, - limit, - cursor, - ) - if errors.Is(err, store.ErrNotFound) { - response.WriteError( - w, - http.StatusNotFound, - response.CodeNotFound, - "chat not found", - reqID, - ) - return - } - - if errors.Is(err, store.ErrInvalidCursor) { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - "invalid cursor", - reqID, - ) - return - } - - if err != nil { - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - reqID, - ) - return - } - - // сообщений нет, [] вместо null - if page.Items == nil { - page.Items = make([]domain.Message, 0) - } - - response.WriteJSON(w, http.StatusOK, page, reqID) -} diff --git a/internal/transport/http/handlers/pagination.go b/internal/transport/http/handlers/pagination.go new file mode 100644 index 0000000..01e3b13 --- /dev/null +++ b/internal/transport/http/handlers/pagination.go @@ -0,0 +1,29 @@ +package handlers + +import ( + "net/http" + "strconv" + + "mtusi2026lab3/internal/transport/http/response" +) + +func parsePagination(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) { + query := r.URL.Query() + limit := 50 + if query.Has("limit") { + parsed, err := strconv.Atoi(query.Get("limit")) + if err != nil || parsed < 1 || parsed > 100 { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "limit must be an integer between 1 and 100", requestID) + return 0, "", false + } + limit = parsed + } + cursor := query.Get("cursor") + if query.Has("cursor") && cursor == "" { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, + "cursor must not be empty", requestID) + return 0, "", false + } + return limit, cursor, true +} diff --git a/internal/transport/http/handlers/sessions.go b/internal/transport/http/handlers/sessions.go index 412f5d0..34bddfa 100644 --- a/internal/transport/http/handlers/sessions.go +++ b/internal/transport/http/handlers/sessions.go @@ -3,25 +3,16 @@ package handlers import ( "errors" "net/http" - "time" "unicode/utf8" - "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/security" - "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/application" + "mtusi2026lab3/internal/transport/http/dto" "mtusi2026lab3/internal/transport/http/middleware" "mtusi2026lab3/internal/transport/http/response" ) const basicChallenge = `Basic realm="messenger", charset="UTF-8"` -// dummyPasswordHash keeps the expensive Argon2id path for an unknown username. -// The all-zero digest is intentionally not a real user's credential; only the -// encoded parameters and lengths need to be valid for constant-cost checking. -const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" + - "AAAAAAAAAAAAAAAAAAAAAA$" + - "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" - func (h *Handler) CreateSession( w http.ResponseWriter, r *http.Request, @@ -35,32 +26,11 @@ func (h *Handler) CreateSession( return } - user, passwordHash, err := h.store.GetUserByUsername( - r.Context(), - username, - ) - userNotFound := errors.Is(err, store.ErrNotFound) - if userNotFound { - passwordHash = dummyPasswordHash - } - if err != nil { - if !userNotFound { - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - requestID, - ) - return - } - } - - passwordMatches, err := security.VerifyPassword( - password, - passwordHash, - ) - if err != nil { + session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{ + Username: username, + Password: password, + }) + if errors.Is(err, application.ErrCredentialState) { response.WriteError( w, http.StatusInternalServerError, @@ -70,31 +40,11 @@ func (h *Handler) CreateSession( ) return } - if userNotFound || !passwordMatches { + if errors.Is(err, application.ErrInvalidCredentials) { writeBasicUnauthorized(w, requestID) return } - - token, tokenHash, err := security.GenerateSessionToken() if err != nil { - response.WriteError( - w, - http.StatusInternalServerError, - response.CodeInternalError, - "failed to create session", - requestID, - ) - return - } - - expiresAt := time.Now().UTC().Add(h.sessionTTL) - - if err := h.store.CreateSession( - r.Context(), - tokenHash, - user.ID, - expiresAt, - ); err != nil { response.WriteError( w, http.StatusServiceUnavailable, @@ -105,50 +55,13 @@ func (h *Handler) CreateSession( return } - session := domain.Session{ - Token: token, - TokenType: "Bearer", - ExpiresAt: expiresAt, - User: user, - } - response.WriteJSON( w, http.StatusCreated, - session, + dto.SessionFromDomain(session), requestID, ) } - -func (h *Handler) DeleteCurrentSession( - w http.ResponseWriter, - r *http.Request, -) { - requestID := middleware.GetRequestID(r.Context()) - tokenHash := middleware.GetCurrentSessionTokenHash(r.Context()) - - if err := h.store.DeleteSession( - r.Context(), - tokenHash, - ); err != nil { - response.WriteError( - w, - http.StatusServiceUnavailable, - response.CodeUnavailable, - "service is temporarily unavailable", - requestID, - ) - return - } - - response.WriteJSON( - w, - http.StatusNoContent, - nil, - requestID, - ) -} - func writeBasicUnauthorized( w http.ResponseWriter, requestID string, diff --git a/internal/transport/http/handlers/users.go b/internal/transport/http/handlers/users.go index cde4af7..af35fb1 100644 --- a/internal/transport/http/handlers/users.go +++ b/internal/transport/http/handlers/users.go @@ -3,75 +3,39 @@ package handlers import ( "errors" "net/http" + "strings" + "mtusi2026lab3/internal/application" "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/security" - "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/dto" "mtusi2026lab3/internal/transport/http/middleware" "mtusi2026lab3/internal/transport/http/response" ) -type CreateUserRequest struct { - Username string `json:"username"` - DisplayName string `json:"display_name"` - Password string `json:"password"` -} - func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) { requestID := middleware.GetRequestID(r.Context()) - var request CreateUserRequest + var request dto.CreateUserRequest if err := decodeJSON(r, &request); err != nil { writeDecodeJSONError(w, requestID, err) return } - userCandidate := domain.User{ - Username: request.Username, - DisplayName: request.DisplayName, - } - - if err := userCandidate.Validate(); err != nil { + createdUser, err := h.service.CreateUser(r.Context(), application.CreateUserCommand{ + Username: request.Username, DisplayName: request.DisplayName, Password: request.Password, + }) + if errors.Is(err, application.ErrInvalidInput) { response.WriteError( w, http.StatusBadRequest, response.CodeInvalidRequest, - err.Error(), + strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID, ) return } - if err := security.ValidatePassword(request.Password); err != nil { - response.WriteError( - w, - http.StatusBadRequest, - response.CodeInvalidRequest, - err.Error(), - requestID, - ) - return - } - - passwordHash, err := security.HashPassword(request.Password) - if err != nil { - response.WriteError( - w, - http.StatusInternalServerError, - response.CodeInternalError, - "failed to process password", - requestID, - ) - return - } - - createdUser, err := h.store.CreateUser( - r.Context(), - request.Username, - request.DisplayName, - passwordHash, - ) - if errors.Is(err, store.ErrConflict) { + if errors.Is(err, domain.ErrConflict) { response.WriteError( w, http.StatusConflict, @@ -95,19 +59,7 @@ func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) { response.WriteJSON( w, http.StatusCreated, - createdUser, - requestID, - ) -} - -func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) { - requestID := middleware.GetRequestID(r.Context()) - currentUser := middleware.GetCurrentUser(r.Context()) - - response.WriteJSON( - w, - http.StatusOK, - currentUser, + dto.UserFromDomain(createdUser), requestID, ) } diff --git a/internal/transport/http/middleware/auth.go b/internal/transport/http/middleware/auth.go index 827e0c8..b3b0d32 100644 --- a/internal/transport/http/middleware/auth.go +++ b/internal/transport/http/middleware/auth.go @@ -7,8 +7,6 @@ import ( "strings" "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/security" - "mtusi2026lab3/internal/store" "mtusi2026lab3/internal/transport/http/response" ) @@ -20,10 +18,10 @@ const ( ) type SessionAuthenticator interface { - GetUserBySession( + Authenticate( ctx context.Context, - tokenHash []byte, - ) (domain.User, error) + token string, + ) (domain.User, []byte, error) } func RequireAuth( @@ -39,13 +37,11 @@ func RequireAuth( return } - tokenHash := security.HashSessionToken(token) - - user, err := authenticator.GetUserBySession( + user, tokenHash, err := authenticator.Authenticate( r.Context(), - tokenHash, + token, ) - if errors.Is(err, store.ErrNotFound) { + if errors.Is(err, domain.ErrNotFound) { writeBearerUnauthorized(w, requestID) return } diff --git a/student_tests/application_helper_test.go b/student_tests/application_helper_test.go new file mode 100644 index 0000000..bb19ca1 --- /dev/null +++ b/student_tests/application_helper_test.go @@ -0,0 +1,32 @@ +package student_tests + +import ( + "time" + + "mtusi2026lab3/internal/application" +) + +const testCursorSigningKey = "student-tests-cursor-signing-key-at-least-32-bytes" + +func newTestService(repository application.Repository, sessionTTL time.Duration) *application.Service { + if sessionTTL <= 0 { + sessionTTL = time.Hour + } + codec, err := application.NewCursorCodec(testCursorSigningKey) + if err != nil { + panic(err) + } + service, err := application.NewService(repository, codec, sessionTTL) + if err != nil { + panic(err) + } + return service +} + +func newTestCursorCodec() *application.CursorCodec { + codec, err := application.NewCursorCodec(testCursorSigningKey) + if err != nil { + panic(err) + } + return codec +} diff --git a/student_tests/auth_test.go b/student_tests/auth_test.go index 49c3930..6b5e6e3 100644 --- a/student_tests/auth_test.go +++ b/student_tests/auth_test.go @@ -10,9 +10,9 @@ import ( "testing" "time" - "mtusi2026lab3/internal/domain" + store "mtusi2026lab3/internal/adapter/memory" "mtusi2026lab3/internal/security" - "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/dto" "mtusi2026lab3/internal/transport/http/handlers" "mtusi2026lab3/internal/transport/http/middleware" ) @@ -26,21 +26,19 @@ func setupSessionTestServer( t.Helper() repository := store.NewMemoryRepository(store.NewMemoryStore()) - handler := handlers.NewHandler( - repository, - handlers.WithSessionTTL(sessionTTL), - ) + service := newTestService(repository, sessionTTL) + handler := handlers.NewHandler(service) mux := http.NewServeMux() mux.HandleFunc("POST /api/v1/users", handler.CreateUser) mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession) mux.HandleFunc( "GET /api/v1/users/me", - middleware.RequireAuth(repository, handler.GetMe), + middleware.RequireAuth(service, handler.GetMe), ) mux.HandleFunc( "DELETE /api/v1/auth/sessions/current", - middleware.RequireAuth(repository, handler.DeleteCurrentSession), + middleware.RequireAuth(service, handler.DeleteCurrentSession), ) var root http.Handler = mux @@ -54,7 +52,7 @@ func registerSessionTestUser( t *testing.T, baseURL string, username string, -) domain.User { +) dto.UserResponse { t.Helper() payload, err := json.Marshal(map[string]string{ @@ -81,7 +79,7 @@ func registerSessionTestUser( t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body) } - var user domain.User + var user dto.UserResponse if err := json.NewDecoder(response.Body).Decode(&user); err != nil { t.Fatalf("decode registered user: %v", err) } @@ -184,7 +182,7 @@ func TestSessionAuthenticationLifecycle(t *testing.T) { t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body) } - var session domain.Session + var session dto.SessionResponse if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { t.Fatalf("decode session: %v", err) } @@ -253,7 +251,7 @@ func TestSessionAuthenticationLifecycle(t *testing.T) { return } - var currentUser domain.User + var currentUser dto.UserResponse if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil { t.Fatalf("decode current user: %v", err) } @@ -321,7 +319,7 @@ func TestSessionExpiry(t *testing.T) { testPassword, ) - var session domain.Session + var session dto.SessionResponse if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { loginResponse.Body.Close() t.Fatalf("decode session: %v", err) diff --git a/student_tests/cursor_concurrency_test.go b/student_tests/cursor_concurrency_test.go index f68e4b9..a14e14d 100644 --- a/student_tests/cursor_concurrency_test.go +++ b/student_tests/cursor_concurrency_test.go @@ -12,6 +12,7 @@ import ( "time" "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/transport/http/dto" ) func fetchCursorPage( @@ -19,7 +20,7 @@ func fetchCursorPage( baseURL, chatID, userID string, limit int, cursor string, -) domain.MessagePage { +) dto.MessagePageResponse { t.Helper() endpoint := fmt.Sprintf( @@ -49,7 +50,7 @@ func fetchCursorPage( t.Fatalf("expected 200, got %d: %s", res.StatusCode, body) } - var page domain.MessagePage + var page dto.MessagePageResponse if err := json.NewDecoder(res.Body).Decode(&page); err != nil { t.Fatalf("decode message page: %v", err) } @@ -109,7 +110,7 @@ func TestCursorTraversalAfterConcurrentWrites(t *testing.T) { seen := make(map[string]struct{}, expectedMessages) duplicateCount := 0 - var previous *domain.Message + var previous *dto.MessageResponse firstOrderingViolation := "" cursor := "" pageCount := 0 @@ -267,7 +268,7 @@ func TestCursorTraversalDuringConcurrentWrites(t *testing.T) { seen := make(map[string]struct{}, expectedTotal) cursor := "" - var previous *domain.Message + var previous *dto.MessageResponse const maxPageRequests = expectedTotal * 4 finished := false @@ -320,11 +321,15 @@ func TestCursorTraversalDuringConcurrentWrites(t *testing.T) { // NextCursor=nil. if len(page.Items) > 0 { last := page.Items[len(page.Items)-1] - cursor = domain.EncodeCursor( - last.CreatedAt, - last.ID, - chat.ID, - ) + var encodeErr error + cursor, encodeErr = newTestCursorCodec().EncodeMessage(domain.MessageCursor{ + CreatedAt: last.CreatedAt, + MessageID: last.ID, + ChatID: chat.ID, + }) + if encodeErr != nil { + t.Fatalf("encode traversal cursor: %v", encodeErr) + } } select { diff --git a/student_tests/messenger_test.go b/student_tests/messenger_test.go index 221a44a..6eedfcb 100644 --- a/student_tests/messenger_test.go +++ b/student_tests/messenger_test.go @@ -12,9 +12,11 @@ import ( "sort" "sync" "testing" + "time" + store "mtusi2026lab3/internal/adapter/memory" "mtusi2026lab3/internal/domain" - "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/dto" "mtusi2026lab3/internal/transport/http/handlers" "mtusi2026lab3/internal/transport/http/middleware" ) @@ -46,7 +48,7 @@ func requireLegacyAuth( func setupTestServer() (*httptest.Server, *store.MemoryStore) { memoryStore := store.NewMemoryStore() repository := store.NewMemoryRepository(memoryStore) - handler := handlers.NewHandler(repository) + handler := handlers.NewHandler(newTestService(repository, time.Hour)) mux := http.NewServeMux() mux.HandleFunc("POST /api/v1/users", handler.CreateUser) @@ -199,7 +201,7 @@ func TestCursorPaginationMultiplePages(t *testing.T) { req.Header.Set("X-User-Id", u.ID) res, _ := http.DefaultClient.Do(req) - var page domain.MessagePage + var page dto.MessagePageResponse body, _ := io.ReadAll(res.Body) json.Unmarshal(body, &page) res.Body.Close() @@ -289,7 +291,7 @@ func TestChatCursorPaginationMultiplePages(t *testing.T) { t.Fatalf("failed to list chats: %v", err) } - var page domain.ChatPage + var page dto.ChatPageResponse decodeErr := json.NewDecoder(res.Body).Decode(&page) res.Body.Close() @@ -391,7 +393,7 @@ func TestChatCursorValidation(t *testing.T) { t.Fatalf("failed to request first page: %v", err) } - var firstPage domain.ChatPage + var firstPage dto.ChatPageResponse decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage) firstResponse.Body.Close() @@ -507,18 +509,18 @@ func TestConcurrent100MessagesFrom10Clients(t *testing.T) { wg.Wait() // должно быть 100 сообщений в чате - page, err := st.GetMessages(chat.ID, memberIDs[0], 200, "") + items, _, err := st.GetMessages(chat.ID, memberIDs[0], 200, nil) if err != nil { t.Fatalf("failed to get messages: %v", err) } - if len(page.Items) != 100 { - t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(page.Items)) + if len(items) != 100 { + t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(items)) } // уникальность ID seenIDs := make(map[string]bool) - for _, m := range page.Items { + for _, m := range items { if seenIDs[m.ID] { t.Fatalf("duplicate message ID found: %s", m.ID) } @@ -546,13 +548,21 @@ func TestForeignAndMalformedCursor(t *testing.T) { st.CreateMessage(chatB.ID, u.ID, "Message 2 in B") // Получаем валидный курсор из Чата А (запрашиваем 1 из 2) - pageA, err := st.GetMessages(chatA.ID, u.ID, 1, "") - if err != nil || pageA.NextCursor == nil { + itemsA, hasMore, err := st.GetMessages(chatA.ID, u.ID, 1, nil) + if err != nil || !hasMore || len(itemsA) != 1 { t.Fatalf("expected next_cursor in Chat A, err: %v", err) } + nextCursor, err := newTestCursorCodec().EncodeMessage(domain.MessageCursor{ + CreatedAt: itemsA[0].CreatedAt, + MessageID: itemsA[0].ID, + ChatID: chatA.ID, + }) + if err != nil { + t.Fatalf("encode test cursor: %v", err) + } // 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400! - urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, *pageA.NextCursor) + urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, nextCursor) reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil) reqForeign.Header.Set("X-User-Id", u.ID) resForeign, _ := http.DefaultClient.Do(reqForeign)