перенос 3 лабы

This commit is contained in:
2026-10-28 12:40:39 +03:00
parent ec540a1a72
commit 7860d81fa1
115 changed files with 12814 additions and 0 deletions
+99
View File
@@ -0,0 +1,99 @@
package cache
import (
"context"
"errors"
"log"
"mtusi2026lab4/internal/adapter/redis"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
// и создания чата, автоматически делегируются встроенному Repository.
type CachedRepository struct {
application.Repository
chatCache redis.ChatCache
logger *log.Logger
}
func NewCachedRepository(
repository application.Repository,
chatCache redis.ChatCache,
logger *log.Logger,
) *CachedRepository {
if logger == nil {
logger = log.Default()
}
return &CachedRepository{
Repository: repository,
chatCache: chatCache,
logger: logger,
}
}
func (r *CachedRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
if err != nil {
return domain.Chat{}, err
}
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
// должна превращать успешную бизнес-операцию в 503.
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
}
return chat, nil
}
func (r *CachedRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
chat, err := r.chatCache.Get(ctx, chatID)
if err == nil {
if !containsMember(chat.MemberIDs, callerID) {
return domain.Chat{}, domain.ErrNotFound
}
return chat, nil
}
shouldFillCache := errors.Is(err, redis.ErrMiss)
if !shouldFillCache {
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
}
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
if err != nil {
return domain.Chat{}, err
}
if shouldFillCache {
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
}
}
return chat, nil
}
func containsMember(memberIDs []string, callerID string) bool {
for _, memberID := range memberIDs {
if memberID == callerID {
return true
}
}
return false
}
var _ application.Repository = (*CachedRepository)(nil)
+183
View File
@@ -0,0 +1,183 @@
package cache
import (
"context"
"errors"
"io"
"log"
"testing"
"mtusi2026lab4/internal/adapter/memory"
"mtusi2026lab4/internal/adapter/redis"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
type fakeChatCache struct {
chats map[string]domain.Chat
getErr error
setErr error
sets int
}
func (c *fakeChatCache) Get(
_ context.Context,
chatID string,
) (domain.Chat, error) {
if c.getErr != nil {
return domain.Chat{}, c.getErr
}
chat, exists := c.chats[chatID]
if !exists {
return domain.Chat{}, redis.ErrMiss
}
return chat, nil
}
func (c *fakeChatCache) Set(
_ context.Context,
chat domain.Chat,
) error {
c.sets++
if c.setErr != nil {
return c.setErr
}
c.chats[chat.ID] = chat
return nil
}
type countingRepository struct {
application.Repository
getChatCalls int
}
func (r *countingRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
r.getChatCalls++
return r.Repository.GetChatByID(ctx, chatID, callerID)
}
func cachedRepositoryFixture(
t *testing.T,
) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) {
t.Helper()
legacy := memory.NewMemoryStore()
member, err := legacy.CreateUser("cache_member", "Участник")
if err != nil {
t.Fatalf("create member: %v", err)
}
outsider, err := legacy.CreateUser("cache_outsider", "Посторонний")
if err != nil {
t.Fatalf("create outsider: %v", err)
}
chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID})
if err != nil {
t.Fatalf("create chat: %v", err)
}
repository := &countingRepository{
Repository: memory.NewMemoryRepository(legacy),
}
chatCache := &fakeChatCache{
chats: make(map[string]domain.Chat),
}
return repository, chatCache, member, outsider, chat
}
func TestCachedRepositoryMissThenHit(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("first read: %v", err)
}
second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("second read: %v", err)
}
if repository.getChatCalls != 1 {
t.Fatalf("expected one source read, got %d", repository.getChatCalls)
}
if chatCache.sets != 1 {
t.Fatalf("expected one cache fill, got %d", chatCache.sets)
}
if first.ID != expected.ID || second.ID != expected.ID {
t.Fatal("cache changed chat identity")
}
}
func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
chatCache.getErr = errors.New("redis unavailable")
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("fallback read: %v", err)
}
if chat.ID != expected.ID || repository.getChatCalls != 1 {
t.Fatal("source repository was not used after cache failure")
}
if chatCache.sets != 0 {
t.Fatal("failed cache read must not trigger another cache operation")
}
}
func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) {
repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t)
chatCache.chats[expected.ID] = expected
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
_, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID)
if !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("expected ErrNotFound for outsider, got %v", err)
}
if repository.getChatCalls != 0 {
t.Fatal("cache hit unexpectedly queried source repository")
}
}
func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) {
repository, chatCache, member, _, _ := cachedRepositoryFixture(t)
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.CreateChat(
context.Background(),
"Новый чат",
[]string{member.ID},
)
if err != nil {
t.Fatalf("create chat with unavailable cache: %v", err)
}
if chat.ID == "" || chatCache.sets != 1 {
t.Fatal("chat was not created before best-effort cache write")
}
}
+8
View File
@@ -0,0 +1,8 @@
package memory
import "mtusi2026lab4/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+295
View File
@@ -0,0 +1,295 @@
package memory
import (
"context"
"fmt"
"sync"
"time"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
type memorySession struct {
userID string
expiresAt time.Time
}
type memoryIdempotencyScope struct {
actorID string
method string
canonicalPath string
key string
}
type memoryIdempotencyResult struct {
requestHash [32]byte
message domain.Message
expiresAt time.Time
}
type MemoryRepository struct {
legacy *MemoryStore
mu sync.RWMutex
passwordByUserID map[string]string
userIDByUsername map[string]string
sessionsByHashKey map[[32]byte]memorySession
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
}
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
return &MemoryRepository{
legacy: legacy,
passwordByUserID: make(map[string]string),
userIDByUsername: make(map[string]string),
sessionsByHashKey: make(map[[32]byte]memorySession),
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
}
}
func (r *MemoryRepository) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
user, err := r.legacy.CreateUser(username, displayName)
if err != nil {
return domain.User{}, err
}
r.mu.Lock()
r.passwordByUserID[user.ID] = passwordHash
r.userIDByUsername[user.Username] = user.ID
r.mu.Unlock()
return user, nil
}
func (r *MemoryRepository) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
return r.legacy.GetUserByID(userID)
}
func (r *MemoryRepository) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, "", err
}
r.mu.RLock()
userID, exists := r.userIDByUsername[username]
passwordHash := r.passwordByUserID[userID]
r.mu.RUnlock()
if !exists {
return domain.User{}, "", ErrNotFound
}
user, err := r.legacy.GetUserByID(userID)
if err != nil {
return domain.User{}, "", err
}
return user, passwordHash, nil
}
func (r *MemoryRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.CreateChat(title, memberIDs)
}
func (r *MemoryRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.GetChatByID(chatID, callerID)
}
func (r *MemoryRepository) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetChatsForUser(userID, limit, cursor)
}
func (r *MemoryRepository) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := ctx.Err(); err != nil {
return domain.Message{}, err
}
scope := memoryIdempotencyScope{
actorID: write.ActorID,
method: write.Method,
canonicalPath: write.CanonicalPath,
key: write.Key,
}
now := time.Now().UTC()
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
return domain.Message{}, err
}
if stored, exists := r.idempotencyByScope[scope]; exists {
if stored.expiresAt.After(now) {
if stored.requestHash != write.RequestHash {
return domain.Message{}, application.ErrIdempotencyConflict
}
return stored.message, nil
}
delete(r.idempotencyByScope, scope)
}
message, err := r.legacy.CreateMessage(write.ChatID, write.ActorID, write.Text)
if err != nil {
return domain.Message{}, err
}
r.idempotencyByScope[scope] = memoryIdempotencyResult{
requestHash: write.RequestHash,
message: message,
expiresAt: now.Add(write.TTL),
}
return message, nil
}
func (r *MemoryRepository) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetMessages(
chatID,
callerID,
limit,
cursor,
)
}
func (r *MemoryRepository) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
r.sessionsByHashKey[key] = memorySession{
userID: userID,
expiresAt: expiresAt,
}
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return domain.User{}, ErrNotFound
}
r.mu.RLock()
session, exists := r.sessionsByHashKey[key]
r.mu.RUnlock()
if !exists || !session.expiresAt.After(time.Now().UTC()) {
return domain.User{}, ErrNotFound
}
return r.legacy.GetUserByID(session.userID)
}
func (r *MemoryRepository) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
delete(r.sessionsByHashKey, key)
r.mu.Unlock()
return nil
}
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
var key [32]byte
if len(tokenHash) != len(key) {
return key, fmt.Errorf(
"session token hash must contain %d bytes",
len(key),
)
}
copy(key[:], tokenHash)
return key, nil
}
var _ application.Repository = (*MemoryRepository)(nil)
+287
View File
@@ -0,0 +1,287 @@
package memory
import (
"fmt"
"sort"
"sync"
"time"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
)
type MemoryStore struct {
mu sync.RWMutex
usersByID map[string]domain.User //key = user UUID
usersByUsername map[string]string //key = username для быстрой проверки уникальности
chatsByID map[string]domain.Chat //key = chat UUID
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
usersByID: make(map[string]domain.User),
usersByUsername: make(map[string]string),
chatsByID: make(map[string]domain.Chat),
messagesByChatID: make(map[string][]domain.Message),
}
}
// ---пользователи---
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
s.mu.Lock()
defer s.mu.Unlock()
// дубликат username -> 409 Conflict
if _, exists := s.usersByUsername[username]; exists {
return domain.User{}, ErrConflict
}
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC(),
}
s.usersByID[user.ID] = user
s.usersByUsername[user.Username] = user.ID
return user, nil
}
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
s.mu.RLock()
defer s.mu.RUnlock()
user, exists := s.usersByID[id]
if !exists {
return domain.User{}, ErrNotFound
}
return user, nil
}
// ---чаты---
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
s.mu.Lock()
defer s.mu.Unlock()
//все участники рил существуют
for _, memberID := range memberIDs {
if _, exists := s.usersByID[memberID]; !exists {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
CreatedAt: time.Now().UTC(),
}
s.chatsByID[chat.ID] = chat
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
return chat, nil
}
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Chat{}, ErrNotFound
}
// Требование безопасности: посторонний получает 404, а не 403
isMember := false
for _, m := range chat.MemberIDs {
if m == callerID {
isMember = true
break
}
}
if !isMember {
return domain.Chat{}, ErrNotFound
}
return chat, nil
}
func (s *MemoryStore) GetChatsForUser(
userID string,
limit int,
cursorData *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chats := make([]domain.Chat, 0)
for _, chat := range s.chatsByID {
for _, memberID := range chat.MemberIDs {
if memberID == userID {
chats = append(chats, chat)
break
}
}
}
sort.Slice(chats, func(i, j int) bool {
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
return chats[i].ID < chats[j].ID
}
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
})
start := 0
if cursorData != nil {
start = sort.Search(len(chats), func(index int) bool {
chat := chats[index]
if chat.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
chat.ID > cursorData.ChatID
})
}
if start >= len(chats) {
return make([]domain.Chat, 0), false, nil
}
end := start + limit
if end > len(chats) {
end = len(chats)
}
items := make([]domain.Chat, end-start)
copy(items, chats[start:end])
return items, end < len(chats), nil
}
// ---Сообщения---
func (s *MemoryStore) CreateMessage(
chatID, senderID, text string,
) (domain.Message, error) {
messageID := uuid.NewString()
s.mu.Lock()
defer s.mu.Unlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Message{}, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == senderID {
isMember = true
break
}
}
if !isMember {
return domain.Message{}, ErrNotFound
}
createdAt := time.Now().UTC()
messages := s.messagesByChatID[chatID]
if len(messages) > 0 {
lastCreatedAt := messages[len(messages)-1].CreatedAt
// Обеспечиваем строго возрастающее время внутри каждого чата.
if !createdAt.After(lastCreatedAt) {
createdAt = lastCreatedAt.Add(time.Nanosecond)
}
}
message := domain.Message{
ID: messageID,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: createdAt,
}
s.messagesByChatID[chatID] = append(messages, message)
return message, nil
}
func (s *MemoryStore) GetMessages(
chatID, callerID string,
limit int,
cursorData *domain.MessageCursor,
) ([]domain.Message, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return nil, false, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == callerID {
isMember = true
break
}
}
if !isMember {
return nil, false, ErrNotFound
}
messages := s.messagesByChatID[chatID]
start := 0
if cursorData != nil {
// Срез уже упорядочен во время записи, поэтому вместо
// полного прохода используем бинарный поиск.
start = sort.Search(len(messages), func(index int) bool {
message := messages[index]
if message.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
message.ID > cursorData.MessageID
})
}
if start >= len(messages) {
return make([]domain.Message, 0), false, nil
}
end := len(messages)
if limit > 0 && end-start > limit {
end = start + limit
}
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
items := make([]domain.Message, end-start)
copy(items, messages[start:end])
return items, end < len(messages), nil
}
+278
View File
@@ -0,0 +1,278 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.Begin(queryContext)
if err != nil {
return domain.Chat{}, fmt.Errorf(
"begin create chat transaction: %w",
err,
)
}
defer func() {
_ = transaction.Rollback(queryContext)
}()
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO chats (
id,
title
)
VALUES ($1, $2)
RETURNING created_at
`,
chat.ID,
chat.Title,
).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
}
for position, memberID := range memberIDs {
commandTag, insertErr := transaction.Exec(
queryContext,
`
INSERT INTO chat_members (
chat_id,
user_id,
position
)
SELECT
$1,
id,
$3
FROM users
WHERE id = $2
`,
chat.ID,
memberID,
position,
)
if insertErr != nil {
return domain.Chat{}, fmt.Errorf(
"insert chat member %s: %w",
memberID,
insertErr,
)
}
// INSERT ... SELECT не вставляет строку, если пользователя нет.
// Возврат из функции активирует deferred Rollback: уже созданные
// chat и предыдущие membership-строки не останутся в базе.
if commandTag.RowsAffected() != 1 {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Chat{}, fmt.Errorf(
"commit create chat transaction: %w",
err,
)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chats AS chat
JOIN chat_members AS caller
ON caller.chat_id = chat.id
AND caller.user_id = $2
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE chat.id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
`,
chatID,
callerID,
).Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Chat{}, ErrNotFound
}
if err != nil {
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
rows pgx.Rows
err error
)
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $2
`,
userID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
AND (chat.created_at, chat.id) > ($2, $3)
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $4
`,
userID,
cursor.CreatedAt,
cursor.ChatID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query chats for user: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Chat, 0, limit+1)
for rows.Next() {
var chat domain.Chat
if err := rows.Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
); err != nil {
return nil, false, fmt.Errorf(
"scan chat page: %w",
err,
)
}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate chat page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+5
View File
@@ -0,0 +1,5 @@
package postgres
import "mtusi2026lab4/internal/application"
var _ application.Repository = (*PostgreSQLStore)(nil)
+8
View File
@@ -0,0 +1,8 @@
package postgres
import "mtusi2026lab4/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+321
View File
@@ -0,0 +1,321 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var isMember bool
err = transaction.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
write.ChatID,
write.ActorID,
).Scan(&isMember)
if err != nil {
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
}
if !isMember {
return domain.Message{}, ErrNotFound
}
_, err = transaction.Exec(
queryContext,
`
DELETE FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
AND expires_at <= CURRENT_TIMESTAMP
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
)
if err != nil {
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
}
var storedHash []byte
var storedMessageID string
err = transaction.QueryRow(
queryContext,
`
INSERT INTO message_idempotency (
user_id,
method,
canonical_path,
idempotency_key,
request_hash,
message_id,
expires_at
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
)
ON CONFLICT DO NOTHING
RETURNING request_hash, message_id::text
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
write.RequestHash[:],
message.ID,
int64(write.TTL/time.Second),
).Scan(&storedHash, &storedMessageID)
if errors.Is(err, pgx.ErrNoRows) {
err = transaction.QueryRow(
queryContext,
`
SELECT request_hash, message_id::text
FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
).Scan(&storedHash, &storedMessageID)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
}
if !bytes.Equal(storedHash, write.RequestHash[:]) {
return domain.Message{}, application.ErrIdempotencyConflict
}
err = transaction.QueryRow(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE id = $1
`,
storedMessageID,
).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
}
return message, nil
}
if err != nil {
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO messages (
id,
chat_id,
sender_id,
text
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
message.ID,
message.ChatID,
message.SenderID,
message.Text,
).Scan(&message.CreatedAt)
if err != nil {
return domain.Message{}, fmt.Errorf("insert message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
}
return message, nil
}
func (s *PostgreSQLStore) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var isMember bool
err := s.pool.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
chatID,
callerID,
).Scan(&isMember)
if err != nil {
return nil, false, fmt.Errorf(
"check chat membership: %w",
err,
)
}
if !isMember {
return nil, false, ErrNotFound
}
var rows pgx.Rows
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE chat_id = $1
ORDER BY
created_at,
id
LIMIT $2
`,
chatID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2, $3)
ORDER BY
created_at,
id
LIMIT $4
`,
chatID,
cursor.CreatedAt,
cursor.MessageID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query messages: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Message, 0, limit+1)
for rows.Next() {
var message domain.Message
if err := rows.Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
); err != nil {
return nil, false, fmt.Errorf(
"scan message page: %w",
err,
)
}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate message page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+108
View File
@@ -0,0 +1,108 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab4/internal/domain"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
INSERT INTO sessions (
token_hash,
user_id,
expires_at
)
VALUES ($1, $2, $3)
`,
tokenHash,
userID,
expiresAt,
)
if err != nil {
return fmt.Errorf("insert session: %w", err)
}
return nil
}
func (s *PostgreSQLStore) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
app_user.id::text,
app_user.username,
app_user.display_name,
app_user.created_at
FROM sessions AS session
JOIN users AS app_user
ON app_user.id = session.user_id
WHERE session.token_hash = $1
AND session.expires_at > CURRENT_TIMESTAMP
`,
tokenHash,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf(
"select user by session: %w",
err,
)
}
return user, nil
}
func (s *PostgreSQLStore) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
DELETE FROM sessions
WHERE token_hash = $1
`,
tokenHash,
)
if err != nil {
return fmt.Errorf("delete session: %w", err)
}
return nil
}
+40
View File
@@ -0,0 +1,40 @@
package postgres
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type PostgreSQLStore struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
func NewPostgreSQLStore(
pool *pgxpool.Pool,
queryTimeout time.Duration,
) *PostgreSQLStore {
return &PostgreSQLStore{
pool: pool,
queryTimeout: queryTimeout,
}
}
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
return s.pool.Ping(queryContext)
}
func (s *PostgreSQLStore) Close() {
s.pool.Close()
}
func (s *PostgreSQLStore) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.queryTimeout)
}
+144
View File
@@ -0,0 +1,144 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func (s *PostgreSQLStore) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
}
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO users (
id,
username,
display_name,
password_hash
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
user.ID,
user.Username,
user.DisplayName,
passwordHash,
).Scan(&user.CreatedAt)
if err == nil {
return user, nil
}
var postgresError *pgconn.PgError
if errors.As(err, &postgresError) &&
postgresError.Code == "23505" &&
postgresError.ConstraintName == "users_username_unique" {
return domain.User{}, ErrConflict
}
return domain.User{}, fmt.Errorf("insert user: %w", err)
}
func (s *PostgreSQLStore) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at
FROM users
WHERE id = $1
`,
userID,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf("select user by id: %w", err)
}
return user, nil
}
func (s *PostgreSQLStore) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
user domain.User
passwordHash string
)
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at,
password_hash
FROM users
WHERE username = $1
`,
username,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
&passwordHash,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, "", ErrNotFound
}
if err != nil {
return domain.User{}, "", fmt.Errorf(
"select user by username: %w",
err,
)
}
return user, passwordHash, nil
}
+175
View File
@@ -0,0 +1,175 @@
package redis
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
)
const chatKeyPrefix = "chat:v2:"
var ErrMiss = errors.New("cache miss")
// ChatCache хранит только производную копию неизменяемых данных чата.
// PostgreSQL остаётся источником истины.
type ChatCache interface {
Get(ctx context.Context, chatID string) (domain.Chat, error)
Set(ctx context.Context, chat domain.Chat) error
}
type RedisChatCache struct {
client *goredis.Client
ttl time.Duration
operationTimeout time.Duration
}
func NewRedisChatCache(
redisURL string,
ttl time.Duration,
operationTimeout time.Duration,
poolSize int,
) (*RedisChatCache, error) {
options, err := goredis.ParseURL(strings.TrimSpace(redisURL))
if err != nil {
return nil, fmt.Errorf("parse Redis URL: %w", err)
}
options.DialTimeout = operationTimeout
options.ReadTimeout = operationTimeout
options.WriteTimeout = operationTimeout
options.PoolTimeout = operationTimeout
options.PoolSize = poolSize
options.MaxRetries = -1
return &RedisChatCache{
client: goredis.NewClient(options),
ttl: ttl,
operationTimeout: operationTimeout,
}, nil
}
func (c *RedisChatCache) Ping(ctx context.Context) error {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err := c.client.Ping(operationContext).Err(); err != nil {
return fmt.Errorf("ping Redis: %w", err)
}
return nil
}
func (c *RedisChatCache) Close() error {
return c.client.Close()
}
func (c *RedisChatCache) Get(
ctx context.Context,
chatID string,
) (domain.Chat, error) {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
payload, err := c.client.Get(
operationContext,
chatKey(chatID),
).Bytes()
if errors.Is(err, goredis.Nil) {
return domain.Chat{}, ErrMiss
}
if err != nil {
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
}
var chat domain.Chat
if err = json.Unmarshal(payload, &chat); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
}
if err = validateCachedChat(chat, chatID); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, err
}
return chat, nil
}
func (c *RedisChatCache) Set(
ctx context.Context,
chat domain.Chat,
) error {
payload, err := json.Marshal(chat)
if err != nil {
return fmt.Errorf("encode chat for cache: %w", err)
}
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err = c.client.Set(
operationContext,
chatKey(chat.ID),
payload,
c.ttl,
).Err(); err != nil {
return fmt.Errorf("cache chat: %w", err)
}
return nil
}
func (c *RedisChatCache) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, c.operationTimeout)
}
func (c *RedisChatCache) deleteInvalidValue(
ctx context.Context,
chatID string,
) {
_ = c.client.Del(ctx, chatKey(chatID)).Err()
}
func chatKey(chatID string) string {
return chatKeyPrefix + chatID
}
func validateCachedChat(chat domain.Chat, expectedID string) error {
if chat.ID != expectedID {
return errors.New("cached chat id does not match cache key")
}
if _, err := uuid.Parse(chat.ID); err != nil {
return errors.New("cached chat contains invalid id")
}
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
return errors.New("cached chat is incomplete")
}
if len(chat.MemberIDs) == 0 {
return errors.New("cached chat has no members")
}
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
for _, memberID := range chat.MemberIDs {
if _, err := uuid.Parse(memberID); err != nil {
return errors.New("cached chat contains invalid member id")
}
if _, exists := seenMembers[memberID]; exists {
return errors.New("cached chat contains duplicate member id")
}
seenMembers[memberID] = struct{}{}
}
return nil
}
var _ ChatCache = (*RedisChatCache)(nil)
+55
View File
@@ -0,0 +1,55 @@
package application
import (
"context"
"fmt"
"mtusi2026lab4/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
}
+27
View File
@@ -0,0 +1,27 @@
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
Method string
CanonicalPath string
IdempotencyKey string
}
+121
View File
@@ -0,0 +1,121 @@
package application
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"mtusi2026lab4/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
}
+70
View File
@@ -0,0 +1,70 @@
package application
import (
"errors"
"testing"
"time"
"mtusi2026lab4/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")
}
}
+11
View File
@@ -0,0 +1,11 @@
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")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
)
+77
View File
@@ -0,0 +1,77 @@
package application
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"mtusi2026lab4/internal/domain"
)
type canonicalMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
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)
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: make([]string, 0),
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
}
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
RequestHash: sha256.Sum256(canonicalBody),
TTL: s.idempotencyTTL,
})
}
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
}
+48
View File
@@ -0,0 +1,48 @@
package application
import (
"context"
"time"
"mtusi2026lab4/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 IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
Method string
CanonicalPath string
Key string
RequestHash [32]byte
TTL time.Duration
}
type MessageRepository interface {
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (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
}
+53
View File
@@ -0,0 +1,53 @@
package application
import (
"fmt"
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*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")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
}
for _, option := range options {
if err := option(service); err != nil {
return nil, err
}
}
return service, nil
}
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return func(service *Service) error {
if ttl < MinimumIdempotencyTTL {
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
}
service.idempotencyTTL = ttl
return nil
}
}
+57
View File
@@ -0,0 +1,57 @@
package application
import (
"context"
"errors"
"fmt"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/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)
}
+29
View File
@@ -0,0 +1,29 @@
package application
import (
"context"
"fmt"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/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,
)
}
+434
View File
@@ -0,0 +1,434 @@
package config
import (
"errors"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Config struct {
HTTPHost string
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
SessionCookieSecure bool
CursorSigningKey string
DatabaseURL string
DatabaseMaxConns int32
DatabaseMinConns int32
DatabaseMaxConnLifetime time.Duration
DatabaseMaxConnIdleTime time.Duration
DatabaseHealthCheckPeriod time.Duration
DatabaseConnectTimeout time.Duration
DatabaseQueryTimeout time.Duration
RedisURL string
RedisCacheTTL time.Duration
RedisOperationTimeout time.Duration
RedisPoolSize int
ReadinessTimeout time.Duration
ShutdownDrainDelay time.Duration
ShutdownTimeout time.Duration
}
func Load() (Config, error) {
instanceID, err := instanceIDFromEnv()
if err != nil {
return Config{}, err
}
sessionTTL, err := secondsDurationFromEnv(
"SESSION_TTL_SECONDS",
3600,
)
if err != nil {
return Config{}, err
}
idempotencyTTL, err := secondsDurationFromEnv(
"IDEMPOTENCY_TTL_SECONDS",
86400,
)
if err != nil {
return Config{}, err
}
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
)
if err != nil {
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
}
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
if err != nil {
return Config{}, err
}
databaseMaxConnLifetime, err := durationFromEnv(
"DB_MAX_CONN_LIFETIME",
30*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseMaxConnIdleTime, err := durationFromEnv(
"DB_MAX_CONN_IDLE_TIME",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseHealthCheckPeriod, err := durationFromEnv(
"DB_HEALTH_CHECK_PERIOD",
30*time.Second,
)
if err != nil {
return Config{}, err
}
databaseConnectTimeout, err := durationFromEnv(
"DB_CONNECT_TIMEOUT",
5*time.Second,
)
if err != nil {
return Config{}, err
}
databaseQueryTimeout, err := durationFromEnv(
"DB_QUERY_TIMEOUT",
3*time.Second,
)
if err != nil {
return Config{}, err
}
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
if err != nil {
return Config{}, err
}
redisCacheTTL, err := durationFromEnv(
"CACHE_TTL",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
redisOperationTimeout, err := durationFromEnv(
"CACHE_OPERATION_TIMEOUT",
250*time.Millisecond,
)
if err != nil {
return Config{}, err
}
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
if err != nil {
return Config{}, err
}
readinessTimeout, err := durationFromEnv(
"READINESS_TIMEOUT",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownDrainDelay, err := durationFromEnv(
"SHUTDOWN_DRAIN_DELAY",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownTimeout, err := durationFromEnv(
"SHUTDOWN_TIMEOUT",
10*time.Second,
)
if err != nil {
return Config{}, err
}
if databaseMinConns > databaseMaxConns {
return Config{}, errors.New(
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
)
}
if idempotencyTTL < 24*time.Hour {
return Config{}, errors.New(
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
)
}
if shutdownDrainDelay >= shutdownTimeout {
return Config{}, errors.New(
"SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT",
)
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
SessionCookieSecure: sessionCookieSecure,
CursorSigningKey: cursorSigningKey,
DatabaseURL: databaseURL,
DatabaseMaxConns: databaseMaxConns,
DatabaseMinConns: databaseMinConns,
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
DatabaseConnectTimeout: databaseConnectTimeout,
DatabaseQueryTimeout: databaseQueryTimeout,
RedisURL: redisURL,
RedisCacheTTL: redisCacheTTL,
RedisOperationTimeout: redisOperationTimeout,
RedisPoolSize: int(redisPoolSize),
ReadinessTimeout: readinessTimeout,
ShutdownDrainDelay: shutdownDrainDelay,
ShutdownTimeout: shutdownTimeout,
}, nil
}
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func instanceIDFromEnv() (string, error) {
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
if instanceID == "" {
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("resolve instance id from hostname: %w", err)
}
instanceID = hostname
}
if !instanceIDPattern.MatchString(instanceID) {
return "", errors.New(
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
)
}
return instanceID, nil
}
func (c Config) HTTPAddress() string {
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
}
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
}
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", nil
}
func envOrDefault(name, fallback string) string {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
return value
}
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseInt(raw, 10, 32)
if err != nil {
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
}
if value < int64(minimum) {
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
}
return int32(value), nil
}
func boolFromEnv(name string, fallback bool) (bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("%s must be true or false: %w", name, err)
}
return value, nil
}
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf(
"%s must be a Go duration such as 3s or 5m: %w",
name,
err,
)
}
if value <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
return value, nil
}
func secondsDurationFromEnv(
name string,
fallbackSeconds int64,
) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
raw = strconv.FormatInt(fallbackSeconds, 10)
}
seconds, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return 0, fmt.Errorf(
"%s must be an integer number of seconds: %w",
name,
err,
)
}
if seconds <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
duration, err := time.ParseDuration(raw + "s")
if err != nil {
return 0, fmt.Errorf("%s is too large: %w", name, err)
}
return duration, nil
}
+35
View File
@@ -0,0 +1,35 @@
package config
import "testing"
func TestInstanceIDFromEnvironment(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-replica_01")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID != "api-replica_01" {
t.Fatalf("got %q, want api-replica_01", instanceID)
}
}
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
if _, err := instanceIDFromEnv(); err == nil {
t.Fatal("expected unsafe instance ID to be rejected")
}
}
func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Setenv("INSTANCE_ID", "")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID == "" {
t.Fatal("hostname fallback returned an empty instance ID")
}
}
+29
View File
@@ -0,0 +1,29 @@
package config
import "testing"
func TestBoolFromEnv(t *testing.T) {
t.Run("fallback", func(t *testing.T) {
t.Setenv("TEST_BOOL", "")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || !value {
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
}
})
t.Run("explicit false", func(t *testing.T) {
t.Setenv("TEST_BOOL", "false")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || value {
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
}
})
t.Run("invalid", func(t *testing.T) {
t.Setenv("TEST_BOOL", "sometimes")
_, err := boolFromEnv("TEST_BOOL", false)
if err == nil {
t.Fatal("boolFromEnv() error = nil, want validation error")
}
})
}
+40
View File
@@ -0,0 +1,40 @@
package database
import (
"context"
"fmt"
"mtusi2026lab4/internal/config"
"github.com/jackc/pgx/v5/pgxpool"
)
func Open(
ctx context.Context,
cfg config.Config,
) (*pgxpool.Pool, error) {
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
if err != nil {
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
}
poolConfig.MaxConns = cfg.DatabaseMaxConns
poolConfig.MinConns = cfg.DatabaseMinConns
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
// NewWithConfig создаёт структуру пула, но не гарантирует,
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
}
return pool, nil
}
+21
View File
@@ -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
}
+8
View File
@@ -0,0 +1,8 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
+22
View File
@@ -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
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Session struct {
Token string
TokenType string
ExpiresAt time.Time
User User
}
+11
View File
@@ -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
}
+77
View File
@@ -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
}
+164
View File
@@ -0,0 +1,164 @@
package security
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/crypto/argon2"
)
const (
argonMemory uint32 = 19 * 1024
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
minPasswordLength = 12
maxPasswordLength = 128
)
var ErrInvalidPasswordHash = errors.New("invalid password hash")
func ValidatePassword(password string) error {
if !utf8.ValidString(password) {
return errors.New("password must be valid UTF-8")
}
length := utf8.RuneCountInString(password)
if length < minPasswordLength || length > maxPasswordLength {
return fmt.Errorf(
"password length must be between %d and %d code points",
minPasswordLength,
maxPasswordLength,
)
}
return nil
}
func HashPassword(password string) (string, error) {
if err := ValidatePassword(password); err != nil {
return "", err
}
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
hash := argon2.IDKey(
[]byte(password),
salt,
argonIterations,
argonMemory,
argonParallelism,
argonKeyLength,
)
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
encoded := fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
argonMemory,
argonIterations,
argonParallelism,
encodedSalt,
encodedHash,
)
return encoded, nil
}
func VerifyPassword(
password string,
encodedHash string,
) (bool, error) {
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
if err != nil {
return false, err
}
actualHash := argon2.IDKey(
[]byte(password),
salt,
parameters.iterations,
parameters.memory,
parameters.parallelism,
uint32(len(expectedHash)),
)
matches := subtle.ConstantTimeCompare(
actualHash,
expectedHash,
) == 1
return matches, nil
}
type argonParameters struct {
memory uint32
iterations uint32
parallelism uint8
}
func decodePasswordHash(
encodedHash string,
) (argonParameters, []byte, []byte, error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 ||
parts[0] != "" ||
parts[1] != "argon2id" {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
if version != argon2.Version {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
var parameters argonParameters
if _, err := fmt.Sscanf(
parts[3],
"m=%d,t=%d,p=%d",
&parameters.memory,
&parameters.iterations,
&parameters.parallelism,
); err != nil {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
// Ограничения не позволяют повреждённой строке из БД запросить
// гигантский объём памяти или процессорного времени.
if parameters.memory < 8*1024 ||
parameters.memory > 256*1024 ||
parameters.iterations < 1 ||
parameters.iterations > 10 ||
parameters.parallelism < 1 ||
parameters.parallelism > 8 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 16 || len(salt) > 64 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(hash) < 16 || len(hash) > 64 {
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
}
return parameters, salt, hash, nil
}
+105
View File
@@ -0,0 +1,105 @@
package security
import (
"strings"
"testing"
)
func TestPasswordHashAndVerify(t *testing.T) {
password := "Correct-password-123"
encodedHash, err := HashPassword(password)
if err != nil {
t.Fatalf("HashPassword returned error: %v", err)
}
if strings.Contains(encodedHash, password) {
t.Fatal("encoded hash contains plaintext password")
}
matches, err := VerifyPassword(password, encodedHash)
if err != nil {
t.Fatalf("VerifyPassword returned error: %v", err)
}
if !matches {
t.Fatal("correct password did not match")
}
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
if err != nil {
t.Fatalf("VerifyPassword returned error: %v", err)
}
if matches {
t.Fatal("wrong password matched")
}
}
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
password := "Correct-password-123"
firstHash, err := HashPassword(password)
if err != nil {
t.Fatalf("first HashPassword returned error: %v", err)
}
secondHash, err := HashPassword(password)
if err != nil {
t.Fatalf("second HashPassword returned error: %v", err)
}
if firstHash == secondHash {
t.Fatal("equal passwords produced equal encoded hashes")
}
}
func TestPasswordValidation(t *testing.T) {
testCases := []struct {
name string
password string
wantErr bool
}{
{
name: "minimum length",
password: "123456789012",
wantErr: false,
},
{
name: "unicode",
password: "пароль-проверка-123",
wantErr: false,
},
{
name: "colon is allowed",
password: "password:with:colon",
wantErr: false,
},
{
name: "too short",
password: "short",
wantErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidatePassword(testCase.password)
if testCase.wantErr && err == nil {
t.Fatal("expected validation error")
}
if !testCase.wantErr && err != nil {
t.Fatalf("unexpected validation error: %v", err)
}
})
}
}
func TestMalformedPasswordHash(t *testing.T) {
_, err := VerifyPassword(
"Correct-password-123",
"not-an-argon2-hash",
)
if err == nil {
t.Fatal("expected malformed hash error")
}
}
+32
View File
@@ -0,0 +1,32 @@
package security
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
)
const sessionTokenBytes = 32
func GenerateSessionToken() (string, []byte, error) {
randomBytes := make([]byte, sessionTokenBytes)
if _, err := rand.Read(randomBytes); err != nil {
return "", nil, fmt.Errorf("generate session token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(randomBytes)
tokenHash := HashSessionToken(token)
return token, tokenHash, nil
}
func HashSessionToken(token string) []byte {
digest := sha256.Sum256([]byte(token))
hash := make([]byte, len(digest))
copy(hash, digest[:])
return hash
}
+35
View File
@@ -0,0 +1,35 @@
package security
import (
"bytes"
"testing"
)
func TestGenerateSessionToken(t *testing.T) {
firstToken, firstHash, err := GenerateSessionToken()
if err != nil {
t.Fatalf("GenerateSessionToken returned error: %v", err)
}
secondToken, secondHash, err := GenerateSessionToken()
if err != nil {
t.Fatalf("GenerateSessionToken returned error: %v", err)
}
if firstToken == secondToken {
t.Fatal("generated session tokens are equal")
}
if bytes.Equal(firstHash, secondHash) {
t.Fatal("generated session token hashes are equal")
}
if len(firstHash) != 32 {
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
}
recalculatedHash := HashSessionToken(firstToken)
if !bytes.Equal(firstHash, recalculatedHash) {
t.Fatal("token hash is not reproducible")
}
}
+38
View File
@@ -0,0 +1,38 @@
package dto
import (
"time"
"mtusi2026lab4/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}
}
+39
View File
@@ -0,0 +1,39 @@
package dto
import (
"time"
"mtusi2026lab4/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}
}
+21
View File
@@ -0,0 +1,21 @@
package dto
import (
"time"
"mtusi2026lab4/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),
}
}
+26
View File
@@ -0,0 +1,26 @@
package dto
import (
"time"
"mtusi2026lab4/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,
}
}
@@ -0,0 +1,44 @@
package handlers
import (
"errors"
"net/http"
"strings"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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)
}
@@ -0,0 +1,71 @@
package handlers
import (
"errors"
"net/http"
"regexp"
"strings"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
"github.com/google/uuid"
)
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"invalid chat_id uuid", requestID)
return
}
chatID := parsedChatID.String()
idempotencyKey := r.Header.Get("Idempotency-Key")
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", 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,
Method: http.MethodPost,
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
IdempotencyKey: idempotencyKey,
})
if errors.Is(err, application.ErrIdempotencyConflict) {
response.WriteError(w, http.StatusConflict, response.CodeConflict,
"Idempotency-Key is already used for another request", requestID)
return
}
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)
}
@@ -0,0 +1,20 @@
package handlers
import (
"net/http"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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
}
h.clearSessionCookie(w)
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
}
@@ -0,0 +1,36 @@
package handlers
import (
"errors"
"net/http"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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)
}
@@ -0,0 +1,15 @@
package handlers
import (
"net/http"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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)
}
+148
View File
@@ -0,0 +1,148 @@
package handlers
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"strings"
"time"
"unicode/utf8"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/transport/http/response"
)
const maxJSONBodyBytes = 1 << 20
var (
errUnsupportedMediaType = errors.New("unsupported media type")
errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB")
)
type ReadinessChecker interface {
Ping(ctx context.Context) error
}
type Option func(*Handler)
type Handler struct {
service *application.Service
readinessChecker ReadinessChecker
readinessTimeout time.Duration
sessionCookieSecure bool
}
func NewHandler(
service *application.Service,
options ...Option,
) *Handler {
handler := &Handler{
service: service,
readinessTimeout: 2 * time.Second,
}
for _, option := range options {
option(handler)
}
return handler
}
func WithReadiness(
checker ReadinessChecker,
timeout time.Duration,
) Option {
return func(handler *Handler) {
handler.readinessChecker = checker
handler.readinessTimeout = timeout
}
}
func WithSessionCookieSecure(secure bool) Option {
return func(handler *Handler) {
handler.sessionCookieSecure = secure
}
}
func decodeJSON(r *http.Request, destination any) error {
mediaType, parameters, err := mime.ParseMediaType(
r.Header.Get("Content-Type"),
)
if err != nil || mediaType != "application/json" {
return errUnsupportedMediaType
}
if charset, exists := parameters["charset"]; exists &&
!strings.EqualFold(charset, "utf-8") {
return errUnsupportedMediaType
}
if r.Body == nil {
return errors.New("request body is empty")
}
defer r.Body.Close()
payload, err := io.ReadAll(io.LimitReader(
r.Body,
maxJSONBodyBytes+1,
))
if err != nil {
return errors.New("read request body")
}
if len(payload) > maxJSONBodyBytes {
return errJSONBodyTooLarge
}
if !utf8.Valid(payload) {
return errors.New("request body must be valid UTF-8")
}
decoder := json.NewDecoder(bytes.NewReader(payload))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return err
}
var extra json.RawMessage
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return errors.New("extra data after JSON")
}
return nil
}
func writeDecodeJSONError(
w http.ResponseWriter,
requestID string,
err error,
) {
switch {
case errors.Is(err, errUnsupportedMediaType):
response.WriteError(
w,
http.StatusUnsupportedMediaType,
response.CodeUnsupportedMediaType,
"Content-Type must be application/json",
requestID,
)
case errors.Is(err, errJSONBodyTooLarge):
response.WriteError(
w,
http.StatusRequestEntityTooLarge,
response.CodePayloadTooLarge,
err.Error(),
requestID,
)
default:
response.WriteError(
w,
http.StatusBadRequest,
response.CodeInvalidRequest,
"malformed or invalid JSON: "+err.Error(),
requestID,
)
}
}
@@ -0,0 +1,62 @@
package handlers
import (
"context"
"net/http"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
)
// HealthLive проверяет только то, что HTTP-процесс работает.
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
response.WriteJSON(
w,
http.StatusOK,
map[string]string{"status": "ok"},
requestID,
)
}
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
// в которых PostgreSQL намеренно не создаётся.
if h.readinessChecker == nil {
response.WriteJSON(
w,
http.StatusOK,
map[string]string{"status": "ok"},
requestID,
)
return
}
ctx, cancel := context.WithTimeout(
r.Context(),
h.readinessTimeout,
)
defer cancel()
if err := h.readinessChecker.Ping(ctx); err != nil {
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is not ready",
requestID,
)
return
}
response.WriteJSON(
w,
http.StatusOK,
map[string]string{"status": "ok"},
requestID,
)
}
@@ -0,0 +1,32 @@
package handlers
import (
"errors"
"net/http"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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)
}
@@ -0,0 +1,45 @@
package handlers
import (
"errors"
"net/http"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/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)
}
@@ -0,0 +1,29 @@
package handlers
import (
"net/http"
"strconv"
"mtusi2026lab4/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
}
@@ -0,0 +1,39 @@
package handlers
import (
"net/http"
"time"
)
const sessionCookieName = "mtusi_session"
func (h *Handler) setSessionCookie(
w http.ResponseWriter,
token string,
expiresAt time.Time,
) {
maxAge := int(time.Until(expiresAt).Seconds())
if maxAge < 1 {
maxAge = 1
}
h.writeSessionCookie(w, token, expiresAt, maxAge)
}
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
}
func (h *Handler) writeSessionCookie(
w http.ResponseWriter,
value string,
expiresAt time.Time,
maxAge int,
) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName, Value: value, Path: "/",
Expires: expiresAt, MaxAge: maxAge,
HttpOnly: true, Secure: h.sessionCookieSecure,
SameSite: http.SameSiteStrictMode,
})
}
@@ -0,0 +1,61 @@
package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestSessionCookieIsHardened(t *testing.T) {
handler := &Handler{sessionCookieSecure: true}
recorder := httptest.NewRecorder()
handler.setSessionCookie(
recorder,
"secret-token",
time.Now().Add(time.Hour),
)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
t.Fatalf("unexpected cookie: %#v", cookie)
}
if cookie.Path != "/" || cookie.Domain != "" {
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
}
if !cookie.HttpOnly || !cookie.Secure {
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
}
if cookie.SameSite != http.SameSiteStrictMode {
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
}
if cookie.MaxAge < 1 {
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
}
}
func TestClearSessionCookieExpiresIt(t *testing.T) {
handler := &Handler{}
recorder := httptest.NewRecorder()
handler.clearSessionCookie(recorder)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Value != "" || cookie.MaxAge != -1 {
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
}
if !cookie.Expires.Before(time.Now()) {
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
}
}
@@ -0,0 +1,80 @@
package handlers
import (
"errors"
"net/http"
"unicode/utf8"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
)
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
func (h *Handler) CreateSession(
w http.ResponseWriter,
r *http.Request,
) {
requestID := middleware.GetRequestID(r.Context())
username, password, ok := r.BasicAuth()
if !ok || username == "" ||
!utf8.ValidString(username) || !utf8.ValidString(password) {
writeBasicUnauthorized(w, requestID)
return
}
session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{
Username: username,
Password: password,
})
if errors.Is(err, application.ErrCredentialState) {
response.WriteError(
w,
http.StatusInternalServerError,
response.CodeInternalError,
"stored password hash is invalid",
requestID,
)
return
}
if errors.Is(err, application.ErrInvalidCredentials) {
writeBasicUnauthorized(w, requestID)
return
}
if err != nil {
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is temporarily unavailable",
requestID,
)
return
}
h.setSessionCookie(w, session.Token, session.ExpiresAt)
response.WriteJSON(
w,
http.StatusCreated,
dto.SessionFromDomain(session),
requestID,
)
}
func writeBasicUnauthorized(
w http.ResponseWriter,
requestID string,
) {
w.Header().Set("WWW-Authenticate", basicChallenge)
response.WriteError(
w,
http.StatusUnauthorized,
response.CodeUnauthorized,
"invalid username or password",
requestID,
)
}
+65
View File
@@ -0,0 +1,65 @@
package handlers
import (
"errors"
"net/http"
"strings"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
)
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
var request dto.CreateUserRequest
if err := decodeJSON(r, &request); err != nil {
writeDecodeJSONError(w, requestID, err)
return
}
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,
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "),
requestID,
)
return
}
if errors.Is(err, domain.ErrConflict) {
response.WriteError(
w,
http.StatusConflict,
response.CodeConflict,
"username already exists",
requestID,
)
return
}
if err != nil {
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is temporarily unavailable",
requestID,
)
return
}
response.WriteJSON(
w,
http.StatusCreated,
dto.UserFromDomain(createdUser),
requestID,
)
}
+113
View File
@@ -0,0 +1,113 @@
package middleware
import (
"context"
"errors"
"net/http"
"strings"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/response"
)
const bearerChallenge = `Bearer realm="messenger"`
const (
UserContextKey contextKey = "current_user"
sessionTokenHashKey contextKey = "session_token_hash"
)
type SessionAuthenticator interface {
Authenticate(
ctx context.Context,
token string,
) (domain.User, []byte, error)
}
func RequireAuth(
authenticator SessionAuthenticator,
next http.HandlerFunc,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := GetRequestID(r.Context())
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok {
writeBearerUnauthorized(w, requestID)
return
}
user, tokenHash, err := authenticator.Authenticate(
r.Context(),
token,
)
if errors.Is(err, domain.ErrNotFound) {
writeBearerUnauthorized(w, requestID)
return
}
if err != nil {
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is temporarily unavailable",
requestID,
)
return
}
ctx := context.WithValue(
r.Context(),
UserContextKey,
user,
)
ctx = context.WithValue(
ctx,
sessionTokenHashKey,
tokenHash,
)
next(w, r.WithContext(ctx))
}
}
func GetCurrentUser(ctx context.Context) domain.User {
user, _ := ctx.Value(UserContextKey).(domain.User)
return user
}
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
result := make([]byte, len(tokenHash))
copy(result, tokenHash)
return result
}
func bearerToken(authorization string) (string, bool) {
parts := strings.Fields(authorization)
if len(parts) != 2 ||
!strings.EqualFold(parts[0], "Bearer") ||
parts[1] == "" {
return "", false
}
return parts[1], true
}
func writeBearerUnauthorized(
w http.ResponseWriter,
requestID string,
) {
w.Header().Set("WWW-Authenticate", bearerChallenge)
response.WriteError(
w,
http.StatusUnauthorized,
response.CodeUnauthorized,
"invalid or expired bearer token",
requestID,
)
}
@@ -0,0 +1,48 @@
package middleware
import (
"net/http"
"sync/atomic"
"mtusi2026lab4/internal/transport/http/response"
)
// AvailabilityGate lets a process reject new work before its HTTP listener is
// closed. Existing requests are still drained by http.Server.Shutdown.
type AvailabilityGate struct {
accepting atomic.Bool
}
func NewAvailabilityGate() *AvailabilityGate {
gate := &AvailabilityGate{}
gate.accepting.Store(true)
return gate
}
func (g *AvailabilityGate) BeginDrain() {
g.accepting.Store(false)
}
func (g *AvailabilityGate) IsAccepting() bool {
return g.accepting.Load()
}
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Liveness deliberately stays available while the process drains. The
// readiness endpoint and all business traffic receive 503 immediately.
if g.IsAccepting() || r.URL.Path == "/health/live" {
next.ServeHTTP(w, r)
return
}
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is draining",
GetRequestID(r.Context()),
)
})
}
@@ -0,0 +1,38 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) {
gate := NewAvailabilityGate()
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := RequestID(gate.Middleware(next))
before := httptest.NewRecorder()
handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
if before.Code != http.StatusNoContent {
t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent)
}
gate.BeginDrain()
draining := httptest.NewRecorder()
handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil))
if draining.Code != http.StatusServiceUnavailable {
t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable)
}
if draining.Header().Get("X-Request-Id") == "" {
t.Fatal("draining response is missing X-Request-Id")
}
live := httptest.NewRecorder()
handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil))
if live.Code != http.StatusNoContent {
t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent)
}
}
@@ -0,0 +1,15 @@
package middleware
import "net/http"
const InstanceIDHeader = "X-Instance-Id"
// InstanceID identifies the process that actually produced the response.
// It must wrap recovery and routing so even errors, health checks and 404/405
// responses carry the same stable process identifier.
func InstanceID(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(InstanceIDHeader, instanceID)
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := InstanceID("api-01", mux)
for _, test := range []struct {
path string
wantStatus int
}{
{path: "/ok", wantStatus: http.StatusNoContent},
{path: "/missing", wantStatus: http.StatusNotFound},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
if recorder.Code != test.wantStatus {
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
}
}
}
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("test panic")
})
handler := InstanceID("api-panic", Recovery(panicking))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("got status %d, want 500", recorder.Code)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
t.Fatalf("got instance ID %q, want api-panic", got)
}
}
@@ -0,0 +1,44 @@
package middleware
import (
"log"
"net/http"
"time"
)
// responseWriterInterceptor перехватывает статус-код ответа для логов
type responseWriterInterceptor struct {
http.ResponseWriter
statusCode int
}
func (w *responseWriterInterceptor) WriteHeader(code int) {
w.statusCode = code
w.ResponseWriter.WriteHeader(code)
}
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
interceptor := &responseWriterInterceptor{
ResponseWriter: w,
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
}
next.ServeHTTP(interceptor, r)
reqID := GetRequestID(r.Context())
duration := time.Since(start)
// метаданные без r.Body
log.Printf(
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
r.Method,
r.URL.Path,
interceptor.statusCode,
duration,
reqID,
)
})
}
@@ -0,0 +1,28 @@
package middleware
import (
"net/http"
"mtusi2026lab4/internal/transport/http/response"
)
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
reqID := GetRequestID(r.Context())
//из контракта: не раскрывать stack trace и внутренности
response.WriteError(
w,
http.StatusInternalServerError,
response.CodeInternalError,
"internal server error",
reqID,
)
}
}()
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,35 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
)
type contextKey string
const RequestIDKey contextKey = "request_id"
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := r.Header.Get("X-Request-Id")
if reqID == "" {
reqID = uuid.NewString()
}
w.Header().Set("X-Request-Id", reqID)
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetRequestID достает ID запроса из контекста
func GetRequestID(ctx context.Context) string {
if val, ok := ctx.Value(RequestIDKey).(string); ok {
return val
}
return uuid.NewString()
}
@@ -0,0 +1,63 @@
package response
import (
"encoding/json"
"net/http"
)
// коды ошибок по контракту
const (
CodeInvalidRequest = "invalid_request"
CodePayloadTooLarge = "payload_too_large"
CodeUnsupportedMediaType = "unsupported_media_type"
CodeUnauthorized = "unauthorized"
CodeNotFound = "not_found"
CodeConflict = "conflict"
CodeUnavailable = "unavailable"
CodeInternalError = "internal_error"
)
type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
// ErrorResponse — строгое тело ответа при любой ошибке
type ErrorResponse struct {
Error ErrorPayload `json:"error"`
}
// WriteJSON отправляет любой успешный ответ с правильными заголовками
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if requestID != "" {
w.Header().Set("X-Request-Id", requestID)
}
w.WriteHeader(statusCode)
if data != nil {
_ = json.NewEncoder(w).Encode(data)
}
}
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if requestID != "" {
w.Header().Set("X-Request-Id", requestID)
}
w.WriteHeader(statusCode)
resp := ErrorResponse{
Error: ErrorPayload{
Code: code,
Message: message,
RequestID: requestID,
},
}
_ = json.NewEncoder(w).Encode(resp)
}