lab4 done
This commit is contained in:
@@ -3,41 +3,76 @@ package postgres
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (s *Storage) CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error) {
|
||||
return s.CreateMessageWithAttachments(ctx, chatID, senderID, text, key, nil)
|
||||
}
|
||||
|
||||
func (s *Storage) CreateMessageWithAttachments(ctx context.Context, chatID, senderID, text, key string, ids []string) (domain.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
message := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text}
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Serialize this idempotency scope before validating attachments. A replay remains a
|
||||
// replay even when reconciliation has since marked an original as missing.
|
||||
if key != "" {
|
||||
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, senderID+":"+chatID+":"+key)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
old := domain.Message{ChatID: chatID, SenderID: senderID}
|
||||
err = tx.QueryRow(ctx, `SELECT id::text,text,attachment_ids::text[],created_at FROM messages WHERE sender_id=$1 AND chat_id=$2 AND idempotency_key=$3`, senderID, chatID, key).Scan(&old.ID, &old.Text, &old.AttachmentIDs, &old.CreatedAt)
|
||||
if err == nil {
|
||||
if old.Text != text || !slices.Equal(old.AttachmentIDs, ids) {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
}
|
||||
// Lock each metadata row against reconciler updates until the link is committed.
|
||||
for _, id := range ids {
|
||||
var status string
|
||||
err = tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE`, id, chatID).Scan(&status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
if status != "ready" {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Вложение не готово")
|
||||
}
|
||||
}
|
||||
m := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}
|
||||
var storedKey *string
|
||||
if key != "" {
|
||||
storedKey = &key
|
||||
}
|
||||
// One row contains both the side effect and its durable replay result.
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,idempotency_key)
|
||||
VALUES($1,$2,$3,$4,$5) ON CONFLICT (sender_id,chat_id,idempotency_key) DO NOTHING RETURNING created_at`,
|
||||
message.ID, chatID, senderID, text, storedKey).Scan(&message.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// A new READ COMMITTED statement sees the winner after the unique-index wait.
|
||||
err = s.pool.QueryRow(ctx, `SELECT id::text,text,created_at FROM messages
|
||||
WHERE sender_id=$1 AND chat_id=$2 AND idempotency_key=$3`, senderID, chatID, key).
|
||||
Scan(&message.ID, &message.Text, &message.CreatedAt)
|
||||
if err == nil && message.Text != text {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,idempotency_key,attachment_ids) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, m.ID, chatID, senderID, text, storedKey, ids).Scan(&m.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
return message, dbError(err)
|
||||
return m, dbError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m WHERE m.chat_id=$1`
|
||||
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.attachment_ids::text[],m.created_at FROM messages m WHERE m.chat_id=$1`
|
||||
args := []any{chatID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (m.created_at,m.id)>($3,$4)`
|
||||
@@ -49,13 +84,13 @@ func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]domain.Message, 0)
|
||||
result := []domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.AttachmentIDs, &m.CreatedAt); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
messages = append(messages, m)
|
||||
result = append(result, m)
|
||||
}
|
||||
return messages, dbError(rows.Err())
|
||||
return result, dbError(rows.Err())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user