- X-Instance-Id, обязательный Idempotency-Key (PostgreSQL, одна транзакция) - HAProxy + 2..N реплик API, readiness/drain по SIGTERM, однократные миграции - скрипты stop-one/restore/restart/rolling-update/collect-evidence - трек 1: параметризованный стенд, cmd/bench, оркестратор и анализ - workflow реального прогона Docker-стенда на GitHub Actions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
162 lines
4.8 KiB
Go
162 lines
4.8 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-удаление в режиме 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
|
|
}
|
|
|
|
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) // ← GetVersion не возвращает ошибку, ок
|
|
if items, next, hit := s.cache.Get(ctx, chatID, versionBefore, cursor, limit); hit { // ← Get: при ошибке false
|
|
// Проверяем, что версия не изменилась с момента 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, versionBefore, cursor, limit, items, next)
|
|
}
|
|
}
|
|
return items, next, nil
|
|
}
|