609 lines
18 KiB
Go
609 lines
18 KiB
Go
package domain
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewStore(ctx context.Context, dsn string) (*Store, error) {
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
cfg.MaxConns = 10
|
|
cfg.MinConns = 1
|
|
cfg.MaxConnLifetime = time.Hour
|
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
|
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
|
|
|
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
|
_, err := conn.Exec(ctx, `
|
|
SET statement_timeout = '5s';
|
|
SET lock_timeout = '2s';
|
|
SET idle_in_transaction_session_timeout = '5s';
|
|
`)
|
|
return err
|
|
}
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(ctxPing); err != nil {
|
|
pool.Close()
|
|
return nil, classifyDBError(err)
|
|
}
|
|
return &Store{pool: pool}, nil
|
|
}
|
|
|
|
func (s *Store) Close() { s.pool.Close() }
|
|
|
|
func (s *Store) Ping(ctx context.Context) error {
|
|
c, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
defer cancel()
|
|
return s.pool.Ping(c)
|
|
}
|
|
|
|
// Argon2id параметры — OWASP baseline: m=19456 KiB (19 MiB), t=2, p=1.
|
|
// Хеш кодируется в формате PHC: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
|
|
const (
|
|
argonMemory uint32 = 19456
|
|
argonTime uint32 = 2
|
|
argonThreads uint8 = 1
|
|
argonKeyLen uint32 = 32
|
|
argonSaltLen = 16
|
|
)
|
|
|
|
func hashPassword(password string) (string, error) {
|
|
salt := make([]byte, argonSaltLen)
|
|
if _, err := rand.Read(salt); err != nil {
|
|
return "", err
|
|
}
|
|
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
|
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
|
|
b64Key := base64.RawStdEncoding.EncodeToString(key)
|
|
// PHC string; параметры можно будет менять в будущем, старые хеши останутся валидными.
|
|
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
|
argonMemory, argonTime, argonThreads, b64Salt, b64Key), nil
|
|
}
|
|
|
|
func verifyPassword(password, encoded string) bool {
|
|
// Минимальный парсер PHC-строки.
|
|
parts := strings.Split(encoded, "$")
|
|
if len(parts) != 6 || parts[1] != "argon2id" {
|
|
return false
|
|
}
|
|
var mem, time uint32
|
|
var threads uint8
|
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &time, &threads); err != nil {
|
|
return false
|
|
}
|
|
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
gotKey := argon2.IDKey([]byte(password), salt, time, mem, threads, uint32(len(wantKey)))
|
|
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1
|
|
}
|
|
|
|
// --- Users ---
|
|
|
|
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
|
hash, err := hashPassword(password)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
id := uuid.NewString()
|
|
var u User
|
|
err = s.pool.QueryRow(ctx,
|
|
`INSERT INTO users (id, username, display_name, password_hash)
|
|
VALUES ($1,$2,$3,$4)
|
|
RETURNING id, username, display_name, created_at`,
|
|
id, username, displayName, string(hash),
|
|
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, ErrConflict
|
|
}
|
|
return nil, classifyDBError(err)
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
|
|
var u User
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT id, username, display_name, created_at FROM users WHERE id=$1`, id,
|
|
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
// VerifyPassword возвращает пользователя, если пароль верный; иначе ErrUnauthorized.
|
|
func (s *Store) VerifyPassword(ctx context.Context, username, password string) (*User, error) {
|
|
var u User
|
|
var hash string
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username=$1`,
|
|
username,
|
|
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
// Тратим сопоставимое время на проверку фиктивного хеша,
|
|
// чтобы не различать "нет пользователя" и "неверный пароль" по таймингу.
|
|
_ = verifyPassword(password, "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
|
|
return nil, ErrUnauthorized
|
|
}
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
if !verifyPassword(password, hash) {
|
|
return nil, ErrUnauthorized
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
// --- Chats ---
|
|
|
|
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, creatorID string) (*Chat, error) {
|
|
// Проверка входных данных.
|
|
seen := map[string]bool{}
|
|
for _, id := range memberIDs {
|
|
if seen[id] {
|
|
return nil, ErrInvalid
|
|
}
|
|
seen[id] = true
|
|
}
|
|
if !seen[creatorID] {
|
|
return nil, ErrInvalid
|
|
}
|
|
|
|
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
// Проверяем, что все участники существуют.
|
|
for id := range seen {
|
|
var exists bool
|
|
if err := tx.QueryRow(ctx, `SELECT true FROM users WHERE id=$1`, id).Scan(&exists); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrInvalid
|
|
}
|
|
return nil, classifyDBError(err)
|
|
}
|
|
}
|
|
|
|
chatID := uuid.NewString()
|
|
var c Chat
|
|
err = tx.QueryRow(ctx,
|
|
`INSERT INTO chats (id, title) VALUES ($1,$2) RETURNING id, title, created_at`,
|
|
chatID, title,
|
|
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
|
|
for id := range seen {
|
|
if _, err := tx.Exec(ctx,
|
|
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2)`,
|
|
c.ID, id,
|
|
); err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
|
|
// Порядок member_ids — как в запросе.
|
|
c.MemberIDs = append([]string(nil), memberIDs...)
|
|
return &c, nil
|
|
}
|
|
|
|
func (s *Store) GetChat(ctx context.Context, chatID, userID string) (*Chat, error) {
|
|
var exists bool
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
|
chatID, userID,
|
|
).Scan(&exists)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
|
|
var c Chat
|
|
err = s.pool.QueryRow(ctx,
|
|
`SELECT id, title, created_at FROM chats WHERE id=$1`, chatID,
|
|
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
|
|
rows, err := s.pool.Query(ctx,
|
|
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chatID)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var uid string
|
|
if err := rows.Scan(&uid); err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
c.MemberIDs = append(c.MemberIDs, uid)
|
|
}
|
|
return &c, rows.Err()
|
|
}
|
|
|
|
// ListChats возвращает чаты пользователя с keyset-пагинацией по (created_at, id).
|
|
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cursor string) ([]Chat, *string, error) {
|
|
var rows pgx.Rows
|
|
var err error
|
|
|
|
if cursor == "" {
|
|
rows, err = s.pool.Query(ctx,
|
|
`SELECT c.id, c.title, c.created_at
|
|
FROM chats c
|
|
JOIN chat_members m ON m.chat_id = c.id
|
|
WHERE m.user_id = $1
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT $2`, userID, limit+1)
|
|
} else {
|
|
var cCreated time.Time
|
|
if err := s.pool.QueryRow(ctx,
|
|
`SELECT created_at FROM chats WHERE id=$1`, cursor,
|
|
).Scan(&cCreated); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil, ErrInvalid
|
|
}
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
rows, err = s.pool.Query(ctx,
|
|
`SELECT c.id, c.title, c.created_at
|
|
FROM chats c
|
|
JOIN chat_members m ON m.chat_id = c.id
|
|
WHERE m.user_id = $1
|
|
AND (c.created_at, c.id) > ($2, $3)
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT $4`, userID, cCreated, cursor, limit+1)
|
|
}
|
|
if err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var chats []Chat
|
|
for rows.Next() {
|
|
var c Chat
|
|
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
chats = append(chats, c)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
|
|
var next *string
|
|
if len(chats) > limit {
|
|
chats = chats[:limit]
|
|
last := chats[len(chats)-1].ID
|
|
next = &last
|
|
}
|
|
if chats == nil {
|
|
chats = []Chat{}
|
|
}
|
|
|
|
// Догружаем участников.
|
|
for i := range chats {
|
|
mrows, err := s.pool.Query(ctx,
|
|
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chats[i].ID)
|
|
if err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
for mrows.Next() {
|
|
var uid string
|
|
if err := mrows.Scan(&uid); err != nil {
|
|
mrows.Close()
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
chats[i].MemberIDs = append(chats[i].MemberIDs, uid)
|
|
}
|
|
mrows.Close()
|
|
}
|
|
return chats, next, nil
|
|
}
|
|
|
|
// --- Messages ---
|
|
|
|
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (*Message, error) {
|
|
// Проверка членства + вставка в одной транзакции.
|
|
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
var ok bool
|
|
if err := tx.QueryRow(ctx,
|
|
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
|
chatID, senderID,
|
|
).Scan(&ok); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, classifyDBError(err)
|
|
}
|
|
|
|
var m Message
|
|
var attach []string
|
|
err = tx.QueryRow(ctx,
|
|
`INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
|
|
VALUES ($1,$2,$3,$4,$5)
|
|
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids`,
|
|
uuid.NewString(), chatID, senderID, text, []string{},
|
|
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &attach)
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
m.AttachmentIDs = attach
|
|
if m.AttachmentIDs == nil {
|
|
m.AttachmentIDs = []string{}
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// ListMessages — keyset-пагинация по (created_at, id).
|
|
// Курсор — это id последнего элемента предыдущей страницы; сам id уникален,
|
|
// поэтому используем его для поиска (created_at, id) в БД.
|
|
func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, cursor string) ([]Message, *string, error) {
|
|
var rows pgx.Rows
|
|
var err error
|
|
|
|
if cursor == "" {
|
|
rows, err = s.pool.Query(ctx,
|
|
`SELECT id, chat_id, sender_id, text, created_at, attachment_ids
|
|
FROM messages
|
|
WHERE chat_id=$1
|
|
ORDER BY created_at, id
|
|
LIMIT $2`, chatID, limit+1)
|
|
} else {
|
|
// Определяем позицию курсора.
|
|
var cCreated time.Time
|
|
if err := s.pool.QueryRow(ctx,
|
|
`SELECT created_at FROM messages WHERE id=$1 AND chat_id=$2`,
|
|
cursor, chatID,
|
|
).Scan(&cCreated); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil, ErrInvalid
|
|
}
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
rows, err = s.pool.Query(ctx,
|
|
`SELECT id, chat_id, sender_id, text, created_at, attachment_ids
|
|
FROM messages
|
|
WHERE chat_id=$1
|
|
AND (created_at, id) > ($2, $3)
|
|
ORDER BY created_at, id
|
|
LIMIT $4`, chatID, cCreated, cursor, limit+1)
|
|
}
|
|
if err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var items []Message
|
|
for rows.Next() {
|
|
var m Message
|
|
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
if m.AttachmentIDs == nil {
|
|
m.AttachmentIDs = []string{}
|
|
}
|
|
items = append(items, m)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, nil, classifyDBError(err)
|
|
}
|
|
|
|
var next *string
|
|
if len(items) > limit {
|
|
items = items[:limit]
|
|
last := items[len(items)-1].ID
|
|
next = &last
|
|
}
|
|
if items == nil {
|
|
items = []Message{}
|
|
}
|
|
return items, next, nil
|
|
}
|
|
|
|
func classifyDBError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
switch pgErr.Code {
|
|
case "57014": // query_canceled (statement_timeout)
|
|
return ErrTimeout
|
|
case "55P03": // lock_not_available (lock_timeout)
|
|
return ErrTimeout
|
|
case "40001": // serialization_failure
|
|
return ErrUnavailable
|
|
case "53300": // too_many_connections
|
|
return ErrUnavailable
|
|
case "22P02", "22007", "22023": // invalid_text_representation / invalid_datetime_format / invalid_parameter_value
|
|
return ErrInvalid
|
|
}
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
|
return ErrTimeout
|
|
}
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrNotFound
|
|
}
|
|
return err
|
|
}
|
|
|
|
// AddMessageIdempotent — атомарно проверяет членство, вставляет сообщение
|
|
// и сохраняет результат идемпотентности в одной транзакции.
|
|
// Если ключ уже есть с тем же body — возвращает сохранённый ответ и replay=true.
|
|
func (s *Store) AddMessageIdempotent(
|
|
ctx context.Context,
|
|
chatID, senderID, text string,
|
|
attachmentIDs []string,
|
|
key, bodyHash string,
|
|
) (msg *Message, rec *IdempotencyRecord, replay bool, err error) {
|
|
path := "/api/v1/chats/" + chatID + "/messages"
|
|
|
|
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
|
|
if err != nil {
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
// 1) Членство.
|
|
var ok bool
|
|
if err := tx.QueryRow(ctx,
|
|
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
|
chatID, senderID,
|
|
).Scan(&ok); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil, false, ErrNotFound
|
|
}
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
|
|
// Вложения должны принадлежать этому чату и быть ready.
|
|
if len(attachmentIDs) > 10 {
|
|
return nil, nil, false, ErrInvalid
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, aid := range attachmentIDs {
|
|
if seen[aid] {
|
|
return nil, nil, false, ErrInvalid
|
|
}
|
|
seen[aid] = true
|
|
var ok bool
|
|
if err := tx.QueryRow(ctx,
|
|
`SELECT true FROM attachments WHERE id=$1 AND chat_id=$2 AND status='ready'`,
|
|
aid, chatID).Scan(&ok); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil, false, ErrNotFound
|
|
}
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
}
|
|
|
|
// 2) Уже был такой ключ?
|
|
var storedHash string
|
|
var storedStatus int
|
|
var storedResp json.RawMessage
|
|
err = tx.QueryRow(ctx,
|
|
`SELECT request_hash, status_code, response
|
|
FROM idempotency_keys
|
|
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
|
senderID, path, key,
|
|
).Scan(&storedHash, &storedStatus, &storedResp)
|
|
switch {
|
|
case err == nil:
|
|
if storedHash != bodyHash {
|
|
return nil, nil, false, ErrConflict
|
|
}
|
|
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
|
case !errors.Is(err, pgx.ErrNoRows):
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
|
|
// 3) Вставка сообщения.
|
|
var m Message
|
|
var attach []string
|
|
err = tx.QueryRow(ctx,
|
|
`INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
|
|
VALUES ($1,$2,$3,$4,$5)
|
|
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids`,
|
|
uuid.NewString(), chatID, senderID, text, attachmentIDs,
|
|
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &attach)
|
|
if err != nil {
|
|
// Гонка на одном ключе в разных репликах: unique violation в idempotency_keys
|
|
// маловероятен здесь, но serialization failure возможен.
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
m.AttachmentIDs = attach
|
|
if m.AttachmentIDs == nil {
|
|
m.AttachmentIDs = []string{}
|
|
}
|
|
|
|
// 4) Сохранение ответа.
|
|
respJSON, _ := json.Marshal(m)
|
|
_, err = tx.Exec(ctx,
|
|
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
|
|
VALUES ($1,'POST',$2,$3,$4,201,$5)`,
|
|
senderID, path, key, bodyHash, respJSON)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
// Кто-то параллельно успел вставить: перечитываем в этой же tx.
|
|
if err2 := tx.QueryRow(ctx,
|
|
`SELECT request_hash, status_code, response
|
|
FROM idempotency_keys
|
|
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
|
senderID, path, key,
|
|
).Scan(&storedHash, &storedStatus, &storedResp); err2 == nil {
|
|
if storedHash != bodyHash {
|
|
return nil, nil, false, ErrConflict
|
|
}
|
|
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
|
}
|
|
}
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, nil, false, classifyDBError(err)
|
|
}
|
|
return &m, nil, false, nil
|
|
}
|