forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
|
||||
return domain.Message{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := m.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID, Text: text, AttachmentIDs: attachmentIDs}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO message_idempotency_keys (user_id, chat_id, key, message_id)
|
||||
VALUES ($1, $2, $3, gen_random_uuid())
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING message_id::text`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return replayMessage(ctx, tx, callerID, chatID, idempotencyKey, text, attachmentIDs)
|
||||
case isFKViolation(err):
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at`,
|
||||
msg.ID, chatID, callerID, encodeText(text),
|
||||
).Scan(&msg.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
// Составной FK сам отклоняет вложение другого чата и неизвестное вложение. Та же транзакция:
|
||||
// при ошибке не останется ни сообщения, ни ключа идемпотентности.
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, e := tx.Query(ctx, `SELECT id::text, status FROM attachments WHERE chat_id=$1 AND id=ANY($2::uuid[]) FOR SHARE`, chatID, attachmentIDs)
|
||||
if e != nil {
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
count := 0
|
||||
failed := false
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if e = rows.Scan(&id, &status); e != nil {
|
||||
rows.Close()
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
count++
|
||||
failed = failed || status == "failed"
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
if count != len(attachmentIDs) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if failed {
|
||||
return domain.Message{}, domain.ErrConflict
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
SELECT $1, $2, t.id::uuid, t.ord::int
|
||||
FROM unnest($3::text[]) WITH ORDINALITY AS t(id, ord)`,
|
||||
msg.ID, chatID, attachmentIDs,
|
||||
)
|
||||
if isFKViolation(err) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func replayMessage(ctx context.Context, tx pgx.Tx, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID}
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT m.id::text, m.text, m.created_at, COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM message_idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, domain.ErrUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.Text = decodeText(msg.Text)
|
||||
if msg.Text != text || !slices.Equal(msg.AttachmentIDs, attachmentIDs) {
|
||||
return domain.Message{}, domain.ErrIdempotencyConflict
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PurgeIdempotencyKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tag, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM message_idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`,
|
||||
ttl.Seconds(),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
member, err := m.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
return m.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
func (m *Messages) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID,
|
||||
).Scan(&member)
|
||||
if err != nil {
|
||||
return false, mapErr(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
cur, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
scope := "chat:" + chatID
|
||||
if cursor != "" && cur.Scope != scope {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var rows pgx.Rows
|
||||
if cur.IsZero() {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2`,
|
||||
chatID, limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND (m.created_at, m.id) > ($2, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`,
|
||||
chatID, cur.CreatedAt, cur.ID, limit+1,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) {
|
||||
var msg domain.Message
|
||||
err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs)
|
||||
msg.Text = decodeText(msg.Text)
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Message]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: scope,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
Reference in New Issue
Block a user