forked from mtusi2026/mtusi2026lab3
- версия истории чата хранится в PostgreSQL (chats.version, миграция 0003) и растёт в одной транзакции с сообщением; ключ кэша включает её, поэтому ошибка любой команды Redis не может вернуть устаревшую историю - членство и версия читаются одним запросом; INCR/GET версии в Redis удалены - пароль из одних пробельных символов -> 400 (unit-тест validatePassword) - student-tests/regressions.py: сценарий проверки с Redis ACL -incr и пароль - CI: тот же тест против кода до исправления; все серии трека 1 заново
154 lines
4.4 KiB
Go
154 lines
4.4 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"regexp"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/charawein/mtusi2026lab3/internal/domain"
|
|
"github.com/charawein/mtusi2026lab3/internal/repository"
|
|
redisrepo "github.com/charawein/mtusi2026lab3/internal/repository/redis"
|
|
)
|
|
|
|
type MessageService struct {
|
|
messages repository.MessageRepository
|
|
chats repository.ChatRepository
|
|
cache *redisrepo.MessageCache
|
|
idempotencyTTL time.Duration
|
|
}
|
|
|
|
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache, idempotencyTTL time.Duration) *MessageService {
|
|
return &MessageService{messages: messages, chats: chats, cache: cache, idempotencyTTL: idempotencyTTL}
|
|
}
|
|
|
|
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
|
|
// requestHash — отпечаток семантики тела запроса. Хешируем уже разобранные поля,
|
|
// а не сырые байты, поэтому порядок ключей и пробелы в JSON не влияют на результат.
|
|
func requestHash(text string) string {
|
|
raw, _ := json.Marshal(struct {
|
|
Text string `json:"text"`
|
|
}{Text: text})
|
|
sum := sha256.Sum256(raw)
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
// Send создаёт сообщение с обязательным Idempotency-Key. Повтор с тем же ключом
|
|
// и телом возвращает исходное сообщение, с другим телом — ErrConflict.
|
|
// Доступ к чату проверяется при каждом повторе.
|
|
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text, idempotencyKey string) (*domain.Message, error) {
|
|
if !idempotencyKeyRe.MatchString(idempotencyKey) {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
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(),
|
|
}
|
|
stored, created, err := s.messages.CreateIdempotent(ctx, m, idempotencyKey, requestHash(text), s.idempotencyTTL)
|
|
if err != nil {
|
|
if errors.Is(err, repository.ErrConflict) {
|
|
return nil, ErrConflict
|
|
}
|
|
return nil, err
|
|
}
|
|
if !created {
|
|
return stored, nil
|
|
}
|
|
|
|
// Версия чата уже увеличена в транзакции записи; здесь только режим scan.
|
|
if s.cache != nil {
|
|
s.cache.OnWrite(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
|
|
}
|
|
|
|
// Членство и версия истории — одним запросом к PostgreSQL. Версия читается
|
|
// до истории, поэтому под ключом версии v лежат данные не старее v.
|
|
version, ok, err := s.chats.MemberVersion(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 {
|
|
if items, next, hit := s.cache.Get(ctx, chatID, version, cursor, limit); hit {
|
|
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 {
|
|
s.cache.Set(ctx, chatID, version, cursor, limit, items, next)
|
|
}
|
|
return items, next, nil
|
|
}
|