package postgres import ( "bytes" "context" "net/http" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "high-loud-apps-labs/internal/domain" ) type MessageRepo struct { pool *pgxpool.Pool } func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo { return &MessageRepo{pool: pool} } func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error { const q = ` INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) ` _, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt) if err != nil { if foreignKeyViolation(err) { return &domain.NotFoundError{Entity: "chat", ID: m.ChatID} } if checkViolation(err) { return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"} } return mapError(err) } return nil } func (r *MessageRepo) CreateIdempotent( ctx context.Context, scope domain.IdempotencyScope, requestHash []byte, fresh *domain.Message, freshResponse []byte, ttl time.Duration, ) (*domain.CreateIdempotentResult, error) { tx, err := r.pool.Begin(ctx) if err != nil { return nil, mapError(err) } defer func() { _ = tx.Rollback(ctx) }() // 1) Убираем просроченную запись, чтобы ON CONFLICT сработал // только на живой, а не на истёкшей строке. if _, err := tx.Exec(ctx, ` DELETE FROM idempotency_keys WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4 AND expires_at <= now() `, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil { return nil, mapError(err) } // 2) Резервируем слот. Если параллельная реплика уже вставила — // Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0 // только после того, как конкурент закоммитит или откатится. expiresAt := time.Now().UTC().Add(ttl) tag, err := tx.Exec(ctx, ` INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, response_status, response_body, expires_at) VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (user_id, method, path, key) DO NOTHING `, scope.UserID, scope.Method, scope.Path, scope.Key, requestHash, http.StatusCreated, freshResponse, expiresAt) if err != nil { return nil, mapError(err) } // 3) Слот занят — читаем сохранённый ответ в этой же транзакции. if tag.RowsAffected() == 0 { var ( storedHash []byte storedStatus int storedBody []byte ) err := tx.QueryRow(ctx, ` SELECT request_hash, response_status, response_body FROM idempotency_keys WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4 `, scope.UserID, scope.Method, scope.Path, scope.Key). Scan(&storedHash, &storedStatus, &storedBody) if err != nil { return nil, mapError(err) } if !bytes.Equal(storedHash, requestHash) { return nil, &domain.IdempotencyConflictError{Key: scope.Key} } if err := tx.Commit(ctx); err != nil { return nil, mapError(err) } return &domain.CreateIdempotentResult{ Status: storedStatus, Body: storedBody, Replayed: true, }, nil } // 4) Слот наш — валидируем вложения, вставляем сообщение, линкуем // вложения. Всё в одной транзакции: при ошибке на любом шаге // откатывается и idempotency-ключ, и сообщение, и связи. if err := r.validateAttachments(ctx, tx, fresh.ChatID, fresh.AttachmentIDs); err != nil { return nil, err } if _, err := tx.Exec(ctx, ` INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) `, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil { if foreignKeyViolation(err) { return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID} } if checkViolation(err) { return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"} } return nil, mapError(err) } if err := r.linkAttachments(ctx, tx, fresh.ID, fresh.AttachmentIDs); err != nil { return nil, err } if err := tx.Commit(ctx); err != nil { return nil, mapError(err) } return &domain.CreateIdempotentResult{ Status: http.StatusCreated, Body: freshResponse, Replayed: false, }, nil } func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { scope := "messages:" + chatID var ( afterTime time.Time afterID string hasCursor bool ) if cursor != nil { t, id, err := decodeCursor(*cursor, scope) if err != nil { return nil, nil, err } afterTime = t afterID = id hasCursor = true } var ( rows pgx.Rows err error ) if hasCursor { const q = ` SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1::uuid AND (created_at, id) > ($2, $3::uuid) ORDER BY created_at, id LIMIT $4 ` rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1) } else { const q = ` SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1::uuid ORDER BY created_at, id LIMIT $2 ` rows, err = r.pool.Query(ctx, q, chatID, limit+1) } if err != nil { return nil, nil, err } defer rows.Close() page := make([]domain.Message, 0, limit) for rows.Next() { var m domain.Message if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { return nil, nil, err } page = append(page, m) } if err := rows.Err(); err != nil { return nil, nil, err } var next *string if len(page) > limit { page = page[:limit] last := page[len(page)-1] c := encodeCursor(scope, last.CreatedAt, last.ID) next = &c } if len(page) > 0 { msgIDs := make([]string, len(page)) for i := range page { msgIDs[i] = page[i].ID } links, err := r.loadAttachmentIDs(ctx, msgIDs) if err != nil { return nil, nil, err } for i := range page { if ids, ok := links[page[i].ID]; ok { page[i].AttachmentIDs = ids } else { page[i].AttachmentIDs = []string{} } } } return page, next, nil } func (r *MessageRepo) validateAttachments(ctx context.Context, tx pgx.Tx, chatID string, ids []string) error { if len(ids) == 0 { return nil } const q = `SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])` rows, err := tx.Query(ctx, q, ids) if err != nil { return mapError(err) } defer rows.Close() type info struct { chatID string status domain.AttachmentStatus } found := make(map[string]info, len(ids)) for rows.Next() { var id, chID, st string if err := rows.Scan(&id, &chID, &st); err != nil { return mapError(err) } found[id] = info{chatID: chID, status: domain.AttachmentStatus(st)} } if err := rows.Err(); err != nil { return mapError(err) } for _, id := range ids { a, ok := found[id] if !ok || a.chatID != chatID { return &domain.NotFoundError{Entity: "attachment", ID: id} } if a.status == domain.AttachmentStatusFailed { return &domain.ConflictError{Reason: "вложение " + id + " в состоянии failed"} } } return nil } func (r *MessageRepo) linkAttachments(ctx context.Context, tx pgx.Tx, messageID string, ids []string) error { if len(ids) == 0 { return nil } const q = `INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)` for i, id := range ids { if _, err := tx.Exec(ctx, q, messageID, id, int16(i)); err != nil { if foreignKeyViolation(err) { return &domain.NotFoundError{Entity: "attachment", ID: id} } if uniqueViolation(err) { return &domain.ValidationError{Field: "attachment_ids", Message: "дубликаты запрещены"} } if checkViolation(err) { return &domain.ValidationError{Field: "attachment_ids", Message: "нарушено ограничение"} } return mapError(err) } } return nil } func (r *MessageRepo) loadAttachmentIDs(ctx context.Context, messageIDs []string) (map[string][]string, error) { if len(messageIDs) == 0 { return map[string][]string{}, nil } const q = ` SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY($1::uuid[]) ORDER BY message_id, position ` rows, err := r.pool.Query(ctx, q, messageIDs) if err != nil { return nil, mapError(err) } defer rows.Close() result := make(map[string][]string, len(messageIDs)) for rows.Next() { var msgID, attID string if err := rows.Scan(&msgID, &attID); err != nil { return nil, mapError(err) } result[msgID] = append(result[msgID], attID) } return result, mapError(rows.Err()) } var _ domain.MessageRepository = (*MessageRepo)(nil)