forked from mtusi2026/mtusi2026lab5
154 lines
6.4 KiB
Go
154 lines
6.4 KiB
Go
package storage
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgerrcode"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
|
)
|
|
|
|
type MessagesRepo struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
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")
|
|
}
|
|
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))
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
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 {
|
|
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
|
|
return nil, apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
|
}
|
|
return nil, 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")
|
|
}
|
|
}
|
|
|
|
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 &message, nil
|
|
}
|
|
|
|
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
|
const query = `SELECT ` + messageColumns + ` FROM messages WHERE chat_id = $1 AND id = $2`
|
|
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
|
|
}
|
|
|
|
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
|
|
query := `SELECT ` + messageColumns + ` FROM messages WHERE chat_id = $1`
|
|
args := []any{chatID, page.Limit}
|
|
if page.After != nil {
|
|
query += ` AND (created_at, id) > ($3, $4)`
|
|
args = append(args, page.After.CreatedAt, page.After.ID)
|
|
}
|
|
query += ` ORDER BY created_at, id LIMIT $2`
|
|
rows, err := r.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
|
}
|
|
defer rows.Close()
|
|
messages := make([]dto.Message, 0)
|
|
for rows.Next() {
|
|
message, err := scanMessage(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
messages = append(messages, *message)
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
|
}
|
|
return messages, nil
|
|
}
|
|
|
|
func scanMessage(row pgx.Row) (*dto.Message, error) {
|
|
var message dto.Message
|
|
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs); err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to get message")
|
|
}
|
|
return &message, nil
|
|
}
|
|
|
|
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)
|
|
if err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to read attachments")
|
|
}
|
|
defer rows.Close()
|
|
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 {
|
|
return nil, apperr.WrapPostgres(err, "failed to read attachment")
|
|
}
|
|
result = append(result, a)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to read attachments")
|
|
}
|
|
return result, nil
|
|
}
|