Files
mtusi2026lab4/internal/storage/postgres/chat_repository.go
T
2026-10-15 20:45:29 +03:00

163 lines
4.1 KiB
Go

package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type ChatRepository struct {
store *Store
}
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var created domain.Chat
if err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
missing, err := queries.ListMissingUserIDs(ctx, draft.MemberIDs)
if err != nil {
return fmt.Errorf("check chat members: %w", mapError(err))
}
if len(missing) > 0 {
return domain.ErrUnknownMember
}
row, err := queries.CreateChat(ctx, draft.Title)
if err != nil {
return fmt.Errorf("create chat: %w", mapError(err))
}
if err := queries.AddChatMembers(ctx, sqlcgen.AddChatMembersParams{
ChatID: row.ID,
UserIds: draft.MemberIDs,
}); err != nil {
return fmt.Errorf("add chat members: %w", mapError(err))
}
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
return fmt.Errorf("bump chat list versions: %w", mapError(err))
}
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
return nil
}); err != nil {
return domain.Chat{}, err
}
return created, nil
}
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
version, err := r.store.queries.GetChatListVersion(ctx, userID)
if err != nil {
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
}
return version, nil
}
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
sorted := slices.Clone(ids)
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
return bytes.Compare(a[:], b[:])
})
return slices.Compact(sorted)
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetChatForMember(ctx, sqlcgen.GetChatForMemberParams{
UserID: callerID,
ID: chatID,
})
if err != nil {
mapped := mapError(err)
if errors.Is(mapped, domain.ErrNotFound) {
return domain.Chat{}, fmt.Errorf("%w: chat %s for user %s", domain.ErrNotFound, chatID, callerID)
}
return domain.Chat{}, fmt.Errorf("get chat: %w", mapped)
}
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds), nil
}
func (r *ChatRepository) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
limit = clampLimit(limit)
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
var rows []domain.Chat
if after == nil {
pageRows, err := r.store.queries.ListChatsForMember(ctx, sqlcgen.ListChatsForMemberParams{
UserID: callerID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRow)
} else {
pageRows, err := r.store.queries.ListChatsForMemberAfter(ctx, sqlcgen.ListChatsForMemberAfterParams{
UserID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRowAfter)
}
return buildPage(rows, limit, func(chat domain.Chat) domain.Cursor {
return domain.Cursor{Scope: callerID, CreatedAt: chat.CreatedAt, ID: chat.ID}
}), nil
}
func mapChatRow(row sqlcgen.ListChatsForMemberRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChatRowAfter(row sqlcgen.ListChatsForMemberAfterRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChat(id uuid.UUID, title string, createdAt time.Time, memberIDs []uuid.UUID) domain.Chat {
return domain.Chat{
ID: id,
Title: title,
MemberIDs: memberIDs,
CreatedAt: toUTCTime(createdAt),
}
}