forked from mtusi2026/mtusi2026lab5
288 lines
8.5 KiB
Go
288 lines
8.5 KiB
Go
package store
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"errors"
|
|
"sort"
|
|
"time"
|
|
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string, attachmentIDs []uuid.UUID) (model.Message, error) {
|
|
ctx, cancel := s.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
// Sorting makes the idempotency fingerprint independent of the order
|
|
// in which the client listed the same set of attachment IDs. The response
|
|
// uses the same deterministic order.
|
|
attachmentIDs = canonicalAttachmentIDs(attachmentIDs)
|
|
fingerprint := messageFingerprint(text, attachmentIDs)
|
|
|
|
if message, found, err := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint); err != nil {
|
|
return model.Message{}, err
|
|
} else if found {
|
|
return message, nil
|
|
}
|
|
|
|
message := model.Message{
|
|
ID: uuid.New(),
|
|
ChatID: chatID,
|
|
SenderID: senderID,
|
|
Text: text,
|
|
CreatedAt: common.NowUTC(),
|
|
AttachmentIDs: attachmentIDs,
|
|
}
|
|
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
defer rollback(tx)
|
|
|
|
// Check membership and attachment ownership in the same transaction as the
|
|
// insert. A foreign chat or a foreign attachment is intentionally the same
|
|
// 404 as a missing object, so the API does not leak existence.
|
|
var member int
|
|
err = tx.QueryRow(ctx,
|
|
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
|
|
chatID, senderID).Scan(&member)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.Message{}, common.NotFound("chat not found")
|
|
}
|
|
if err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
|
|
if len(attachmentIDs) > 0 {
|
|
rows, queryErr := tx.Query(ctx, `
|
|
SELECT id, status FROM attachments
|
|
WHERE chat_id = $1 AND id = ANY($2::uuid[])`, chatID, attachmentIDs)
|
|
if queryErr != nil {
|
|
return model.Message{}, dbError(queryErr)
|
|
}
|
|
|
|
found := 0
|
|
for rows.Next() {
|
|
var (
|
|
id uuid.UUID
|
|
status string
|
|
)
|
|
if scanErr := rows.Scan(&id, &status); scanErr != nil {
|
|
rows.Close()
|
|
return model.Message{}, dbError(scanErr)
|
|
}
|
|
found++
|
|
// A queued/processing attachment is already linked to its
|
|
// chat and may be sent. Only a terminal failed one is refused.
|
|
if status == "failed" {
|
|
rows.Close()
|
|
return model.Message{}, common.Conflict("attachment failed processing")
|
|
}
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
rows.Close()
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
rows.Close()
|
|
|
|
if found != len(attachmentIDs) {
|
|
return model.Message{}, common.NotFound("attachment not found")
|
|
}
|
|
}
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5)`,
|
|
message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt))
|
|
if err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
|
|
for position, attachmentID := range attachmentIDs {
|
|
if _, err = tx.Exec(ctx, `
|
|
INSERT INTO message_attachments (message_id, attachment_id, position)
|
|
VALUES ($1, $2, $3)`, message.ID, attachmentID, position); err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
}
|
|
|
|
expiresAt := time.Time(message.CreatedAt).Add(s.idempotencyTTL)
|
|
tag, err := tx.Exec(ctx, `
|
|
INSERT INTO message_idempotency
|
|
(sender_id, chat_id, idempotency_key, request_hash, message_id, created_at, expires_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
|
|
SET request_hash = EXCLUDED.request_hash,
|
|
message_id = EXCLUDED.message_id,
|
|
created_at = EXCLUDED.created_at,
|
|
expires_at = EXCLUDED.expires_at
|
|
WHERE message_idempotency.expires_at <= now()`,
|
|
senderID, chatID, idempotencyKey, fingerprint, message.ID,
|
|
time.Time(message.CreatedAt), expiresAt)
|
|
if err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
|
|
if tag.RowsAffected() == 0 {
|
|
rollback(tx)
|
|
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint)
|
|
if lookupErr != nil {
|
|
return model.Message{}, lookupErr
|
|
}
|
|
if !found {
|
|
return model.Message{}, common.Internal()
|
|
}
|
|
return stored, nil
|
|
}
|
|
|
|
if err = tx.Commit(ctx); err != nil {
|
|
return model.Message{}, dbError(err)
|
|
}
|
|
|
|
return message, nil
|
|
}
|
|
|
|
func canonicalAttachmentIDs(ids []uuid.UUID) []uuid.UUID {
|
|
result := append([]uuid.UUID(nil), ids...)
|
|
sort.Slice(result, func(i, j int) bool {
|
|
return bytes.Compare(result[i][:], result[j][:]) < 0
|
|
})
|
|
if result == nil {
|
|
return []uuid.UUID{}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// messageFingerprint keeps the legacy hash for messages without attachments,
|
|
// so an idempotency key stored before this migration still replays correctly.
|
|
// For messages with attachments the sorted IDs are part of the canonical body.
|
|
func messageFingerprint(text string, attachmentIDs []uuid.UUID) []byte {
|
|
if len(attachmentIDs) == 0 {
|
|
sum := sha256.Sum256([]byte(text))
|
|
return sum[:]
|
|
}
|
|
|
|
hash := sha256.New()
|
|
hash.Write([]byte(text))
|
|
hash.Write([]byte{0})
|
|
for _, id := range attachmentIDs {
|
|
hash.Write(id[:])
|
|
}
|
|
return hash.Sum(nil)
|
|
}
|
|
|
|
func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid.UUID, idempotencyKey string, expectedHash []byte) (model.Message, bool, error) {
|
|
var message model.Message
|
|
var createdAt time.Time
|
|
var storedHash []byte
|
|
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
ARRAY(SELECT ma.attachment_id
|
|
FROM message_attachments ma
|
|
WHERE ma.message_id = m.id
|
|
ORDER BY ma.position),
|
|
i.request_hash
|
|
FROM message_idempotency i
|
|
JOIN messages m ON m.id = i.message_id
|
|
JOIN chat_members cm ON cm.chat_id = i.chat_id AND cm.user_id = i.sender_id
|
|
WHERE i.sender_id = $1
|
|
AND i.chat_id = $2
|
|
AND i.idempotency_key = $3
|
|
AND i.expires_at > now()`,
|
|
senderID, chatID, idempotencyKey).Scan(
|
|
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt,
|
|
&message.AttachmentIDs, &storedHash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.Message{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return model.Message{}, false, dbError(err)
|
|
}
|
|
if !bytes.Equal(storedHash, expectedHash) {
|
|
return model.Message{}, false, common.Conflict("idempotency key reused with a different message")
|
|
}
|
|
if message.AttachmentIDs == nil {
|
|
message.AttachmentIDs = []uuid.UUID{}
|
|
}
|
|
|
|
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
|
return message, true, nil
|
|
}
|
|
|
|
func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) {
|
|
ctx, cancel := s.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
isMember, err := s.IsMember(ctx, userID, chatID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !isMember {
|
|
return nil, common.NotFound("chat not found")
|
|
}
|
|
// AGENT: Cursor context is checked only after membership, so a foreign
|
|
// caller gets 404 and cannot probe cursor validity against someone else's chat.
|
|
if cursor != nil && cursor.ContextID != chatID {
|
|
return nil, common.BadRequest("bad cursor value")
|
|
}
|
|
|
|
cursorTime, cursorID := cursorValues(cursor)
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
ARRAY(SELECT ma.attachment_id
|
|
FROM message_attachments ma
|
|
WHERE ma.message_id = m.id
|
|
ORDER BY ma.position)
|
|
FROM messages m
|
|
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
|
ORDER BY m.created_at, m.id
|
|
LIMIT $4`, chatID, cursorTime, cursorID, limit+1)
|
|
if err != nil {
|
|
return nil, dbError(err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
messages := make([]model.Message, 0, limit)
|
|
for rows.Next() {
|
|
message, scanErr := scanMessage(rows)
|
|
if scanErr != nil {
|
|
return nil, dbError(scanErr)
|
|
}
|
|
messages = append(messages, message)
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return nil, dbError(err)
|
|
}
|
|
|
|
hasMore := len(messages) > limit
|
|
if hasMore {
|
|
messages = messages[:limit]
|
|
}
|
|
|
|
return &common.Page[model.Message]{
|
|
Items: messages,
|
|
NextCursor: common.NextCursor(messages, hasMore, chatID),
|
|
}, nil
|
|
}
|
|
|
|
func scanMessage(row rowScanner) (model.Message, error) {
|
|
var message model.Message
|
|
var createdAt time.Time
|
|
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text,
|
|
&createdAt, &message.AttachmentIDs); err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
if message.AttachmentIDs == nil {
|
|
message.AttachmentIDs = []uuid.UUID{}
|
|
}
|
|
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
|
return message, nil
|
|
}
|