forked from mtusi2026/mtusi2026lab5
71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package domain
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// MaxMessageAttachments is the contract limit for attachment_ids on a message.
|
|
const MaxMessageAttachments = 10
|
|
|
|
type Message struct {
|
|
ID uuid.UUID
|
|
ChatID uuid.UUID
|
|
SenderID uuid.UUID
|
|
Text string
|
|
AttachmentIDs []uuid.UUID
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
// MessageIdempotency is the client Idempotency-Key together with the fingerprint
|
|
// of the payload it was first used with. The same key and fingerprint replay the
|
|
// stored message; the same key with another payload is a conflict.
|
|
type MessageIdempotency struct {
|
|
Key string
|
|
RequestHash [sha256.Size]byte
|
|
}
|
|
|
|
type MessageDraft struct {
|
|
ChatID uuid.UUID
|
|
SenderID uuid.UUID
|
|
Text string
|
|
AttachmentIDs []uuid.UUID
|
|
Idempotency MessageIdempotency
|
|
}
|
|
|
|
// Validate enforces the contract rule that a message carries either non-blank
|
|
// text or at least one attachment, never neither.
|
|
func (d MessageDraft) Validate() error {
|
|
if strings.TrimSpace(d.Text) == "" && len(d.AttachmentIDs) == 0 {
|
|
return fmt.Errorf("message has neither text nor attachments: %w", ErrValidation)
|
|
}
|
|
|
|
if len(d.AttachmentIDs) > MaxMessageAttachments {
|
|
return fmt.Errorf("too many attachments: %w", ErrValidation)
|
|
}
|
|
|
|
seen := make(map[uuid.UUID]struct{}, len(d.AttachmentIDs))
|
|
|
|
for _, id := range d.AttachmentIDs {
|
|
if id == uuid.Nil {
|
|
return fmt.Errorf("attachment id is empty: %w", ErrValidation)
|
|
}
|
|
|
|
if _, ok := seen[id]; ok {
|
|
return fmt.Errorf("duplicate attachment id %s: %w", id, ErrValidation)
|
|
}
|
|
|
|
seen[id] = struct{}{}
|
|
}
|
|
|
|
if d.Idempotency.Key == "" {
|
|
return fmt.Errorf("idempotency key is missing: %w", ErrValidation)
|
|
}
|
|
|
|
return nil
|
|
}
|