97 lines
3.7 KiB
Go
97 lines
3.7 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"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()
|
|
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 == "failed" {
|
|
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
|
|
}
|
|
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 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.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)`
|
|
args = append(args, after.CreatedAt, after.ID)
|
|
}
|
|
query += ` ORDER BY m.created_at,m.id LIMIT $2`
|
|
rows, err := s.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, dbError(err)
|
|
}
|
|
defer rows.Close()
|
|
result := []domain.Message{}
|
|
for rows.Next() {
|
|
var m domain.Message
|
|
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.AttachmentIDs, &m.CreatedAt); err != nil {
|
|
return nil, dbError(err)
|
|
}
|
|
result = append(result, m)
|
|
}
|
|
return result, dbError(rows.Err())
|
|
}
|