lab2: fix review round 2 — cache versioning, UUID normalization, cursor validation, ready deps
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-10 07:46:39 +03:00
parent 40f260612f
commit 6e3515d71b
8 changed files with 160 additions and 57 deletions
+17 -3
View File
@@ -28,16 +28,27 @@ func (s *ChatService) Create(ctx context.Context, callerID, title string, member
return nil, ErrInvalidInput
}
// Нормализация UUID: убираем разницу регистра.
normalized := make([]string, 0, len(memberIDs))
seen := make(map[string]struct{}, len(memberIDs))
callerFound := false
callerParsed, err := uuid.Parse(callerID)
if err != nil {
return nil, ErrInvalidInput
}
callerID = callerParsed.String()
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
parsed, err := uuid.Parse(id)
if err != nil {
return nil, ErrInvalidInput
}
id = parsed.String()
if _, dup := seen[id]; dup {
return nil, ErrInvalidInput
}
seen[id] = struct{}{}
normalized = append(normalized, id)
if id == callerID {
callerFound = true
}
@@ -58,7 +69,7 @@ func (s *ChatService) Create(ctx context.Context, callerID, title string, member
c := &domain.Chat{
ID: newID(),
Title: title,
MemberIDs: memberIDs,
MemberIDs: normalized,
CreatedAt: nowUTC(),
}
if err := s.chats.Create(ctx, c); err != nil {
@@ -68,9 +79,12 @@ 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 {
parsed, err := uuid.Parse(chatID)
if err != nil {
return nil, ErrInvalidInput
}
chatID = parsed.String()
ok, err := s.chats.IsMember(ctx, chatID, callerID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
+12 -3
View File
@@ -4,27 +4,36 @@ import (
"encoding/base64"
"strings"
"time"
"github.com/google/uuid"
)
// encodeCursor кодирует (scope, created_at, id) в base64.
func encodeCursor(scope string, createdAt time.Time, id string) string {
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
// decodeCursor декодирует и проверяет scope.
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
raw, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return time.Time{}, "", ErrInvalidInput
}
parts := strings.SplitN(string(raw), "|", 3)
if len(parts) != 3 || parts[0] != expectedScope {
if len(parts) != 3 {
return time.Time{}, "", ErrInvalidInput
}
if _, err := uuid.Parse(parts[0]); err != nil {
return time.Time{}, "", ErrInvalidInput
}
if parts[0] != expectedScope {
return time.Time{}, "", ErrInvalidInput
}
t, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return time.Time{}, "", ErrInvalidInput
}
if _, err := uuid.Parse(parts[2]); err != nil {
return time.Time{}, "", ErrInvalidInput
}
return t, parts[2], nil
}
+24 -4
View File
@@ -23,9 +23,12 @@ func NewMessageService(messages repository.MessageRepository, chats repository.C
}
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
if _, err := uuid.Parse(chatID); err != nil {
parsed, err := uuid.Parse(chatID)
if err != nil {
return nil, ErrInvalidInput
}
chatID = parsed.String()
if !validateText(text) {
return nil, ErrInvalidInput
}
@@ -50,16 +53,23 @@ func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string
if err := s.messages.Create(ctx, m); err != nil {
return nil, err
}
// Инвалидация через увеличение версии чата + удаление старых ключей.
// Ошибки Redis игнорируем — при недоступности кэш просто устареет по TTL.
if s.cache != nil {
s.cache.IncrVersion(ctx, chatID)
_ = 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 {
parsed, err := uuid.Parse(chatID)
if err != nil {
return nil, "", ErrInvalidInput
}
chatID = parsed.String()
if limit < 1 || limit > 100 {
return nil, "", ErrInvalidInput
}
@@ -75,9 +85,15 @@ func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor stri
return nil, "", ErrNotFound
}
// Проверяем кэш. Если версия изменилась между GetVersion и Get — не используем.
var versionBefore int64
if s.cache != nil {
versionBefore = s.cache.GetVersion(ctx, chatID)
if items, next, hit := s.cache.Get(ctx, chatID, cursor, limit); hit {
return items, next, nil
// Проверяем, что версия не изменилась с момента Set
if s.cache.GetVersion(ctx, chatID) == versionBefore {
return items, next, nil
}
}
}
@@ -106,8 +122,12 @@ func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor stri
next = encodeCursor(chatID, last.CreatedAt, last.ID)
}
// Записываем в кэш только если версия не изменилась за время чтения БД.
if s.cache != nil {
s.cache.Set(ctx, chatID, cursor, limit, items, next)
versionAfter := s.cache.GetVersion(ctx, chatID)
if versionBefore == versionAfter {
s.cache.Set(ctx, chatID, cursor, limit, items, next)
}
}
return items, next, nil
}