Files
mtusi2026lab2/internal/service/message.go
T
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

131 lines
2.8 KiB
Go

package service
import (
"context"
"highload/internal/model"
"highload/internal/repository"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
type MessageService struct {
repo repository.MessageRepository
userService *UserService
chatService *ChatService
}
func NewMessageService(repo repository.MessageRepository, chatService *ChatService, userService *UserService) *MessageService {
return &MessageService{repo: repo, chatService: chatService, userService: userService}
}
func (s *MessageService) CreateMessage(ctx context.Context, text, chatID, userID string) (*model.Message, error) {
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, err
}
lenText := utf8.RuneCountInString(text)
if lenText > 4000 || lenText < 1 {
return nil, ErrInvalidInput
}
trimText := strings.TrimSpace(text)
if len(trimText) == 0 {
return nil, ErrInvalidInput
}
message, err := s.repo.CreateMessage(ctx, chatID, userID, text)
if err != nil {
return nil, convertRepoError(err)
}
return message, nil
}
func (s *MessageService) GetMessagesByChatID(ctx context.Context, chatID, userID string, limit *int, cursor *string) ([]*model.Message, *string, error) {
actualLimit := 50
if limit != nil {
actualLimit = *limit
}
if actualLimit <= 0 || actualLimit > 100 {
return nil, nil, ErrInvalidInput
}
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
if err != nil {
return nil, nil, err
}
var messagePosition *repository.MessagePosition
if cursor != nil {
mesCursor, err := decodeCursor[messageCursor](*cursor)
if err != nil {
return nil, nil, ErrInvalidInput
}
if _, err := uuid.Parse(mesCursor.ChatID); err != nil {
return nil, nil, ErrInvalidInput
}
if _, err := uuid.Parse(mesCursor.MessageID); err != nil {
return nil, nil, ErrInvalidInput
}
if mesCursor.CreatedAt.IsZero() {
return nil, nil, ErrInvalidInput
}
if mesCursor.ChatID != chat.ID {
return nil, nil, ErrInvalidInput
}
messagePosition = &repository.MessagePosition{
ID: mesCursor.MessageID,
CreatedAt: mesCursor.CreatedAt,
}
}
messages, err := s.repo.GetMessagesByChatID(ctx, chat.ID, actualLimit+1, messagePosition)
if err != nil {
return nil, nil, convertRepoError(err)
}
if len(messages) > actualLimit {
mesCursor := &messageCursor{
MessageID: messages[actualLimit-1].ID,
ChatID: chat.ID,
CreatedAt: messages[actualLimit-1].CreatedAt,
}
cursor, err = encodeCursor[messageCursor](*mesCursor)
if err != nil {
return nil, nil, ErrServerError
}
return messages[:actualLimit], cursor, nil
}
return messages, nil, nil
}
type messageCursor struct {
MessageID string `json:"message_id"`
ChatID string `json:"chat_id"`
CreatedAt time.Time `json:"created_at"`
}