Files
mtusi2026lab4/internal/chat/chat.go
T

87 lines
2.6 KiB
Go

// Package chat is the chats module. Entities mirror table rows and
// carry no behaviour; membership is a query rather than a field, and
// ChatWithMembers is the projection the API renders. Both entities derive
// CreatedAt from their UUIDv7 id, so the history order (created_at, id) is
// plain id order.
package chat
import (
"bytes"
"fmt"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const (
MaxTitleCodePoints = 100
MaxMembers = 100
)
// ErrNotFound covers both a missing chat and a chat the caller is not a
// member of, so outsiders cannot probe for existence.
var ErrNotFound = apperr.NotFound("chat not found")
// ErrKeyReused answers a send whose Idempotency-Key is already bound to a
// message with a different text.
var ErrKeyReused = apperr.Conflict("Idempotency-Key was already used with a different message")
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatWithMembers struct {
Chat
MemberIDs []uuid.UUID
}
func NewChat(id uuid.UUID, title string) (Chat, error) {
if strings.TrimSpace(title) == "" {
return Chat{}, apperr.Invalid("title must not be blank")
}
if utf8.RuneCountInString(title) > MaxTitleCodePoints {
return Chat{}, apperr.Invalid(fmt.Sprintf("title must be at most %d characters", MaxTitleCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(title, 0) {
return Chat{}, apperr.Invalid("title must not contain the NUL character")
}
return Chat{ID: id, Title: title, CreatedAt: ident.TimeOf(id)}, nil
}
// ValidateMembers checks the member list of a new chat and returns its own
// copy ordered by id: members are a set, and this is the one order in which
// every read returns them.
func ValidateMembers(memberIDs []uuid.UUID, creator uuid.UUID) ([]uuid.UUID, error) {
if len(memberIDs) == 0 {
return nil, apperr.Invalid("member_ids must not be empty")
}
if len(memberIDs) > MaxMembers {
return nil, apperr.Invalid(fmt.Sprintf("member_ids must have at most %d entries", MaxMembers))
}
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
for _, m := range memberIDs {
if m == uuid.Nil {
return nil, apperr.Invalid("member_ids must not contain the nil uuid")
}
if _, dup := seen[m]; dup {
return nil, apperr.Invalid("member_ids must be unique")
}
seen[m] = struct{}{}
}
if _, ok := seen[creator]; !ok {
return nil, apperr.Invalid("member_ids must include the creator")
}
members := slices.Clone(memberIDs)
slices.SortFunc(members, func(a, b uuid.UUID) int { return bytes.Compare(a[:], b[:]) })
return members, nil
}