forked from mtusi2026/mtusi2026lab3
feat: add shared idempotency and replica identity
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidMembers = errors.New("invalid members")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
)
|
||||
@@ -0,0 +1,653 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, created_at`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, uuid.NewString(), username, displayName, passwordHash).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.UserCredentials, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1`
|
||||
|
||||
var credentials model.UserCredentials
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.ID,
|
||||
&credentials.Username,
|
||||
&credentials.DisplayName,
|
||||
&credentials.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.UserCredentials{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.UserCredentials{}, fmt.Errorf("get user by username: %w", err)
|
||||
}
|
||||
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
callerID string,
|
||||
) (model.Chat, error) {
|
||||
if !validMembers(memberIDs, callerID) {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("begin create chat transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
valid, err := allUsersExist(ctx, tx, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !valid {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
chat, err := insertChat(ctx, tx, title)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := insertMembers(ctx, tx, chat.ID, memberIDs); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("commit create chat transaction: %w", err)
|
||||
}
|
||||
|
||||
chat.MemberIDs = append([]string(nil), memberIDs...)
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func validMembers(memberIDs []string, callerID string) bool {
|
||||
callerUUID, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
callerIncluded := false
|
||||
for _, memberID := range memberIDs {
|
||||
memberUUID, err := uuid.Parse(memberID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if _, exists := seen[memberUUID]; exists {
|
||||
return false
|
||||
}
|
||||
|
||||
seen[memberUUID] = struct{}{}
|
||||
callerIncluded = callerIncluded || memberUUID == callerUUID
|
||||
}
|
||||
|
||||
return callerIncluded
|
||||
}
|
||||
|
||||
func allUsersExist(ctx context.Context, tx pgx.Tx, memberIDs []string) (bool, error) {
|
||||
const query = `
|
||||
SELECT count(*)
|
||||
FROM users
|
||||
WHERE id::text = ANY($1)`
|
||||
|
||||
var count int
|
||||
if err := tx.QueryRow(ctx, query, memberIDs).Scan(&count); err != nil {
|
||||
return false, fmt.Errorf("check chat members: %w", err)
|
||||
}
|
||||
|
||||
return count == len(memberIDs), nil
|
||||
}
|
||||
|
||||
func insertChat(ctx context.Context, tx pgx.Tx, title string) (model.Chat, error) {
|
||||
const query = `
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, title, created_at`
|
||||
|
||||
var chat model.Chat
|
||||
if err := tx.QueryRow(ctx, query, uuid.NewString(), title).Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func insertMembers(ctx context.Context, tx pgx.Tx, chatID string, memberIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
VALUES ($1, $2, $3)`
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(query, chatID, memberID, position)
|
||||
}
|
||||
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
defer func() { _ = results.Close() }()
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return fmt.Errorf("close chat members batch: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members visible
|
||||
WHERE visible.chat_id = c.id AND visible.user_id = $2
|
||||
)
|
||||
GROUP BY c.id, c.title, c.created_at`
|
||||
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat for user: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Chat, bool, error) {
|
||||
if after != nil {
|
||||
valid, err := s.visibleChatPositionExists(ctx, userID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(all_members.user_id::text ORDER BY all_members.position)
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id AND visible.user_id = $1
|
||||
JOIN chat_members all_members ON all_members.chat_id = c.id
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, userID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Chat](func(row pgx.CollectableRow) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
return chat, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan chats: %w", err)
|
||||
}
|
||||
|
||||
return page(chats, limit)
|
||||
}
|
||||
|
||||
func (s *Store) visibleChatPositionExists(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1 AND c.created_at = $2 AND c.id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, userID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate chat cursor: %w", err)
|
||||
}
|
||||
|
||||
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,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Message, bool, error) {
|
||||
visible, err := s.chatVisible(ctx, chatID, userID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !visible {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if after != nil {
|
||||
valid, err := s.messagePositionExists(ctx, chatID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, chatID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Message](func(row pgx.CollectableRow) (model.Message, error) {
|
||||
var message model.Message
|
||||
err := row.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
return message, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan messages: %w", err)
|
||||
}
|
||||
|
||||
return page(messages, limit)
|
||||
}
|
||||
|
||||
func (s *Store) chatVisible(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) messagePositionExists(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND created_at = $2 AND id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate message cursor: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func page[T any](items []T, limit int) ([]T, bool, error) {
|
||||
if limit < 1 {
|
||||
return nil, false, fmt.Errorf("limit must be positive")
|
||||
}
|
||||
if len(items) <= limit {
|
||||
return items, false, nil
|
||||
}
|
||||
|
||||
return items[:limit], true, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var postgresError *pgconn.PgError
|
||||
return errors.As(err, &postgresError) && postgresError.Code == "23505"
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"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)
|
||||
username := "race_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
|
||||
|
||||
const workers = 8
|
||||
results := make(chan error, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := store.CreateUser(context.Background(), username, "Race user", "password-hash")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, postgres.ErrConflict):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != workers-1 {
|
||||
t.Fatalf("created = %d, conflicts = %d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRollsBackForUnknownMember(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
store := postgres.New(pool)
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
|
||||
before := chatCount(t, pool)
|
||||
_, err = store.CreateChat(context.Background(), "Invalid chat", []string{owner.ID, uuid.NewString()}, owner.ID)
|
||||
if !errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
t.Fatalf("CreateChat() error = %v, want ErrInvalidMembers", err)
|
||||
}
|
||||
if after := chatCount(t, pool); after != before {
|
||||
t.Fatalf("chat count changed from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
store := postgres.New(pool)
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
key := uuid.NewString()
|
||||
|
||||
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
|
||||
if err != nil || replay {
|
||||
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
|
||||
}
|
||||
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
|
||||
if err != nil || !replay {
|
||||
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatalf("replay message = %v, want %v", second, first)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessageIdempotency(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
stores := []*postgres.Store{postgres.New(pool), postgres.New(pool)}
|
||||
owner, chatID := createOwnerAndChat(t, stores[0])
|
||||
key := uuid.NewString()
|
||||
|
||||
const workers = 8
|
||||
type result struct {
|
||||
message model.Message
|
||||
replay bool
|
||||
err error
|
||||
}
|
||||
results := make(chan result, workers)
|
||||
var group sync.WaitGroup
|
||||
for worker := range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
message, replay, err := stores[worker%len(stores)].CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "concurrent body", key, 24*time.Hour,
|
||||
)
|
||||
results <- result{message: message, replay: replay, err: err}
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var messageID string
|
||||
var created int
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("CreateMessage() error = %v", result.err)
|
||||
}
|
||||
if messageID == "" {
|
||||
messageID = result.message.ID
|
||||
}
|
||||
if result.message.ID != messageID {
|
||||
t.Fatalf("message ID = %s, want %s", result.message.ID, messageID)
|
||||
}
|
||||
if !result.replay {
|
||||
created++
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Fatalf("new message results = %d, want 1", created)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyScopeAndExpiry(t *testing.T) {
|
||||
pool := openTestDatabase(t)
|
||||
store := postgres.New(pool)
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
second, err := store.CreateUser(context.Background(), uniqueUsername(), "Second", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Shared", []string{owner.ID, second.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
key := uuid.NewString()
|
||||
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("owner CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("second user CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("other chat CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, err := 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, chat.ID, key); err != nil {
|
||||
t.Fatalf("expire idempotency key: %v", err)
|
||||
}
|
||||
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", key, 24*time.Hour)
|
||||
if err != nil || replay || message.Text != "after expiry" {
|
||||
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
|
||||
}
|
||||
}
|
||||
|
||||
func createOwnerAndChat(t *testing.T, store *postgres.Store) (model.User, string) {
|
||||
t.Helper()
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Chat", []string{owner.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
return owner, chat.ID
|
||||
}
|
||||
|
||||
func messageCount(t *testing.T, pool *pgxpool.Pool, chatID string) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id = $1", chatID).Scan(&count); err != nil {
|
||||
t.Fatalf("count messages: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func openTestDatabase(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := testSecret(t, "TEST_DATABASE_URL", "TEST_DATABASE_URL_FILE")
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: url, MinConnections: 0, MaxConnections: 10,
|
||||
MaxConnectionAge: time.Minute, MaxConnectionIdle: time.Minute,
|
||||
HealthCheckPeriod: time.Minute, ConnectTimeout: 5 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("database.Open() error = %v", err)
|
||||
}
|
||||
if err := database.Migrate(context.Background(), pool, 30*time.Second); err != nil {
|
||||
pool.Close()
|
||||
t.Fatalf("database.Migrate() error = %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
func testSecret(t *testing.T, valueName, fileName string) string {
|
||||
t.Helper()
|
||||
if value := strings.TrimSpace(os.Getenv(valueName)); value != "" {
|
||||
return value
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileName))
|
||||
if path == "" {
|
||||
t.Skipf("set %s or %s to run integration tests", valueName, fileName)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", fileName, err)
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func uniqueUsername() string {
|
||||
return "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
|
||||
}
|
||||
|
||||
func chatCount(t *testing.T, pool *pgxpool.Pool) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&count); err != nil {
|
||||
t.Fatalf("count chats: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
Reference in New Issue
Block a user