207 lines
5.7 KiB
Go
207 lines
5.7 KiB
Go
package postgres
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
|
)
|
|
|
|
type MessageRepository struct {
|
|
store *Store
|
|
}
|
|
|
|
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
|
var created domain.Message
|
|
|
|
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
|
message, err := createIdempotent(ctx, queries, draft, r.store.idempotencyTTL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
created = message
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
// mapError нужен и здесь: отказ BEGIN/COMMIT (недоступная БД, исчерпанный
|
|
// пул, истёкший контекст) обязан давать 503, а не 500.
|
|
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
|
|
}
|
|
|
|
return created, nil
|
|
}
|
|
|
|
// createIdempotent stores the message and its Idempotency-Key in one
|
|
// transaction: either both are committed or neither, so a replay never observes
|
|
// a claimed key whose message is missing. Claiming is a single statement, so
|
|
// concurrent duplicates with the same key wait for the winner and then replay
|
|
// the message it stored.
|
|
func createIdempotent(
|
|
ctx context.Context,
|
|
queries *sqlcgen.Queries,
|
|
draft domain.MessageDraft,
|
|
ttl time.Duration,
|
|
) (domain.Message, error) {
|
|
_, err := queries.ClaimMessageIdempotency(ctx, sqlcgen.ClaimMessageIdempotencyParams{
|
|
ActorID: draft.SenderID,
|
|
ChatID: draft.ChatID,
|
|
Key: draft.Idempotency.Key,
|
|
RequestHash: draft.Idempotency.RequestHash[:],
|
|
ExpiresAt: time.Now().Add(ttl),
|
|
})
|
|
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows): // the key is still live: replay it
|
|
return replayIdempotent(ctx, queries, draft)
|
|
case err != nil:
|
|
return domain.Message{}, mapError(err)
|
|
default:
|
|
return createClaimed(ctx, queries, draft)
|
|
}
|
|
}
|
|
|
|
func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
|
row, err := queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
|
|
ChatID: draft.ChatID,
|
|
SenderID: draft.SenderID,
|
|
Text: draft.Text,
|
|
})
|
|
if err != nil {
|
|
return domain.Message{}, mapError(err)
|
|
}
|
|
|
|
err = queries.CompleteMessageIdempotency(ctx, sqlcgen.CompleteMessageIdempotencyParams{
|
|
MessageID: pgtype.UUID{Bytes: row.ID, Valid: true},
|
|
ActorID: draft.SenderID,
|
|
ChatID: draft.ChatID,
|
|
Key: draft.Idempotency.Key,
|
|
})
|
|
if err != nil {
|
|
return domain.Message{}, mapError(err)
|
|
}
|
|
|
|
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
|
|
}
|
|
|
|
func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
|
stored, err := queries.GetMessageIdempotency(ctx, sqlcgen.GetMessageIdempotencyParams{
|
|
ActorID: draft.SenderID,
|
|
ChatID: draft.ChatID,
|
|
Key: draft.Idempotency.Key,
|
|
})
|
|
if err != nil {
|
|
return domain.Message{}, mapError(err)
|
|
}
|
|
|
|
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
|
return domain.Message{}, domain.ErrIdempotency
|
|
}
|
|
|
|
if !stored.MessageID.Valid {
|
|
return domain.Message{}, errors.New("idempotency record without a message")
|
|
}
|
|
|
|
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
|
if err != nil {
|
|
return domain.Message{}, mapError(err)
|
|
}
|
|
|
|
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
|
|
}
|
|
|
|
func (r *MessageRepository) ListVisible(
|
|
ctx context.Context,
|
|
chatID, callerID uuid.UUID,
|
|
after *domain.Cursor,
|
|
limit int,
|
|
) (domain.Page[domain.Message], error) {
|
|
ctx, cancel := r.store.timeout(ctx)
|
|
defer cancel()
|
|
|
|
limit = clampLimit(limit)
|
|
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
|
|
|
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
|
|
if err != nil {
|
|
return domain.Page[domain.Message]{}, err
|
|
}
|
|
|
|
if len(messages) == 0 {
|
|
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
|
ChatID: chatID,
|
|
UserID: callerID,
|
|
})
|
|
if err != nil {
|
|
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
|
|
}
|
|
|
|
if !member {
|
|
return domain.Page[domain.Message]{}, fmt.Errorf(
|
|
"%w: chat %s for user %s",
|
|
domain.ErrNotFound, chatID, callerID,
|
|
)
|
|
}
|
|
}
|
|
|
|
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
|
|
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
|
|
}), nil
|
|
}
|
|
|
|
func (r *MessageRepository) fetch(
|
|
ctx context.Context,
|
|
chatID, callerID uuid.UUID,
|
|
after *domain.Cursor,
|
|
fetch int32,
|
|
) ([]domain.Message, error) {
|
|
if after == nil {
|
|
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
|
|
ChatID: chatID,
|
|
CallerID: callerID,
|
|
RowLimit: fetch,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
|
}
|
|
|
|
return mapAll(rows, mapMessageRow), nil
|
|
}
|
|
|
|
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
|
|
ChatID: chatID,
|
|
CallerID: callerID,
|
|
AfterCreatedAt: after.CreatedAt,
|
|
AfterID: after.ID,
|
|
RowLimit: fetch,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
|
}
|
|
|
|
return mapAll(rows, mapMessageRow), nil
|
|
}
|
|
|
|
func mapMessageRow(row sqlcgen.Message) domain.Message {
|
|
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
|
}
|
|
|
|
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
|
|
return domain.Message{
|
|
ID: id,
|
|
ChatID: chatID,
|
|
SenderID: senderID,
|
|
Text: text,
|
|
CreatedAt: toUTCTime(createdAt),
|
|
}
|
|
}
|