Files
mtusi2026lab3/backend/internal/domain/model/message.go
T

52 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package model
import (
"crypto/sha256"
"encoding/hex"
"regexp"
"time"
"github.com/google/uuid"
)
const MaxMessageRunes = 4000
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
// а не из тела запроса.
type MessageDraft struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
Key string
PayloadHash string
}
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func WithKey(d MessageDraft, key string) (MessageDraft, error) {
if !keyPattern.MatchString(key) {
return MessageDraft{}, invalidf("Idempotency-Key: 1–128 ASCII characters required")
}
sum := sha256.Sum256([]byte(d.Text))
d.Key = key
d.PayloadHash = hex.EncodeToString(sum[:])
return d, nil
}
func NewMessageDraft(chatID, senderID uuid.UUID, text string) (MessageDraft, error) {
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
return MessageDraft{}, err
}
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text}, nil
}
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }