96 lines
3.6 KiB
Go
96 lines
3.6 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"reflect"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
var ErrAttachmentNotFound = errors.New("attachment not found")
|
|
var ErrAttachmentFailed = errors.New("attachment failed")
|
|
|
|
var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message")
|
|
|
|
// CreateIdempotent commits the message and its replay record together.
|
|
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string, attachments ...[]string) (Message, error) {
|
|
ids := []string{}
|
|
if len(attachments) > 0 && attachments[0] != nil {
|
|
ids = attachments[0]
|
|
}
|
|
ctx, cancel := boundedQuery(ctx)
|
|
defer cancel()
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
|
|
// The transaction-scoped lock is shared by all API replicas. Hash collisions
|
|
// only serialize unrelated requests; the full scope is checked by the query.
|
|
scope := senderID + ":POST:/api/v1/chats/" + chatID + "/messages:" + key
|
|
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil {
|
|
return Message{}, err
|
|
}
|
|
// A shared row lock prevents failure publication racing with a new link.
|
|
hasFailed := false
|
|
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 Message{}, ErrAttachmentNotFound
|
|
}
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
hasFailed = hasFailed || status == "failed"
|
|
}
|
|
|
|
var message Message
|
|
err = tx.QueryRow(ctx, `
|
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=m.id ORDER BY position)
|
|
FROM message_idempotency i JOIN messages m ON m.id = i.message_id
|
|
WHERE i.sender_id=$1 AND i.chat_id=$2 AND i.key=$3
|
|
AND i.expires_at > clock_timestamp()`, senderID, chatID, key).
|
|
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs)
|
|
if err == nil {
|
|
message.CreatedAt = message.CreatedAt.UTC()
|
|
if message.Text != text || !reflect.DeepEqual(message.AttachmentIDs, ids) {
|
|
return Message{}, ErrIdempotencyConflict
|
|
}
|
|
return message, tx.Commit(ctx)
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
return Message{}, err
|
|
}
|
|
|
|
if hasFailed {
|
|
return Message{}, ErrAttachmentFailed
|
|
}
|
|
|
|
// Expiry permits key reuse; it never deletes the original message.
|
|
if _, err = tx.Exec(ctx, "DELETE FROM message_idempotency WHERE sender_id=$1 AND chat_id=$2 AND key=$3", senderID, chatID, key); err != nil {
|
|
return Message{}, err
|
|
}
|
|
message = Message{
|
|
AttachmentIDs: ids, ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
|
|
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, chatID, senderID, text, message.CreatedAt); err != nil {
|
|
return Message{}, err
|
|
}
|
|
for position, id := range ids {
|
|
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", message.ID, id, position); err != nil {
|
|
return Message{}, err
|
|
}
|
|
}
|
|
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(sender_id,chat_id,key,message_id,expires_at)
|
|
VALUES($1,$2,$3,$4,clock_timestamp() + $5 * interval '1 second')`, senderID, chatID, key, message.ID, s.idempotencyTTL.Seconds()); err != nil {
|
|
return Message{}, err
|
|
}
|
|
return message, tx.Commit(ctx)
|
|
}
|