lab2: fix review round 2 — cache versioning, UUID normalization, cursor validation, ready deps
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user