Files
mtusi2026lab2/internal/service/message.go
T
Weinmaier_Andrew d8842a3de4
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2: postgres, sessions, redis, persistence, stale read
2026-10-09 21:30:36 +03:00

115 lines
2.9 KiB
Go

package service
import (
"context"
"errors"
"time"
"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
}
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache) *MessageService {
return &MessageService{messages: messages, chats: chats, cache: cache, invalidate: false}
}
func (s *MessageService) SetInvalidate(v bool) { s.invalidate = v }
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string) (*domain.Message, error) {
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
}
// Если invalidate=false — кэш НЕ сбрасывается, будет stale read.
if s.invalidate && 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 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
}
// Попытка достать из кэша (только для первой страницы).
if s.cache != nil && cursor == "" {
if cached, hit := s.cache.Get(ctx, chatID, cursor); hit {
return cached, "", 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 && cursor == "" {
s.cache.Set(ctx, chatID, cursor, items)
}
return items, next, nil
}