Реализовать lab3: HAProxy, API×N, идемпотентность и трек 1.
Горизонтальное масштабирование за LB с общими сессиями Redis, X-Instance-Id, обязательным Idempotency-Key в PostgreSQL, сценариями failover/persistence и измерением цены масштабирования при фиксированном CPU/RAM бюджете.
This commit is contained in:
@@ -0,0 +1,641 @@
|
||||
// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL.
|
||||
//
|
||||
// Источник истины — только эти таблицы. Память процесса после рестарта пуста,
|
||||
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||
// текст сообщения не склеивается в SQL.
|
||||
//
|
||||
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab3/internal/auth"
|
||||
)
|
||||
|
||||
const queryTimeout = 3 * time.Second
|
||||
|
||||
// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL.
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
// ErrIdempotencyConflict — тот же ключ, но другое тело запроса.
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
)
|
||||
|
||||
// User — публичные поля пользователя. Hash пароля в эту структуру не попадает.
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — чат и явный состав участников.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
type PageCursor struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
Scope string
|
||||
}
|
||||
|
||||
// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
hasher *auth.Hasher
|
||||
}
|
||||
|
||||
// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503,
|
||||
// а не висела до клиентского таймаута теста.
|
||||
// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns.
|
||||
func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) {
|
||||
if maxConns < 1 {
|
||||
maxConns = 5
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
// UTC, чтобы timestamptz читался так же, как мы его записали.
|
||||
// statement_timeout обрывает запрос, который внезапно решил сканировать всё.
|
||||
_, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`)
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, hasher: hasher}, nil
|
||||
}
|
||||
|
||||
// Close освобождает соединения при остановке процесса.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := auth.Hash(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль
|
||||
// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет».
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
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) {
|
||||
s.hasher.Burn(password)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if !s.hasher.Verify(hash, password) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации.
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
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, mapWriteErr(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё:
|
||||
// в таблице chats не остаётся «пустой» строки без полного состава.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
chat := &Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
for _, uid := range memberIDs {
|
||||
// INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK.
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403).
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.loadChat(ctx, chatID)
|
||||
}
|
||||
|
||||
// ListChats — keyset по (created_at, id) только среди чатов этого пользователя.
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
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 {
|
||||
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, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Chat
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) {
|
||||
return c.CreatedAt, c.ID
|
||||
})
|
||||
for i := range items {
|
||||
members, err := s.memberIDs(ctx, items[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
items[i].MemberIDs = members
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if next {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// CreateMessage пишет сообщение только если отправитель состоит в чате.
|
||||
// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории.
|
||||
// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||
)`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение.
|
||||
type IdempotentMessage struct {
|
||||
Message *Message
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе INSERT message + INSERT idempotency_keys в той же транзакции;
|
||||
// 5. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID uuid.UUID,
|
||||
text string,
|
||||
method, path, idemKey, requestHash string,
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
lockKey := idempotencyLockKey(senderID, method, path, idemKey)
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash string
|
||||
msgID uuid.UUID
|
||||
msgChat uuid.UUID
|
||||
msgSender uuid.UUID
|
||||
msgText string
|
||||
msgCreated time.Time
|
||||
)
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
senderID, method, path, idemKey,
|
||||
).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated)
|
||||
if err == nil {
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{
|
||||
Message: &Message{
|
||||
ID: msgID,
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
CreatedAt: msgCreated,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// response_body заполняем каноническим Message JSON уже здесь, чтобы replay
|
||||
// не зависел от повторной сериализации в HTTP-слое с другим порядком полей.
|
||||
bodyJSON, err := json.Marshal(map[string]any{
|
||||
"id": msg.ID.String(),
|
||||
"chat_id": msg.ChatID.String(),
|
||||
"sender_id": msg.SenderID.String(),
|
||||
"text": msg.Text,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys (
|
||||
user_id, method, path, key, request_hash,
|
||||
response_status, response_body, message_id, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
senderID, method, path, idemKey, requestHash,
|
||||
201, bodyJSON, msg.ID, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{Message: msg, Replayed: false}, nil
|
||||
}
|
||||
|
||||
// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа.
|
||||
func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 {
|
||||
sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key))
|
||||
return int64(binary.BigEndian.Uint64(sum[:8]))
|
||||
}
|
||||
|
||||
// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку,
|
||||
// чтобы next_cursor был null, когда следующей записи уже нет.
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(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); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет.
|
||||
func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n)
|
||||
if err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var one int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
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, mapWriteErr(err)
|
||||
}
|
||||
c.MemberIDs, err = s.memberIDs(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) {
|
||||
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, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []uuid.UUID
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) {
|
||||
if len(items) > limit {
|
||||
return true, items[:limit]
|
||||
}
|
||||
return false, items
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
// Миллисекунда — точность, которую мы же и печатаем в JSON.
|
||||
return time.Now().UTC().Truncate(time.Millisecond)
|
||||
}
|
||||
|
||||
func mapWriteErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrConflict
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || isConn(err) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isConn(err error) bool {
|
||||
msg := err.Error()
|
||||
// Не логируем и не возвращаем клиенту эту строку. Здесь только классификация.
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return false
|
||||
default:
|
||||
if stringsContains(msg, "connection refused") ||
|
||||
stringsContains(msg, "failed to connect") ||
|
||||
stringsContains(msg, "conn closed") ||
|
||||
stringsContains(msg, "closed pool") ||
|
||||
stringsContains(msg, "broken pipe") ||
|
||||
stringsContains(msg, "connection reset") ||
|
||||
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||
stringsContains(msg, "SQLSTATE 08006") ||
|
||||
stringsContains(msg, "SQLSTATE 08001") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stringsContains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||
(func() bool { return contains(s, sub) })())
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user