forked from mtusi2026/mtusi2026lab6
136 lines
5.5 KiB
Go
136 lines
5.5 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
|
|
"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}
|
|
}
|
|
|
|
// 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")
|
|
}
|
|
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 err != nil {
|
|
return nil, apperr.WrapPostgres(err, "failed to read message key")
|
|
}
|
|
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 apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
|
}
|
|
return apperr.WrapPostgres(err, "failed to create message")
|
|
}
|
|
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")
|
|
}
|
|
}
|
|
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 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 (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,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")
|
|
}
|
|
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, &a.Status); 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
|
|
}
|