import lab3 files
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
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 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) Слот наш — вставляем сообщение в той же транзакции.
|
||||
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 := 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
|
||||
}
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
Reference in New Issue
Block a user