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
+34 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"time"
"github.com/redis/go-redis/v9"
@@ -28,6 +29,29 @@ func cacheKey(chatID, cursor string, limit int) string {
return fmt.Sprintf("messages:%s:%s:%d", chatID, cursor, limit)
}
func versionKey(chatID string) string {
return "chat_version:" + chatID
}
// GetVersion возвращает текущую версию чата. 0, если ключа нет.
func (c *MessageCache) GetVersion(ctx context.Context, chatID string) int64 {
v, err := c.client.Get(ctx, versionKey(chatID)).Int64()
if err != nil {
return 0
}
return v
}
// IncrVersion увеличивает версию чата. Используется в Send для инвалидации.
func (c *MessageCache) IncrVersion(ctx context.Context, chatID string) int64 {
v, err := c.client.Incr(ctx, versionKey(chatID)).Result()
if err != nil {
slog.Warn("redis incr version failed", "chat_id", chatID, "err", err)
return 0
}
return v
}
func (c *MessageCache) Get(ctx context.Context, chatID, cursor string, limit int) ([]*domain.Message, string, bool) {
raw, err := c.client.Get(ctx, cacheKey(chatID, cursor, limit)).Bytes()
if err != nil {
@@ -42,11 +66,18 @@ func (c *MessageCache) Get(ctx context.Context, chatID, cursor string, limit int
func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, limit int, items []*domain.Message, next string) {
e := cacheEntry{Items: items, NextCursor: next}
raw, _ := json.Marshal(e)
_ = c.client.Set(ctx, cacheKey(chatID, cursor, limit), raw, 30*time.Second).Err()
raw, err := json.Marshal(e)
if err != nil {
slog.Warn("marshal cache entry failed", "err", err)
return
}
if err := c.client.Set(ctx, cacheKey(chatID, cursor, limit), raw, 30*time.Second).Err(); err != nil {
// Redis недоступен — не падаем, работаем без кэша.
slog.Warn("redis set failed", "chat_id", chatID, "err", err)
}
}
// Invalidate удаляет все ключи для чата через SCAN (безопасно на больших объёмах).
// Invalidate удаляет все ключи messages:{chatID}:* через SCAN.
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
pattern := fmt.Sprintf("messages:%s:*", chatID)
iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
+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
}