fix: address review comments
CI / verify (pull_request) Successful in 4m21s

This commit is contained in:
2026-10-02 17:23:58 +03:00
parent 18d51db435
commit 0062313c0b
15 changed files with 698 additions and 395 deletions
+285
View File
@@ -0,0 +1,285 @@
package postgres
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
)
const expiredIdempotencyCleanupBatch = 100
func (s *Store) CreateMessage(
ctx context.Context,
chatID string,
senderID string,
text string,
idempotencyKey string,
idempotencyTTL time.Duration,
) (model.Message, bool, error) {
var (
tx pgx.Tx
err error
visible bool
requestHash [sha256.Size]byte
message model.Message
replay bool
)
tx, err = s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return model.Message{}, false, fmt.Errorf("begin create message transaction: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
visible, err = chatVisibleInTransaction(ctx, tx, chatID, senderID)
if err != nil {
return model.Message{}, false, err
}
if !visible {
return model.Message{}, false, ErrNotFound
}
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
return model.Message{}, false, err
}
requestHash = sha256.Sum256([]byte(text))
message, replay, err = createIdempotentMessage(
ctx, tx, chatID, senderID, text, idempotencyKey, requestHash[:], idempotencyTTL,
)
if err != nil {
return model.Message{}, false, err
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, fmt.Errorf("commit create message transaction: %w", err)
}
return message, replay, nil
}
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1 AND user_id = $2
)`
var visible bool
if err := tx.QueryRow(ctx, query, chatID, userID).Scan(&visible); err != nil {
return false, fmt.Errorf("check chat visibility: %w", err)
}
return visible, nil
}
func createIdempotentMessage(
ctx context.Context,
tx pgx.Tx,
chatID string,
senderID string,
text string,
idempotencyKey string,
requestHash []byte,
idempotencyTTL time.Duration,
) (model.Message, bool, error) {
for {
var (
record idempotencyRecord
found bool
err error
messageID string
reserved bool
message model.Message
)
record, found, err = lockIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey)
if err != nil {
return model.Message{}, false, err
}
if found && record.active {
if !bytes.Equal(record.requestHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
message, err = messageByID(ctx, tx, record.messageID)
return message, true, err
}
if found {
if err := deleteIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey); err != nil {
return model.Message{}, false, err
}
}
messageID = uuid.NewString()
reserved, err = reserveIdempotencyKey(
ctx, tx, senderID, chatID, idempotencyKey, requestHash, messageID, idempotencyTTL,
)
if err != nil {
return model.Message{}, false, err
}
if !reserved {
continue
}
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text)
return message, false, err
}
}
func deleteExpiredIdempotencyRecords(ctx context.Context, tx pgx.Tx, limit int) error {
const query = `
WITH expired AS (
SELECT ctid
FROM message_idempotency
WHERE expires_at <= statement_timestamp()
ORDER BY expires_at
LIMIT $1
FOR UPDATE SKIP LOCKED
)
DELETE FROM message_idempotency records
USING expired
WHERE records.ctid = expired.ctid`
if _, err := tx.Exec(ctx, query, limit); err != nil {
return fmt.Errorf("delete expired idempotency records: %w", err)
}
return nil
}
type idempotencyRecord struct {
requestHash []byte
messageID string
active bool
}
func lockIdempotencyRecord(
ctx context.Context,
tx pgx.Tx,
userID string,
chatID string,
key string,
) (idempotencyRecord, bool, error) {
const query = `
SELECT request_hash, message_id, expires_at > statement_timestamp()
FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND key = $3
FOR UPDATE`
var (
record idempotencyRecord
err error
)
err = tx.QueryRow(ctx, query, userID, chatID, key).Scan(
&record.requestHash,
&record.messageID,
&record.active,
)
if errors.Is(err, pgx.ErrNoRows) {
return idempotencyRecord{}, false, nil
}
if err != nil {
return idempotencyRecord{}, false, fmt.Errorf("lock idempotency key: %w", err)
}
return record, true, nil
}
func deleteIdempotencyRecord(ctx context.Context, tx pgx.Tx, userID, chatID, key string) error {
const query = `
DELETE FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND key = $3`
if _, err := tx.Exec(ctx, query, userID, chatID, key); err != nil {
return fmt.Errorf("delete expired idempotency key: %w", err)
}
return nil
}
func reserveIdempotencyKey(
ctx context.Context,
tx pgx.Tx,
userID string,
chatID string,
key string,
requestHash []byte,
messageID string,
ttl time.Duration,
) (bool, error) {
const query = `
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, expires_at)
VALUES ($1, $2, $3, $4, $5, statement_timestamp() + $6 * INTERVAL '1 second')
ON CONFLICT (user_id, chat_id, key) DO NOTHING
RETURNING true`
var (
inserted bool
err error
)
err = tx.QueryRow(ctx, query, userID, chatID, key, requestHash, messageID, int64(ttl/time.Second)).Scan(&inserted)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("reserve idempotency key: %w", err)
}
return inserted, nil
}
func insertMessage(
ctx context.Context,
tx pgx.Tx,
messageID string,
chatID string,
senderID string,
text string,
) (model.Message, error) {
const query = `
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ($1, $2, $3, $4)
RETURNING id, chat_id, sender_id, text, created_at`
var (
message model.Message
err error
)
err = tx.QueryRow(ctx, query, messageID, chatID, senderID, text).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if err != nil {
return model.Message{}, fmt.Errorf("insert message: %w", err)
}
return message, nil
}
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
const query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE id = $1`
var (
message model.Message
err error
)
err = tx.QueryRow(ctx, query, messageID).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, fmt.Errorf("idempotency result message not found")
}
if err != nil {
return model.Message{}, fmt.Errorf("get idempotency result message: %w", err)
}
return message, nil
}
-218
View File
@@ -1,12 +1,9 @@
package postgres
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -322,221 +319,6 @@ func (s *Store) visibleChatPositionExists(
return exists, nil
}
func (s *Store) CreateMessage(
ctx context.Context,
chatID string,
senderID string,
text string,
idempotencyKey string,
idempotencyTTL time.Duration,
) (model.Message, bool, error) {
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return model.Message{}, false, fmt.Errorf("begin create message transaction: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
visible, err := chatVisibleInTransaction(ctx, tx, chatID, senderID)
if err != nil {
return model.Message{}, false, err
}
if !visible {
return model.Message{}, false, ErrNotFound
}
requestHash := sha256.Sum256([]byte(text))
message, replay, err := createIdempotentMessage(
ctx, tx, chatID, senderID, text, idempotencyKey, requestHash[:], idempotencyTTL,
)
if err != nil {
return model.Message{}, false, err
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, fmt.Errorf("commit create message transaction: %w", err)
}
return message, replay, nil
}
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1 AND user_id = $2
)`
var visible bool
if err := tx.QueryRow(ctx, query, chatID, userID).Scan(&visible); err != nil {
return false, fmt.Errorf("check chat visibility: %w", err)
}
return visible, nil
}
func createIdempotentMessage(
ctx context.Context,
tx pgx.Tx,
chatID string,
senderID string,
text string,
idempotencyKey string,
requestHash []byte,
idempotencyTTL time.Duration,
) (model.Message, bool, error) {
for {
record, found, err := lockIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey)
if err != nil {
return model.Message{}, false, err
}
if found && record.active {
if !bytes.Equal(record.requestHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
message, err := messageByID(ctx, tx, record.messageID)
return message, true, err
}
if found {
if err := deleteIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey); err != nil {
return model.Message{}, false, err
}
}
messageID := uuid.NewString()
reserved, err := reserveIdempotencyKey(
ctx, tx, senderID, chatID, idempotencyKey, requestHash, messageID, idempotencyTTL,
)
if err != nil {
return model.Message{}, false, err
}
if !reserved {
continue
}
message, err := insertMessage(ctx, tx, messageID, chatID, senderID, text)
return message, false, err
}
}
type idempotencyRecord struct {
requestHash []byte
messageID string
active bool
}
func lockIdempotencyRecord(
ctx context.Context,
tx pgx.Tx,
userID string,
chatID string,
key string,
) (idempotencyRecord, bool, error) {
const query = `
SELECT request_hash, message_id, expires_at > statement_timestamp()
FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND key = $3
FOR UPDATE`
var record idempotencyRecord
err := tx.QueryRow(ctx, query, userID, chatID, key).Scan(
&record.requestHash,
&record.messageID,
&record.active,
)
if errors.Is(err, pgx.ErrNoRows) {
return idempotencyRecord{}, false, nil
}
if err != nil {
return idempotencyRecord{}, false, fmt.Errorf("lock idempotency key: %w", err)
}
return record, true, nil
}
func deleteIdempotencyRecord(ctx context.Context, tx pgx.Tx, userID, chatID, key string) error {
const query = `
DELETE FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND key = $3`
if _, err := tx.Exec(ctx, query, userID, chatID, key); err != nil {
return fmt.Errorf("delete expired idempotency key: %w", err)
}
return nil
}
func reserveIdempotencyKey(
ctx context.Context,
tx pgx.Tx,
userID string,
chatID string,
key string,
requestHash []byte,
messageID string,
ttl time.Duration,
) (bool, error) {
const query = `
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, expires_at)
VALUES ($1, $2, $3, $4, $5, statement_timestamp() + $6 * INTERVAL '1 second')
ON CONFLICT (user_id, chat_id, key) DO NOTHING
RETURNING true`
var inserted bool
err := tx.QueryRow(ctx, query, userID, chatID, key, requestHash, messageID, int64(ttl/time.Second)).Scan(&inserted)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("reserve idempotency key: %w", err)
}
return inserted, nil
}
func insertMessage(
ctx context.Context,
tx pgx.Tx,
messageID string,
chatID string,
senderID string,
text string,
) (model.Message, error) {
const query = `
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ($1, $2, $3, $4)
RETURNING id, chat_id, sender_id, text, created_at`
var message model.Message
err := tx.QueryRow(ctx, query, messageID, chatID, senderID, text).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if err != nil {
return model.Message{}, fmt.Errorf("insert message: %w", err)
}
return message, nil
}
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
const query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE id = $1`
var message model.Message
err := tx.QueryRow(ctx, query, messageID).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, fmt.Errorf("idempotency result message not found")
}
if err != nil {
return model.Message{}, fmt.Errorf("get idempotency result message: %w", err)
}
return message, nil
}
func (s *Store) ListMessages(
ctx context.Context,
chatID string,
+72 -15
View File
@@ -11,15 +11,37 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/postgres"
)
func TestConcurrentUsernameCreation(t *testing.T) {
pool := openTestDatabase(t)
store := postgres.New(pool)
type PostgresSuite struct {
suite.Suite
pool *pgxpool.Pool
store *postgres.Store
}
func TestPostgresSuite(t *testing.T) {
suite.Run(t, new(PostgresSuite))
}
func (s *PostgresSuite) SetupSuite() {
s.pool = openTestDatabase(s.T())
s.store = postgres.New(s.pool)
}
func (s *PostgresSuite) TearDownSuite() {
if s.pool != nil {
s.pool.Close()
}
}
func (s *PostgresSuite) TestConcurrentUsernameCreation() {
t := s.T()
store := s.store
username := "race_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
const workers = 8
@@ -52,9 +74,10 @@ func TestConcurrentUsernameCreation(t *testing.T) {
}
}
func TestCreateChatRollsBackForUnknownMember(t *testing.T) {
pool := openTestDatabase(t)
store := postgres.New(pool)
func (s *PostgresSuite) TestCreateChatRollsBackForUnknownMember() {
t := s.T()
pool := s.pool
store := s.store
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
if err != nil {
t.Fatalf("CreateUser() error = %v", err)
@@ -70,9 +93,10 @@ func TestCreateChatRollsBackForUnknownMember(t *testing.T) {
}
}
func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
pool := openTestDatabase(t)
store := postgres.New(pool)
func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
t := s.T()
pool := s.pool
store := s.store
owner, chatID := createOwnerAndChat(t, store)
key := uuid.NewString()
@@ -95,8 +119,9 @@ func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
}
}
func TestConcurrentMessageIdempotency(t *testing.T) {
pool := openTestDatabase(t)
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
t := s.T()
pool := s.pool
stores := []*postgres.Store{postgres.New(pool), postgres.New(pool)}
owner, chatID := createOwnerAndChat(t, stores[0])
key := uuid.NewString()
@@ -146,9 +171,10 @@ func TestConcurrentMessageIdempotency(t *testing.T) {
}
}
func TestMessageIdempotencyScopeAndExpiry(t *testing.T) {
pool := openTestDatabase(t)
store := postgres.New(pool)
func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
t := s.T()
pool := s.pool
store := s.store
owner, chatID := createOwnerAndChat(t, store)
second, err := store.CreateUser(context.Background(), uniqueUsername(), "Second", "password-hash")
if err != nil {
@@ -182,6 +208,38 @@ func TestMessageIdempotencyScopeAndExpiry(t *testing.T) {
}
}
func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
t := s.T()
owner, chatID := createOwnerAndChat(t, s.store)
expiredKey := uuid.NewString()
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", expiredKey, 24*time.Hour); err != nil {
t.Fatalf("create expired message: %v", err)
}
if _, err := s.pool.Exec(context.Background(), `
UPDATE message_idempotency
SET created_at = clock_timestamp() - INTERVAL '2 days',
expires_at = clock_timestamp() - INTERVAL '1 day'
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey); err != nil {
t.Fatalf("expire idempotency key: %v", err)
}
if _, _, err := s.store.CreateMessage(
context.Background(), chatID, owner.ID, "new message", uuid.NewString(), 24*time.Hour,
); err != nil {
t.Fatalf("create new message: %v", err)
}
var remaining int
if err := s.pool.QueryRow(context.Background(), `
SELECT count(*)
FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey).Scan(&remaining); err != nil {
t.Fatalf("count expired idempotency records: %v", err)
}
if remaining != 0 {
t.Fatalf("expired idempotency records = %d, want 0", remaining)
}
}
func createOwnerAndChat(t *testing.T, store *postgres.Store) (model.User, string) {
t.Helper()
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
@@ -219,7 +277,6 @@ func openTestDatabase(t *testing.T) *pgxpool.Pool {
pool.Close()
t.Fatalf("database.Migrate() error = %v", err)
}
t.Cleanup(pool.Close)
return pool
}