forked from mtusi2026/mtusi2026lab5
Реализация на 5
This commit is contained in:
@@ -1,10 +1,8 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
@@ -26,55 +24,49 @@ func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
// CreateIdempotentTx serializes only requests sharing an idempotency scope.
|
||||
// The transaction commits both the message and its replay record, or neither.
|
||||
func (r *MessagesRepo) CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error) {
|
||||
scope := req.SenderID.String() + ":POST:" + req.ChatID.String() + ":" + req.IdempotencyKey
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, scope); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to lock message key")
|
||||
// LockKeyTx serializes persistence for one idempotency scope.
|
||||
func (r *MessagesRepo) LockKeyTx(ctx context.Context, tx pgx.Tx, scope string) error {
|
||||
_, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, scope)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to lock message key")
|
||||
}
|
||||
hash := messageHash(req)
|
||||
var hashVersion int
|
||||
var storedHash []byte
|
||||
var messageID uuid.UUID
|
||||
err := tx.QueryRow(ctx, `SELECT request_hash, message_id, hash_version FROM message_idempotency
|
||||
WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`,
|
||||
req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&storedHash, &messageID, &hashVersion)
|
||||
if err == nil {
|
||||
if hashVersion == 1 && len(req.AttachmentIDs) == 0 {
|
||||
hash = sha256.Sum256([]byte(req.Text))
|
||||
} else if hashVersion != 2 {
|
||||
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
|
||||
}
|
||||
if !bytes.Equal(hash[:], storedHash) {
|
||||
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
|
||||
}
|
||||
return scanMessage(tx.QueryRow(ctx, `SELECT `+messageColumns+` FROM messages WHERE id=$1`, messageID))
|
||||
return nil
|
||||
}
|
||||
func (r *MessagesRepo) ReplayTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.MessageReplay, error) {
|
||||
v := new(dto.MessageReplay)
|
||||
err := tx.QueryRow(ctx, `SELECT request_hash,message_id,hash_version FROM message_idempotency WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`, req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&v.Hash, &v.MessageID, &v.HashVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to read message key")
|
||||
}
|
||||
message := dto.Message{ID: uuid.New(), ChatID: req.ChatID, SenderID: req.SenderID, Text: req.Text, AttachmentIDs: append([]uuid.UUID{}, req.AttachmentIDs...), CreatedAt: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`,
|
||||
message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt); err != nil {
|
||||
return v, nil
|
||||
}
|
||||
func (r *MessagesRepo) MessageTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.Message, error) {
|
||||
return scanMessage(tx.QueryRow(ctx, `SELECT `+messageColumns+` FROM messages WHERE id=$1`, id))
|
||||
}
|
||||
func (r *MessagesRepo) InsertMessageTx(ctx context.Context, tx pgx.Tx, message dto.Message) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`, message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
|
||||
if err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
|
||||
return nil, apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return nil, apperr.WrapPostgres(err, "failed to create message")
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
for position, attachmentID := range req.AttachmentIDs {
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_attachments(message_id,chat_id,attachment_id,position) VALUES($1,$2,$3,$4)`, message.ID, message.ChatID, attachmentID, position); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to link attachment")
|
||||
for position, id := range message.AttachmentIDs {
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_attachments(message_id,chat_id,attachment_id,position) VALUES($1,$2,$3,$4)`, message.ID, message.ChatID, id, position); err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to link attachment")
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at,hash_version)
|
||||
VALUES($1,'POST',$2,$3,$4,$5,clock_timestamp()+interval '24 hours',2)
|
||||
ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,
|
||||
message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at,hash_version=EXCLUDED.hash_version`, req.SenderID, req.ChatID, req.IdempotencyKey, hash[:], message.ID); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to save message key")
|
||||
return nil
|
||||
}
|
||||
func (r *MessagesRepo) SaveKeyTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage, hash []byte, messageID uuid.UUID, expires time.Time) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at,hash_version) VALUES($1,'POST',$2,$3,$4,$5,$6,2) ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at,hash_version=EXCLUDED.hash_version`, req.SenderID, req.ChatID, req.IdempotencyKey, hash, messageID, expires)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to save message key")
|
||||
}
|
||||
return &message, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
@@ -120,20 +112,10 @@ func scanMessage(row pgx.Row) (*dto.Message, error) {
|
||||
const messageColumns = `id, chat_id, sender_id, text, created_at,
|
||||
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=messages.id ORDER BY position)`
|
||||
|
||||
func messageHash(req dto.CreateMessage) [32]byte {
|
||||
// Field order and a non-nil list define the canonical v2 representation.
|
||||
canonical := struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
||||
}{req.Text, append([]uuid.UUID{}, req.AttachmentIDs...)}
|
||||
encoded, _ := json.Marshal(canonical) // strings and UUIDs have no encoding failures.
|
||||
return sha256.Sum256(encoded)
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, ids []uuid.UUID) ([]dto.MessageAttachment, error) {
|
||||
// Prevent a concurrent integrity update from invalidating the checked rows
|
||||
// until the message and its links have committed together.
|
||||
rows, err := tx.Query(ctx, `SELECT id, chat_id, integrity_missing FROM attachments WHERE id=ANY($1) ORDER BY id FOR SHARE`, ids)
|
||||
rows, err := tx.Query(ctx, `SELECT id, chat_id, integrity_missing,status FROM attachments WHERE id=ANY($1) ORDER BY id FOR SHARE`, ids)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to read attachments")
|
||||
}
|
||||
@@ -141,7 +123,7 @@ func (r *MessagesRepo) AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, i
|
||||
result := make([]dto.MessageAttachment, 0, len(ids))
|
||||
for rows.Next() {
|
||||
var a dto.MessageAttachment
|
||||
if err := rows.Scan(&a.ID, &a.ChatID, &a.Missing); err != nil {
|
||||
if err := rows.Scan(&a.ID, &a.ChatID, &a.Missing, &a.Status); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to read attachment")
|
||||
}
|
||||
result = append(result, a)
|
||||
|
||||
Reference in New Issue
Block a user