returned lab1
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username is already taken")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrNotMember = errors.New("user is not a chat member")
|
||||
)
|
||||
|
||||
// Repository is the persistence port required by the chat use case.
|
||||
type Repository interface {
|
||||
CreateUser(ctx context.Context, username, displayName string) (domain.User, error)
|
||||
User(ctx context.Context, id string) (domain.User, bool, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
type UseCase struct {
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func New(repository Repository) *UseCase {
|
||||
return &UseCase{repository: repository}
|
||||
}
|
||||
|
||||
func (u *UseCase) Authenticate(ctx context.Context, rawUserID string) (domain.User, error) {
|
||||
userID, valid := normalizeUUID(rawUserID)
|
||||
if !valid {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
user, exists, err := u.repository.User(ctx, userID)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !exists {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateUser(ctx context.Context, user domain.User) (domain.User, error) {
|
||||
if !validUsername(user.Username) {
|
||||
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
}
|
||||
if !validRequiredText(user.DisplayName, 100) {
|
||||
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
|
||||
}
|
||||
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName)
|
||||
if errors.Is(err, ErrUsernameTaken) {
|
||||
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
if !validRequiredText(chat.Title, 100) {
|
||||
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
|
||||
}
|
||||
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
|
||||
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
|
||||
}
|
||||
|
||||
normalizedIDs := make([]string, len(chat.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(chat.MemberIDs))
|
||||
callerIncluded := false
|
||||
for index, memberID := range chat.MemberIDs {
|
||||
normalized, valid := normalizeUUID(memberID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
|
||||
}
|
||||
if _, duplicate := seen[normalized]; duplicate {
|
||||
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
|
||||
}
|
||||
normalizedIDs[index] = normalized
|
||||
seen[normalized] = struct{}{}
|
||||
callerIncluded = callerIncluded || normalized == callerID
|
||||
}
|
||||
if !callerIncluded {
|
||||
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
|
||||
}
|
||||
|
||||
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
|
||||
if errors.Is(err, ErrUserNotFound) {
|
||||
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
return u.chatForUser(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
|
||||
chatID, valid := normalizeUUID(message.ChatID)
|
||||
if !valid {
|
||||
return domain.Message{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if !validRequiredText(message.Text, 4000) {
|
||||
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
|
||||
}
|
||||
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text)
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Message{}, notFound()
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.MessagePage{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
|
||||
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Chat{}, notFound()
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func invalid(message string) error {
|
||||
return domain.NewApplicationError(domain.ErrorInvalid, message)
|
||||
}
|
||||
|
||||
func unauthorized() error {
|
||||
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительный X-User-Id")
|
||||
}
|
||||
|
||||
func notFound() error {
|
||||
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func normalizeUUID(value string) (string, bool) {
|
||||
parsed, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
normalized := parsed.String()
|
||||
if !strings.EqualFold(value, normalized) {
|
||||
return "", false
|
||||
}
|
||||
return normalized, true
|
||||
}
|
||||
|
||||
func validUsername(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validRequiredText(value string, maxRunes int) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
|
||||
}
|
||||
Reference in New Issue
Block a user