lab2: fix review — cache consistency, readiness, timeouts, uuid validation, tuple index
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-10 01:14:56 +03:00
parent a327909856
commit 40f260612f
21 changed files with 185 additions and 189 deletions
+8 -1
View File
@@ -5,6 +5,8 @@ import (
"errors"
"time"
"github.com/google/uuid"
"github.com/charawein/mtusi2026lab2/internal/domain"
"github.com/charawein/mtusi2026lab2/internal/repository"
)
@@ -29,6 +31,9 @@ func (s *ChatService) Create(ctx context.Context, callerID, title string, member
seen := make(map[string]struct{}, len(memberIDs))
callerFound := false
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
return nil, ErrInvalidInput
}
if _, dup := seen[id]; dup {
return nil, ErrInvalidInput
}
@@ -63,6 +68,9 @@ func (s *ChatService) Create(ctx context.Context, callerID, title string, member
}
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
if _, err := uuid.Parse(chatID); err != nil {
return nil, ErrInvalidInput
}
ok, err := s.chats.IsMember(ctx, chatID, callerID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
@@ -102,7 +110,6 @@ func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit i
if err != nil {
return nil, "", err
}
if items == nil {
items = []*domain.Chat{}
}
+6 -16
View File
@@ -3,20 +3,10 @@ package service
import "errors"
var (
// ErrInvalidInput — невалидные данные от клиента (не проходит валидацию).
// Мапится в HTTP 400 invalid_request.
ErrInvalidInput = errors.New("invalid input")
// ErrUnauthorized — нет аутентификации или она недействительна.
// Мапится в HTTP 401 unauthorized.
ErrUnauthorized = errors.New("unauthorized")
// ErrNotFound — объект не существует или недоступен вызывающему.
// README требует: чужой объект → 404, чтобы не раскрывать существование.
// Мапится в HTTP 404 not_found.
ErrNotFound = errors.New("not found")
// ErrConflict — нарушение уникальности (занятый username).
// Мапится в HTTP 409 conflict.
ErrConflict = errors.New("conflict")
ErrInvalidInput = errors.New("invalid input")
ErrUnauthorized = errors.New("unauthorized")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrUnavailable = errors.New("unavailable")
ErrPasswordMismatch = errors.New("password mismatch")
)
+18 -19
View File
@@ -5,25 +5,27 @@ import (
"errors"
"time"
"github.com/google/uuid"
"github.com/charawein/mtusi2026lab2/internal/domain"
"github.com/charawein/mtusi2026lab2/internal/repository"
redisrepo "github.com/charawein/mtusi2026lab2/internal/repository/redis"
)
type MessageService struct {
messages repository.MessageRepository
chats repository.ChatRepository
cache *redisrepo.MessageCache
invalidate bool // ВРЕМЕННЫЙ ФЛАГ для демонстрации stale read
messages repository.MessageRepository
chats repository.ChatRepository
cache *redisrepo.MessageCache
}
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache) *MessageService {
return &MessageService{messages: messages, chats: chats, cache: cache, invalidate: false}
return &MessageService{messages: messages, chats: chats, cache: cache}
}
func (s *MessageService) SetInvalidate(v bool) { s.invalidate = v }
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
if _, err := uuid.Parse(chatID); err != nil {
return nil, ErrInvalidInput
}
if !validateText(text) {
return nil, ErrInvalidInput
}
@@ -48,15 +50,16 @@ func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string
if err := s.messages.Create(ctx, m); err != nil {
return nil, err
}
// Если invalidate=false — кэш НЕ сбрасывается, будет stale read.
if s.invalidate && s.cache != nil {
if s.cache != nil {
_ = s.cache.Invalidate(ctx, chatID)
}
return m, nil
}
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
if _, err := uuid.Parse(chatID); err != nil {
return nil, "", ErrInvalidInput
}
if limit < 1 || limit > 100 {
return nil, "", ErrInvalidInput
}
@@ -72,10 +75,9 @@ func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor stri
return nil, "", ErrNotFound
}
// Попытка достать из кэша (только для первой страницы).
if s.cache != nil && cursor == "" {
if cached, hit := s.cache.Get(ctx, chatID, cursor); hit {
return cached, "", nil
if s.cache != nil {
if items, next, hit := s.cache.Get(ctx, chatID, cursor, limit); hit {
return items, next, nil
}
}
@@ -93,7 +95,6 @@ func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor stri
if err != nil {
return nil, "", err
}
if items == nil {
items = []*domain.Message{}
}
@@ -105,10 +106,8 @@ func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor stri
next = encodeCursor(chatID, last.CreatedAt, last.ID)
}
// Кэшируем только первую страницу.
if s.cache != nil && cursor == "" {
s.cache.Set(ctx, chatID, cursor, items)
if s.cache != nil {
s.cache.Set(ctx, chatID, cursor, limit, items, next)
}
return items, next, nil
}
+1 -15
View File
@@ -4,28 +4,20 @@ import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Параметры Argon2id. Значения — стандартные рекомендации OWASP для интерактивного логина.
const (
argonTime = 1
argonMemory = 64 * 1024 // 64 MiB
argonMemory = 64 * 1024
argonThreads = 4
argonKeyLen = 32
argonSaltLen = 16
)
// ErrPasswordMismatch возвращается, если пароль не совпадает с хешем.
// Не путать с "неверный формат хеша" — это тоже ошибка, но другая.
var ErrPasswordMismatch = errors.New("password mismatch")
// hashPassword хеширует пароль через Argon2id и возвращает строку в формате
// $argon2id$v=19$m=65536,t=1,p=4$<salt>$<hash>.
func hashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
@@ -40,14 +32,11 @@ func hashPassword(password string) (string, error) {
), nil
}
// verifyPassword сравнивает пароль с хешем, возвращённым hashPassword.
// Возвращает ErrPasswordMismatch, если пароль не подходит.
func verifyPassword(password, encoded string) error {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return fmt.Errorf("invalid hash format")
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return fmt.Errorf("parse version: %w", err)
@@ -55,14 +44,12 @@ func verifyPassword(password, encoded string) error {
if version != argon2.Version {
return fmt.Errorf("incompatible version: %d", version)
}
var mem uint32
var iters uint32
var threads uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
return fmt.Errorf("parse params: %w", err)
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return fmt.Errorf("decode salt: %w", err)
@@ -71,7 +58,6 @@ func verifyPassword(password, encoded string) error {
if err != nil {
return fmt.Errorf("decode hash: %w", err)
}
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
if subtle.ConstantTimeCompare(got, want) != 1 {
return ErrPasswordMismatch