chore: import lab5 baseline
This commit is contained in:
@@ -0,0 +1,374 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const expiredIdempotencyCleanupBatch = 100
|
||||
|
||||
func (s *Store) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
var (
|
||||
tx pgx.Tx
|
||||
err error
|
||||
visible bool
|
||||
requestHash [sha256.Size]byte
|
||||
message model.Message
|
||||
replay bool
|
||||
)
|
||||
|
||||
tx, err = s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("begin create message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
visible, err = chatVisibleInTransaction(ctx, tx, chatID, senderID)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !visible {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
validAttachments, failedAttachment, err := attachmentsBelongToChat(ctx, tx, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !validAttachments {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
if failedAttachment {
|
||||
return model.Message{}, false, ErrConflict
|
||||
}
|
||||
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
|
||||
requestHash, err = messageRequestHash(text, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
message, replay, err = createIdempotentMessage(
|
||||
ctx, tx, chatID, senderID, text, attachmentIDs, idempotencyKey, requestHash[:], idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("commit create message transaction: %w", err)
|
||||
}
|
||||
return message, replay, nil
|
||||
}
|
||||
|
||||
func messageRequestHash(text string, attachmentIDs []string) ([sha256.Size]byte, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, attachmentIDs})
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("marshal message request: %w", err)
|
||||
}
|
||||
return sha256.Sum256(payload), nil
|
||||
}
|
||||
|
||||
func attachmentsBelongToChat(ctx context.Context, tx pgx.Tx, chatID string, attachmentIDs []string) (bool, bool, error) {
|
||||
if len(attachmentIDs) == 0 {
|
||||
return true, false, nil
|
||||
}
|
||||
const query = `
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1 AND id::text = ANY($2)
|
||||
AND status IN ('queued', 'processing', 'ready', 'failed')
|
||||
FOR UPDATE`
|
||||
rows, err := tx.Query(ctx, query, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return false, false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var count int
|
||||
var failed bool
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
return false, false, fmt.Errorf("scan message attachment: %w", err)
|
||||
}
|
||||
count++
|
||||
failed = failed || status == model.AttachmentFailed
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return false, false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
return count == len(attachmentIDs), failed, nil
|
||||
}
|
||||
|
||||
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var visible bool
|
||||
if err := tx.QueryRow(ctx, query, chatID, userID).Scan(&visible); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
return visible, nil
|
||||
}
|
||||
|
||||
func createIdempotentMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
requestHash []byte,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
for {
|
||||
var (
|
||||
record idempotencyRecord
|
||||
found bool
|
||||
err error
|
||||
messageID string
|
||||
reserved bool
|
||||
message model.Message
|
||||
)
|
||||
|
||||
record, found, err = lockIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if found && record.active {
|
||||
if !bytes.Equal(record.requestHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
message, err = messageByID(ctx, tx, record.messageID)
|
||||
return message, true, err
|
||||
}
|
||||
if found {
|
||||
if err := deleteIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
}
|
||||
|
||||
messageID = uuid.NewString()
|
||||
reserved, err = reserveIdempotencyKey(
|
||||
ctx, tx, senderID, chatID, idempotencyKey, requestHash, messageID, idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !reserved {
|
||||
continue
|
||||
}
|
||||
|
||||
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text, attachmentIDs)
|
||||
return message, false, err
|
||||
}
|
||||
}
|
||||
|
||||
func deleteExpiredIdempotencyRecords(ctx context.Context, tx pgx.Tx, limit int) error {
|
||||
const query = `
|
||||
WITH expired AS (
|
||||
SELECT ctid
|
||||
FROM message_idempotency
|
||||
WHERE expires_at <= statement_timestamp()
|
||||
ORDER BY expires_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM message_idempotency records
|
||||
USING expired
|
||||
WHERE records.ctid = expired.ctid`
|
||||
|
||||
if _, err := tx.Exec(ctx, query, limit); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency records: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type idempotencyRecord struct {
|
||||
requestHash []byte
|
||||
messageID string
|
||||
active bool
|
||||
}
|
||||
|
||||
func lockIdempotencyRecord(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
) (idempotencyRecord, bool, error) {
|
||||
const query = `
|
||||
SELECT request_hash, message_id, expires_at > statement_timestamp()
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3
|
||||
FOR UPDATE`
|
||||
|
||||
var (
|
||||
record idempotencyRecord
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key).Scan(
|
||||
&record.requestHash,
|
||||
&record.messageID,
|
||||
&record.active,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return idempotencyRecord{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return idempotencyRecord{}, false, fmt.Errorf("lock idempotency key: %w", err)
|
||||
}
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func deleteIdempotencyRecord(ctx context.Context, tx pgx.Tx, userID, chatID, key string) error {
|
||||
const query = `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`
|
||||
if _, err := tx.Exec(ctx, query, userID, chatID, key); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func reserveIdempotencyKey(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
requestHash []byte,
|
||||
messageID string,
|
||||
ttl time.Duration,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, statement_timestamp() + $6 * INTERVAL '1 second')
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING true`
|
||||
|
||||
var (
|
||||
inserted bool
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key, requestHash, messageID, int64(ttl/time.Second)).Scan(&inserted)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reserve idempotency key: %w", err)
|
||||
}
|
||||
return inserted, nil
|
||||
}
|
||||
|
||||
func insertMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
messageID string,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
) (model.Message, error) {
|
||||
const query = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID, chatID, senderID, text).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
if err := insertMessageAttachments(ctx, tx, messageID, chatID, attachmentIDs); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
message.AttachmentIDs = make([]string, len(attachmentIDs))
|
||||
copy(message.AttachmentIDs, attachmentIDs)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func insertMessageAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, attachmentIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3, $4)`
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, query, messageID, chatID, attachmentID, position); err != nil {
|
||||
return fmt.Errorf("insert message attachment: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
|
||||
const query = `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position
|
||||
)
|
||||
FROM messages m
|
||||
WHERE m.id = $1`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, fmt.Errorf("idempotency result message not found")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("get idempotency result message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
Reference in New Issue
Block a user