Files
mtusi2026lab7/internal/chat/message.go
T
kudesn1k 8054913ef9
Application / e2e (pull_request) Blocked by required conditions
Application / unit (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
2026-11-30 10:54:41 +03:00

70 lines
1.9 KiB
Go

package chat
import (
"fmt"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const (
MaxTextCodePoints = 4000
MaxAttachments = 10
)
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
AttachmentIDs []uuid.UUID
}
// NewMessage keeps text and attachment order verbatim; it owns its attachment slice.
func NewMessage(id, chatID, senderID uuid.UUID, text string, attachmentIDs ...uuid.UUID) (Message, error) {
if len(attachmentIDs) > MaxAttachments {
return Message{}, apperr.Invalid("attachment_ids must have at most 10 entries")
}
seen := make(map[uuid.UUID]struct{}, len(attachmentIDs))
for _, id := range attachmentIDs {
if id == uuid.Nil {
return Message{}, apperr.Invalid("attachment_ids must contain non-nil UUIDs")
}
if _, duplicate := seen[id]; duplicate {
return Message{}, apperr.Invalid("attachment_ids must be unique")
}
seen[id] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return Message{}, apperr.Invalid("text must not be blank")
}
if utf8.RuneCountInString(text) > MaxTextCodePoints {
return Message{}, apperr.Invalid(fmt.Sprintf("text must be at most %d characters", MaxTextCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(text, 0) {
return Message{}, apperr.Invalid("text must not contain the NUL character")
}
return Message{
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: ident.TimeOf(id),
AttachmentIDs: slices.Clone(attachmentIDs),
}, nil
}
// SameContent reports whether two messages say the same thing, whatever their
// ids and times.
func (m Message) SameContent(other Message) bool {
return m.Text == other.Text && slices.Equal(m.AttachmentIDs, other.AttachmentIDs)
}