134 lines
3.5 KiB
Go
134 lines
3.5 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"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
|
|
}
|
|
|
|
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache) *MessageService {
|
|
return &MessageService{messages: messages, chats: chats, cache: cache}
|
|
}
|
|
|
|
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
|
|
parsed, err := uuid.Parse(chatID)
|
|
if err != nil {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
chatID = parsed.String()
|
|
|
|
if !validateText(text) {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
ok, err := s.chats.IsMember(ctx, chatID, senderID)
|
|
if err != nil {
|
|
if errors.Is(err, repository.ErrNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
if !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
m := &domain.Message{
|
|
ID: newID(),
|
|
ChatID: chatID,
|
|
SenderID: senderID,
|
|
Text: text,
|
|
CreatedAt: nowUTC(),
|
|
}
|
|
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) {
|
|
parsed, err := uuid.Parse(chatID)
|
|
if err != nil {
|
|
return nil, "", ErrInvalidInput
|
|
}
|
|
chatID = parsed.String()
|
|
|
|
if limit < 1 || limit > 100 {
|
|
return nil, "", ErrInvalidInput
|
|
}
|
|
|
|
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
|
if err != nil {
|
|
if errors.Is(err, repository.ErrNotFound) {
|
|
return nil, "", ErrNotFound
|
|
}
|
|
return nil, "", err
|
|
}
|
|
if !ok {
|
|
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 {
|
|
// Проверяем, что версия не изменилась с момента Set
|
|
if s.cache.GetVersion(ctx, chatID) == versionBefore {
|
|
return items, next, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
cursorTime := time.Unix(0, 0).UTC()
|
|
cursorID := "00000000-0000-0000-0000-000000000000"
|
|
if cursor != "" {
|
|
t, id, err := decodeCursor(cursor, chatID)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
cursorTime, cursorID = t, id
|
|
}
|
|
|
|
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if items == nil {
|
|
items = []*domain.Message{}
|
|
}
|
|
|
|
var next string
|
|
if len(items) > limit {
|
|
items = items[:limit]
|
|
last := items[limit-1]
|
|
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
|
}
|
|
|
|
// Записываем в кэш только если версия не изменилась за время чтения БД.
|
|
if s.cache != nil {
|
|
versionAfter := s.cache.GetVersion(ctx, chatID)
|
|
if versionBefore == versionAfter {
|
|
s.cache.Set(ctx, chatID, cursor, limit, items, next)
|
|
}
|
|
}
|
|
return items, next, nil
|
|
}
|