forked from mtusi2026/mtusi2026lab3
feat(app) lab 3 implemented
This commit is contained in:
@@ -1,21 +1,30 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
|
||||
"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"
|
||||
)
|
||||
|
||||
// CreateMessage uses INSERT ... SELECT so the membership check and the insert
|
||||
// are a single atomic statement: no window where the user is removed between
|
||||
// check and write. Zero affected rows means the chat is missing or foreign.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) {
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string) (model.Message, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
fingerprint := sha256.Sum256([]byte(text))
|
||||
|
||||
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,
|
||||
@@ -24,7 +33,13 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
@@ -36,9 +51,72 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
return model.Message{}, common.NotFound("chat not found")
|
||||
}
|
||||
|
||||
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 (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, 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, &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")
|
||||
}
|
||||
|
||||
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) {
|
||||
isMember, err := s.IsMember(ctx, userID, chatID)
|
||||
if err != nil {
|
||||
@@ -56,8 +134,6 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
// AGENT: limit+1 is fetched so next_cursor is known to be non-null without a
|
||||
// second COUNT query; the extra row is never returned to the client.
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
|
||||
Reference in New Issue
Block a user