Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
// Package chat is the chats module. Entities mirror future 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 (
|
||||
"fmt"
|
||||
"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")
|
||||
|
||||
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))
|
||||
}
|
||||
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 in the original order.
|
||||
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")
|
||||
}
|
||||
return append([]uuid.UUID(nil), memberIDs...), nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewChatDerivesCreatedAtFromID(t *testing.T) {
|
||||
id := ident.New()
|
||||
c, err := chat.NewChat(id, "Проект")
|
||||
if err != nil {
|
||||
t.Fatalf("NewChat error: %v", err)
|
||||
}
|
||||
if c.ID != id || c.Title != "Проект" || !c.CreatedAt.Equal(ident.TimeOf(id)) {
|
||||
t.Fatalf("unexpected chat %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChatValidatesTitle(t *testing.T) {
|
||||
for _, title := range []string{"", " ", strings.Repeat("я", 101)} {
|
||||
_, err := chat.NewChat(ident.New(), title)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("title %q must be rejected as invalid, got %v", title, err)
|
||||
}
|
||||
}
|
||||
if _, err := chat.NewChat(ident.New(), strings.Repeat("я", 100)); err != nil {
|
||||
t.Errorf("100 code points must be accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMembersCopiesAndKeepsOrder(t *testing.T) {
|
||||
alice, bob := ident.New(), ident.New()
|
||||
input := []uuid.UUID{bob, alice}
|
||||
members, err := chat.ValidateMembers(input, alice)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateMembers error: %v", err)
|
||||
}
|
||||
if len(members) != 2 || members[0] != bob || members[1] != alice {
|
||||
t.Fatalf("order must be preserved, got %v", members)
|
||||
}
|
||||
input[0] = ident.New()
|
||||
if members[0] != bob {
|
||||
t.Fatal("result must not alias the input slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMembersRejectsInvalidLists(t *testing.T) {
|
||||
alice, bob := ident.New(), ident.New()
|
||||
cases := map[string][]uuid.UUID{
|
||||
"empty": {},
|
||||
"nil": nil,
|
||||
"missing creator": {bob},
|
||||
"duplicate": {alice, bob, bob},
|
||||
"duplicate self": {alice, alice},
|
||||
"too many": append([]uuid.UUID{alice}, many(100)...),
|
||||
"nil uuid member": {alice, uuid.Nil},
|
||||
}
|
||||
for name, members := range cases {
|
||||
_, err := chat.ValidateMembers(members, alice)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("%s: want invalid, got %v", name, err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "member_ids") {
|
||||
t.Errorf("%s: message must name the field: %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := chat.ValidateMembers(append([]uuid.UUID{alice}, many(99)...), alice); err != nil {
|
||||
t.Errorf("100 members must be accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func many(n int) []uuid.UUID {
|
||||
out := make([]uuid.UUID, n)
|
||||
for i := range out {
|
||||
out[i] = ident.New()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
chats *Service
|
||||
}
|
||||
|
||||
func NewHandler(chats *Service) *Handler {
|
||||
return &Handler{chats: chats}
|
||||
}
|
||||
|
||||
// Register mounts the chat endpoints on a router guarded by RequireUser.
|
||||
func (h *Handler) Register(protected gin.IRouter) {
|
||||
protected.POST("/chats", auth.WithUser(h.create))
|
||||
protected.GET("/chats", auth.WithUser(h.list))
|
||||
protected.GET("/chats/:chat_id", auth.WithUser(h.get))
|
||||
protected.POST("/chats/:chat_id/messages", auth.WithUser(h.send))
|
||||
protected.GET("/chats/:chat_id/messages", auth.WithUser(h.history))
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func toChatResponse(c ChatWithMembers) ChatResponse {
|
||||
members := make([]string, 0, len(c.MemberIDs))
|
||||
for _, m := range c.MemberIDs {
|
||||
members = append(members, m.String())
|
||||
}
|
||||
return ChatResponse{
|
||||
ID: c.ID.String(),
|
||||
Title: c.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: httpx.Timestamp(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessageResponse(m Message) MessageResponse {
|
||||
return MessageResponse{
|
||||
ID: m.ID.String(),
|
||||
ChatID: m.ChatID.String(),
|
||||
SenderID: m.SenderID.String(),
|
||||
Text: m.Text,
|
||||
CreatedAt: httpx.Timestamp(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) create(c *gin.Context, actor uuid.UUID) {
|
||||
var req createChatRequest
|
||||
if err := httpx.DecodeJSON(c, &req); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
members := make([]uuid.UUID, 0, len(req.MemberIDs))
|
||||
for _, raw := range req.MemberIDs {
|
||||
id, err := ident.Parse(raw)
|
||||
if err != nil {
|
||||
httpx.Error(c, apperr.Invalid("member_ids must contain valid UUIDs"))
|
||||
return
|
||||
}
|
||||
members = append(members, id)
|
||||
}
|
||||
chat, err := h.chats.Create(c.Request.Context(), actor, req.Title, members)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *Handler) list(c *gin.Context, actor uuid.UUID) {
|
||||
limit, after, err := listing(c, actor)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
page, err := h.chats.List(c.Request.Context(), actor, after, limit)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, actor, toChatResponse))
|
||||
}
|
||||
|
||||
func (h *Handler) get(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.Get(c.Request.Context(), actor, chatID)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *Handler) send(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
var req createMessageRequest
|
||||
if err := httpx.DecodeJSON(c, &req); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
message, err := h.chats.Send(c.Request.Context(), actor, chatID, req.Text)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, toMessageResponse(message))
|
||||
}
|
||||
|
||||
func (h *Handler) history(c *gin.Context, actor uuid.UUID) {
|
||||
chatID, err := chatParam(c)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
limit, after, err := listing(c, chatID)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
page, err := h.chats.History(c.Request.Context(), actor, chatID, after, limit)
|
||||
if err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, chatID, toMessageResponse))
|
||||
}
|
||||
|
||||
func chatParam(c *gin.Context) (uuid.UUID, error) {
|
||||
id, err := ident.Parse(c.Param("chat_id"))
|
||||
if err != nil {
|
||||
return uuid.Nil, apperr.Invalid("chat_id must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// listing parses limit and cursor; the cursor must belong to scope, and a
|
||||
// present but empty cursor is rejected like a malformed one.
|
||||
func listing(c *gin.Context, scope uuid.UUID) (int, *uuid.UUID, error) {
|
||||
limit, err := pagination.ParseLimit(c.Query("limit"))
|
||||
if err != nil {
|
||||
return 0, nil, apperr.Wrap(apperr.KindInvalid, err.Error(), err)
|
||||
}
|
||||
token, present := c.GetQuery("cursor")
|
||||
if !present {
|
||||
return limit, nil, nil
|
||||
}
|
||||
last, err := pagination.DecodeCursor(token, scope)
|
||||
if err != nil {
|
||||
return 0, nil, apperr.Wrap(apperr.KindInvalid, "cursor is invalid for this resource", err)
|
||||
}
|
||||
return limit, &last, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const MaxTextCodePoints = 4000
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// NewMessage keeps the text verbatim; only blank or oversized text is rejected.
|
||||
func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
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))
|
||||
}
|
||||
return Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: ident.TimeOf(id),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewMessageDerivesCreatedAt(t *testing.T) {
|
||||
id, chatID, alice := ident.New(), ident.New(), ident.New()
|
||||
m, err := chat.NewMessage(id, chatID, alice, "Привет, мир 👋")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMessage error: %v", err)
|
||||
}
|
||||
if m.ID != id || m.ChatID != chatID || m.SenderID != alice || m.Text != "Привет, мир 👋" {
|
||||
t.Fatalf("unexpected message %+v", m)
|
||||
}
|
||||
if !m.CreatedAt.Equal(ident.TimeOf(id)) {
|
||||
t.Fatalf("CreatedAt = %v, want %v", m.CreatedAt, ident.TimeOf(id))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageValidatesTextByCodePoints(t *testing.T) {
|
||||
chatID, alice := ident.New(), ident.New()
|
||||
if _, err := chat.NewMessage(ident.New(), chatID, alice, strings.Repeat("я", 4000)); err != nil {
|
||||
t.Errorf("4000 code points must be accepted: %v", err)
|
||||
}
|
||||
for _, text := range []string{"", " ", "\n\t ", strings.Repeat("я", 4001)} {
|
||||
_, err := chat.NewMessage(ident.New(), chatID, alice, text)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("text %q must be rejected as invalid, got %v", text, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageKeepsSurroundingWhitespace(t *testing.T) {
|
||||
m, err := chat.NewMessage(ident.New(), ident.New(), ident.New(), " hi ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Text != " hi " {
|
||||
t.Fatalf("text must be stored verbatim, got %q", m.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ChatRepository stores chats and their membership. Membership is answered
|
||||
// by queries; the projection with members is assembled by the store in one
|
||||
// query, never by loading a member list into the entity.
|
||||
type ChatRepository interface {
|
||||
// Create stores the chat row and its members atomically.
|
||||
Create(ctx context.Context, chat Chat, memberIDs []uuid.UUID) error
|
||||
// GetForMember returns the chat with members, or ErrNotFound when the
|
||||
// chat does not exist or the user is not a member.
|
||||
GetForMember(ctx context.Context, chatID, userID uuid.UUID) (ChatWithMembers, error)
|
||||
IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
// ListByMember returns up to limit chats of the user ordered by
|
||||
// (created_at, id), strictly after the chat identified by after when set.
|
||||
ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]ChatWithMembers, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
Append(ctx context.Context, message Message) error
|
||||
// ListByChat returns up to limit messages ordered by (created_at, id),
|
||||
// strictly after the message identified by after when set. An unknown
|
||||
// chat yields an empty history.
|
||||
ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]Message, error)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
// UserLookup is what this module needs from the users module: one batched
|
||||
// existence check. It is declared here, on the consumer side, so this
|
||||
// package never imports the users package and tests substitute a map.
|
||||
type UserLookup interface {
|
||||
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
chats ChatRepository
|
||||
messages MessageRepository
|
||||
users UserLookup
|
||||
}
|
||||
|
||||
func NewService(chats ChatRepository, messages MessageRepository, users UserLookup) *Service {
|
||||
return &Service{chats: chats, messages: messages, users: users}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, creator uuid.UUID, title string, memberIDs []uuid.UUID) (ChatWithMembers, error) {
|
||||
chat, err := NewChat(ident.New(), title)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
members, err := ValidateMembers(memberIDs, creator)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
found, err := s.users.ExistingIDs(ctx, members)
|
||||
if err != nil {
|
||||
return ChatWithMembers{}, fmt.Errorf("check members: %w", err)
|
||||
}
|
||||
if len(found) != len(members) {
|
||||
return ChatWithMembers{}, apperr.Invalid("member_ids must reference registered users")
|
||||
}
|
||||
if err := s.chats.Create(ctx, chat, members); err != nil {
|
||||
return ChatWithMembers{}, err
|
||||
}
|
||||
return ChatWithMembers{Chat: chat, MemberIDs: members}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, actor, chatID uuid.UUID) (ChatWithMembers, error) {
|
||||
return s.chats.GetForMember(ctx, chatID, actor)
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, actor uuid.UUID, after *uuid.UUID, limit int) (pagination.Page[ChatWithMembers], error) {
|
||||
items, err := s.chats.ListByMember(ctx, actor, after, limit+1)
|
||||
if err != nil {
|
||||
return pagination.Page[ChatWithMembers]{}, err
|
||||
}
|
||||
return pagination.Cut(items, limit, func(c ChatWithMembers) uuid.UUID { return c.ID }), nil
|
||||
}
|
||||
|
||||
func (s *Service) Send(ctx context.Context, actor, chatID uuid.UUID, text string) (Message, error) {
|
||||
if err := s.requireMember(ctx, actor, chatID); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
message, err := NewMessage(ident.New(), chatID, actor, text)
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
if err := s.messages.Append(ctx, message); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *Service) History(ctx context.Context, actor, chatID uuid.UUID, after *uuid.UUID, limit int) (pagination.Page[Message], error) {
|
||||
if err := s.requireMember(ctx, actor, chatID); err != nil {
|
||||
return pagination.Page[Message]{}, err
|
||||
}
|
||||
items, err := s.messages.ListByChat(ctx, chatID, after, limit+1)
|
||||
if err != nil {
|
||||
return pagination.Page[Message]{}, err
|
||||
}
|
||||
return pagination.Cut(items, limit, func(m Message) uuid.UUID { return m.ID }), nil
|
||||
}
|
||||
|
||||
// requireMember runs before any field validation, so an outsider gets the
|
||||
// same answer for a foreign chat as for a missing one.
|
||||
func (s *Service) requireMember(ctx context.Context, actor, chatID uuid.UUID) error {
|
||||
ok, err := s.chats.IsMember(ctx, chatID, actor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
// knownUsers doubles chat.UserLookup and counts calls to prove that member
|
||||
// checks are batched.
|
||||
type knownUsers struct {
|
||||
ids map[uuid.UUID]struct{}
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (k *knownUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
k.calls.Add(1)
|
||||
out := make([]uuid.UUID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := k.ids[id]; ok {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
svc *chat.Service
|
||||
users *knownUsers
|
||||
alice, bob uuid.UUID
|
||||
eve uuid.UUID
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture() fixture {
|
||||
alice, bob, eve := ident.New(), ident.New(), ident.New()
|
||||
users := &knownUsers{ids: map[uuid.UUID]struct{}{alice: {}, bob: {}, eve: {}}}
|
||||
return fixture{
|
||||
svc: chat.NewService(store.NewInMemChats(), store.NewInMemMessages(), users),
|
||||
users: users,
|
||||
alice: alice,
|
||||
bob: bob,
|
||||
eve: eve,
|
||||
ctx: context.Background(),
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatChecksMembersInOneCall(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "Проект", []uuid.UUID{f.alice, f.bob, f.eve})
|
||||
if err != nil {
|
||||
t.Fatalf("Create error: %v", err)
|
||||
}
|
||||
if c.Title != "Проект" || len(c.MemberIDs) != 3 {
|
||||
t.Fatalf("unexpected chat %+v", c)
|
||||
}
|
||||
if got := f.users.calls.Load(); got != 1 {
|
||||
t.Fatalf("member existence must be checked with one batch call, got %d", got)
|
||||
}
|
||||
got, err := f.svc.Get(f.ctx, f.bob, c.ID)
|
||||
if err != nil || got.ID != c.ID || len(got.MemberIDs) != 3 {
|
||||
t.Fatalf("member Get = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsUnknownMember(t *testing.T) {
|
||||
f := newFixture()
|
||||
_, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, ident.New()})
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "member_ids") {
|
||||
t.Fatalf("message must name the field: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsInvalidInputBeforeAnyLookup(t *testing.T) {
|
||||
f := newFixture()
|
||||
cases := map[string]struct {
|
||||
title string
|
||||
members []uuid.UUID
|
||||
}{
|
||||
"blank title": {" ", []uuid.UUID{f.alice}},
|
||||
"missing creator": {"t", []uuid.UUID{f.bob}},
|
||||
"duplicate": {"t", []uuid.UUID{f.alice, f.alice}},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
_, err := f.svc.Create(f.ctx, f.alice, tc.title, tc.members)
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Errorf("%s: kind = %v, want KindInvalid (%v)", name, apperr.KindOf(err), err)
|
||||
}
|
||||
}
|
||||
if got := f.users.calls.Load(); got != 0 {
|
||||
t.Fatalf("invalid input must be rejected before any user lookup, got %d calls", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHidesForeignAndUnknownChatsAlike(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
_, foreign := f.svc.Get(f.ctx, f.eve, c.ID)
|
||||
_, unknown := f.svc.Get(f.ctx, f.eve, ident.New())
|
||||
if !errors.Is(foreign, chat.ErrNotFound) || !errors.Is(unknown, chat.ErrNotFound) {
|
||||
t.Fatalf("foreign = %v, unknown = %v; want both ErrNotFound", foreign, unknown)
|
||||
}
|
||||
if apperr.KindOf(foreign) != apperr.KindNotFound {
|
||||
t.Fatalf("ErrNotFound must carry KindNotFound, got %v", apperr.KindOf(foreign))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPagesOnlyOwnChats(t *testing.T) {
|
||||
f := newFixture()
|
||||
var mine []uuid.UUID
|
||||
for i := 0; i < 3; i++ {
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mine = append(mine, c.ID)
|
||||
if _, err := f.svc.Create(f.ctx, f.eve, "t", []uuid.UUID{f.eve}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
page, err := f.svc.List(f.ctx, f.alice, nil, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 2 || page.Next == nil || *page.Next != mine[1] {
|
||||
t.Fatalf("first page = %+v", page)
|
||||
}
|
||||
if len(page.Items[0].MemberIDs) != 2 {
|
||||
t.Fatalf("listed chats must carry their members: %+v", page.Items[0])
|
||||
}
|
||||
rest, err := f.svc.List(f.ctx, f.alice, page.Next, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest.Items) != 1 || rest.Items[0].ID != mine[2] || rest.Next != nil {
|
||||
t.Fatalf("second page = %+v", rest)
|
||||
}
|
||||
all, err := f.svc.List(f.ctx, f.bob, nil, 100)
|
||||
if err != nil || len(all.Items) != 3 || all.Next != nil {
|
||||
t.Fatalf("bob page = %+v, %v", all, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendChecksAccessBeforeValidation(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
_, err := f.svc.Send(f.ctx, f.eve, c.ID, " ")
|
||||
if !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider with blank text: err = %v, want ErrNotFound", err)
|
||||
}
|
||||
_, err = f.svc.Send(f.ctx, f.bob, c.ID, " ")
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("member with blank text: kind = %v, want KindInvalid", apperr.KindOf(err))
|
||||
}
|
||||
msg, err := f.svc.Send(f.ctx, f.bob, c.ID, "Привет 👋")
|
||||
if err != nil || msg.SenderID != f.bob || msg.ChatID != c.ID || msg.Text != "Привет 👋" {
|
||||
t.Fatalf("Send = %+v, %v", msg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
first, _ := f.svc.Send(f.ctx, f.alice, c.ID, "1")
|
||||
second, _ := f.svc.Send(f.ctx, f.bob, c.ID, "2")
|
||||
|
||||
page, err := f.svc.History(f.ctx, f.bob, c.ID, nil, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != first.ID || page.Next == nil || *page.Next != first.ID {
|
||||
t.Fatalf("first page = %+v", page)
|
||||
}
|
||||
rest, err := f.svc.History(f.ctx, f.alice, c.ID, page.Next, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest.Items) != 1 || rest.Items[0].ID != second.ID || rest.Next != nil {
|
||||
t.Fatalf("second page = %+v", rest)
|
||||
}
|
||||
if _, err := f.svc.History(f.ctx, f.eve, c.ID, nil, 10); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider history: err = %v, want ErrNotFound", err)
|
||||
}
|
||||
empty, err := f.svc.History(f.ctx, f.alice, c.ID, &second.ID, 10)
|
||||
if err != nil || empty.Items == nil || len(empty.Items) != 0 || empty.Next != nil {
|
||||
t.Fatalf("page after last = %+v, %v; want empty non-nil items", empty, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package store holds the repository implementations of the chats module.
|
||||
// inmem.go is the in-process one: state lives only in this process and
|
||||
// disappears with it by design of the lab.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
// InMemChats keeps chat rows, a per-chat member list and set, and a
|
||||
// per-member index of chat ids ordered by (created_at, id), which for UUIDv7
|
||||
// ids is plain id order. One read-write mutex guards all four maps.
|
||||
type InMemChats struct {
|
||||
mu sync.RWMutex
|
||||
rows map[uuid.UUID]chat.Chat
|
||||
members map[uuid.UUID][]uuid.UUID
|
||||
memberOf map[uuid.UUID]map[uuid.UUID]struct{}
|
||||
byMember map[uuid.UUID][]uuid.UUID
|
||||
}
|
||||
|
||||
var _ chat.ChatRepository = (*InMemChats)(nil)
|
||||
|
||||
func NewInMemChats() *InMemChats {
|
||||
return &InMemChats{
|
||||
rows: make(map[uuid.UUID]chat.Chat),
|
||||
members: make(map[uuid.UUID][]uuid.UUID),
|
||||
memberOf: make(map[uuid.UUID]map[uuid.UUID]struct{}),
|
||||
byMember: make(map[uuid.UUID][]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *InMemChats) Create(_ context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
members := append([]uuid.UUID(nil), memberIDs...)
|
||||
set := make(map[uuid.UUID]struct{}, len(members))
|
||||
for _, m := range members {
|
||||
set[m] = struct{}{}
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.rows[c.ID] = c
|
||||
r.members[c.ID] = members
|
||||
r.memberOf[c.ID] = set
|
||||
for _, m := range members {
|
||||
r.byMember[m] = insertSorted(r.byMember[m], c.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) GetForMember(_ context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if _, ok := r.memberOf[chatID][userID]; !ok {
|
||||
return chat.ChatWithMembers{}, chat.ErrNotFound
|
||||
}
|
||||
return r.projection(chatID), nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) IsMember(_ context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
_, ok := r.memberOf[chatID][userID]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) ListByMember(_ context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
ids := r.byMember[userID]
|
||||
start := firstAfter(ids, after)
|
||||
end := min(start+limit, len(ids))
|
||||
out := make([]chat.ChatWithMembers, 0, end-start)
|
||||
for _, id := range ids[start:end] {
|
||||
out = append(out, r.projection(id))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// projection copies the member list so callers never alias the store.
|
||||
func (r *InMemChats) projection(chatID uuid.UUID) chat.ChatWithMembers {
|
||||
return chat.ChatWithMembers{
|
||||
Chat: r.rows[chatID],
|
||||
MemberIDs: append([]uuid.UUID(nil), r.members[chatID]...),
|
||||
}
|
||||
}
|
||||
|
||||
// InMemMessages keeps one ordered history per chat. The outer lock only
|
||||
// guards the map of histories; each history has its own lock, so writers to
|
||||
// different chats never contend.
|
||||
type InMemMessages struct {
|
||||
mu sync.RWMutex
|
||||
byChat map[uuid.UUID]*history
|
||||
}
|
||||
|
||||
type history struct {
|
||||
mu sync.RWMutex
|
||||
items []chat.Message
|
||||
}
|
||||
|
||||
var _ chat.MessageRepository = (*InMemMessages)(nil)
|
||||
|
||||
func NewInMemMessages() *InMemMessages {
|
||||
return &InMemMessages{byChat: make(map[uuid.UUID]*history)}
|
||||
}
|
||||
|
||||
// Append inserts at the sorted position; ids are monotonic, so the usual
|
||||
// case is an append at the tail.
|
||||
func (r *InMemMessages) Append(_ context.Context, m chat.Message) error {
|
||||
h := r.historyFor(m.ChatID, true)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
n := len(h.items)
|
||||
if n == 0 || less(h.items[n-1].ID, m.ID) {
|
||||
h.items = append(h.items, m)
|
||||
return nil
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(h.items[k].ID, m.ID) })
|
||||
h.items = append(h.items, chat.Message{})
|
||||
copy(h.items[i+1:], h.items[i:])
|
||||
h.items[i] = m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) ListByChat(_ context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) {
|
||||
h := r.historyFor(chatID, false)
|
||||
if h == nil {
|
||||
return []chat.Message{}, nil
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
start := 0
|
||||
if after != nil {
|
||||
start = sort.Search(len(h.items), func(k int) bool { return less(*after, h.items[k].ID) })
|
||||
}
|
||||
end := min(start+limit, len(h.items))
|
||||
out := make([]chat.Message, end-start)
|
||||
copy(out, h.items[start:end])
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) historyFor(chatID uuid.UUID, create bool) *history {
|
||||
r.mu.RLock()
|
||||
h := r.byChat[chatID]
|
||||
r.mu.RUnlock()
|
||||
if h != nil || !create {
|
||||
return h
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if h = r.byChat[chatID]; h == nil {
|
||||
h = &history{}
|
||||
r.byChat[chatID] = h
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// less orders ids lexicographically, which for UUIDv7 is creation order.
|
||||
func less(a, b uuid.UUID) bool {
|
||||
return bytes.Compare(a[:], b[:]) < 0
|
||||
}
|
||||
|
||||
func insertSorted(ids []uuid.UUID, id uuid.UUID) []uuid.UUID {
|
||||
n := len(ids)
|
||||
if n == 0 || less(ids[n-1], id) {
|
||||
return append(ids, id)
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(ids[k], id) })
|
||||
ids = append(ids, uuid.Nil)
|
||||
copy(ids[i+1:], ids[i:])
|
||||
ids[i] = id
|
||||
return ids
|
||||
}
|
||||
|
||||
// firstAfter returns the index of the first id strictly greater than after,
|
||||
// or len(ids) when there is none; nil after means the start.
|
||||
func firstAfter(ids []uuid.UUID, after *uuid.UUID) int {
|
||||
if after == nil {
|
||||
return 0
|
||||
}
|
||||
return sort.Search(len(ids), func(k int) bool { return less(*after, ids[k]) })
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func mustChat(t *testing.T) chat.Chat {
|
||||
t.Helper()
|
||||
c, err := chat.NewChat(ident.New(), "title")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func mustMessage(t *testing.T, chatID uuid.UUID) chat.Message {
|
||||
t.Helper()
|
||||
m, err := chat.NewMessage(ident.New(), chatID, ident.New(), "text")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestChatCreateThenGetForMember(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
c := mustChat(t)
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := repo.GetForMember(ctx, c.ID, bob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Chat != c || len(got.MemberIDs) != 2 || got.MemberIDs[0] != alice || got.MemberIDs[1] != bob {
|
||||
t.Fatalf("GetForMember = %+v", got)
|
||||
}
|
||||
got.MemberIDs[0] = ident.New()
|
||||
again, _ := repo.GetForMember(ctx, c.ID, alice)
|
||||
if again.MemberIDs[0] != alice {
|
||||
t.Fatal("GetForMember must return a copy of the member list")
|
||||
}
|
||||
if _, err := repo.GetForMember(ctx, c.ID, ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider must get ErrNotFound, got %v", err)
|
||||
}
|
||||
for who, want := range map[uuid.UUID]bool{alice: true, bob: true, ident.New(): false} {
|
||||
ok, err := repo.IsMember(ctx, c.ID, who)
|
||||
if err != nil || ok != want {
|
||||
t.Fatalf("IsMember(%s) = %v, %v; want %v", who, ok, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUnknownID(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
if _, err := repo.GetForMember(ctx, ident.New(), ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("GetForMember err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if ok, err := repo.IsMember(ctx, ident.New(), ident.New()); err != nil || ok {
|
||||
t.Fatalf("IsMember on unknown chat = %v, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByMemberFiltersOrdersAndPages(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
var mine []chat.Chat
|
||||
for i := 0; i < 5; i++ {
|
||||
mine = append(mine, mustChat(t))
|
||||
// A chat without alice must never show up in her listing.
|
||||
if err := repo.Create(ctx, mustChat(t), []uuid.UUID{bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Insert the oldest chat last to prove the store sorts, not appends.
|
||||
for _, c := range mine[1:] {
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := repo.Create(ctx, mine[0], []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, err := repo.ListByMember(ctx, alice, nil, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) != 3 || page[0].ID != mine[0].ID || page[2].ID != mine[2].ID {
|
||||
t.Fatalf("first page mismatch: %v", page)
|
||||
}
|
||||
if len(page[0].MemberIDs) != 2 {
|
||||
t.Fatalf("listing must carry members: %+v", page[0])
|
||||
}
|
||||
last := page[2].ID
|
||||
rest, err := repo.ListByMember(ctx, alice, &last, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest) != 2 || rest[0].ID != mine[3].ID || rest[1].ID != mine[4].ID {
|
||||
t.Fatalf("second page mismatch: %v", rest)
|
||||
}
|
||||
none, err := repo.ListByMember(ctx, ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none == nil || len(none) != 0 {
|
||||
t.Fatalf("unknown member must get an empty non-nil slice, got %#v", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatUnknownChatIsEmpty(t *testing.T) {
|
||||
got, err := store.NewInMemMessages().ListByChat(context.Background(), ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("want empty non-nil slice, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOutOfOrderIsSortedByID(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
first, second, third := mustMessage(t, chatID), mustMessage(t, chatID), mustMessage(t, chatID)
|
||||
for _, m := range []chat.Message{third, first, second} {
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 || got[0].ID != first.ID || got[1].ID != second.ID || got[2].ID != third.ID {
|
||||
t.Fatalf("history must be ordered by id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagingWalksWholeHistoryWithoutGapsOrDuplicates(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const total = 250
|
||||
var expected []uuid.UUID
|
||||
for i := 0; i < total; i++ {
|
||||
m := mustMessage(t, chatID)
|
||||
expected = append(expected, m.ID)
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, limit := range []int{1, 7, 100} {
|
||||
var seen []uuid.UUID
|
||||
var after *uuid.UUID
|
||||
for {
|
||||
page, err := repo.ListByChat(ctx, chatID, after, limit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
if len(page) > limit {
|
||||
t.Fatalf("limit %d: page has %d items", limit, len(page))
|
||||
}
|
||||
for _, m := range page {
|
||||
seen = append(seen, m.ID)
|
||||
}
|
||||
last := page[len(page)-1].ID
|
||||
after = &last
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Fatalf("limit %d: walked %d messages, want %d", limit, len(seen), total)
|
||||
}
|
||||
for i := range seen {
|
||||
if seen[i] != expected[i] {
|
||||
t.Fatalf("limit %d: position %d has %s, want %s", limit, i, seen[i], expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAfterUnknownIDStartsAtNextGreater(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
a := mustMessage(t, chatID)
|
||||
gap := ident.New() // never stored, but sorts between a and b
|
||||
b := mustMessage(t, chatID)
|
||||
_ = repo.Append(ctx, a)
|
||||
_ = repo.Append(ctx, b)
|
||||
got, _ := repo.ListByChat(ctx, chatID, &gap, 10)
|
||||
if len(got) != 1 || got[0].ID != b.ID {
|
||||
t.Fatalf("want only b after the gap id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatReturnsCopy(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
_ = repo.Append(ctx, mustMessage(t, chatID))
|
||||
page, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
page[0].Text = "mutated"
|
||||
again, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if again[0].Text != "text" {
|
||||
t.Fatal("ListByChat must not expose internal storage")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentAppendsKeepEveryMessageOrdered(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const clients, perClient = 10, 10
|
||||
var wg sync.WaitGroup
|
||||
for c := 0; c < clients; c++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClient; i++ {
|
||||
if err := repo.Append(ctx, mustMessage(t, chatID)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
got, err := repo.ListByChat(ctx, chatID, nil, clients*perClient+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != clients*perClient {
|
||||
t.Fatalf("stored %d messages, want %d", len(got), clients*perClient)
|
||||
}
|
||||
unique := make(map[uuid.UUID]struct{}, len(got))
|
||||
for i, m := range got {
|
||||
unique[m.ID] = struct{}{}
|
||||
if i > 0 && bytes.Compare(got[i-1].ID[:], m.ID[:]) >= 0 {
|
||||
t.Fatalf("history out of order at %d", i)
|
||||
}
|
||||
}
|
||||
if len(unique) != clients*perClient {
|
||||
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user