373 lines
14 KiB
Go
373 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
type Chat struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
MemberIDs []string `json:"member_ids"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
type Message struct {
|
|
ID string `json:"id"`
|
|
ChatID string `json:"chat_id"`
|
|
SenderID string `json:"sender_id"`
|
|
Text string `json:"text"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
var (
|
|
errConflict = errors.New("conflict")
|
|
errNotFound = errors.New("not found")
|
|
errInvalidMembers = errors.New("invalid members")
|
|
)
|
|
|
|
// Store — единственный источник истины: PostgreSQL. Все запросы параметризованы ($1, $2, …),
|
|
// строки SQL не собираются из пользовательских данных.
|
|
type Store struct{ pool *pgxpool.Pool }
|
|
|
|
func newPool(ctx context.Context, url string, maxConns int32) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
return nil, errors.New("invalid database URL")
|
|
}
|
|
cfg.MaxConns = maxConns
|
|
cfg.MaxConnLifetime = 30 * time.Minute
|
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
|
cfg.HealthCheckPeriod = 15 * time.Second
|
|
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
|
if cfg.ConnConfig.RuntimeParams == nil {
|
|
cfg.ConnConfig.RuntimeParams = map[string]string{}
|
|
}
|
|
cfg.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
|
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
|
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "10000"
|
|
cfg.ConnConfig.RuntimeParams["application_name"] = "messenger-api"
|
|
// Соединения создаются лениво: API стартует и при недоступной БД (тогда /health/ready даёт 503).
|
|
return pgxpool.NewWithConfig(ctx, cfg)
|
|
}
|
|
|
|
// dbFail переводит ошибку БД в ограниченный ответ: ни SQL, ни адреса, ни текста драйвера клиенту не уходят.
|
|
func dbFail(err error) *apiError {
|
|
var pg *pgconn.PgError
|
|
if errors.As(err, &pg) {
|
|
// 08 — соединение, 53 — ресурсы, 57 — остановка/отмена, 40 — откат по конкуренции.
|
|
switch pg.Code[:2] {
|
|
case "08", "53", "57", "40":
|
|
return unavailable()
|
|
}
|
|
return fail(500, "internal_error", "Внутренняя ошибка")
|
|
}
|
|
// не PgError: обрыв соединения, таймаут, пул исчерпан, БД недоступна
|
|
return unavailable()
|
|
}
|
|
|
|
func isPgCode(err error, code string) bool {
|
|
var pg *pgconn.PgError
|
|
return errors.As(err, &pg) && pg.Code == code
|
|
}
|
|
|
|
// ---- пользователи ----
|
|
|
|
func (s *Store) createUser(ctx context.Context, u User, passwordHash string) (User, error) {
|
|
var created time.Time
|
|
err := s.pool.QueryRow(ctx,
|
|
`INSERT INTO users (id, username, display_name, password_hash) VALUES ($1::uuid, $2, $3, $4) RETURNING created_at`,
|
|
u.ID, u.Username, u.DisplayName, passwordHash).Scan(&created)
|
|
if err != nil {
|
|
if isPgCode(err, "23505") { // unique_violation: username занят, в том числе при гонке
|
|
return User{}, errConflict
|
|
}
|
|
return User{}, err
|
|
}
|
|
u.CreatedAt = formatTime(created)
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) userWithHash(ctx context.Context, username string) (User, string, error) {
|
|
var u User
|
|
var hash string
|
|
var created time.Time
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT id::text, username, display_name, created_at, password_hash FROM users WHERE username = $1`,
|
|
username).Scan(&u.ID, &u.Username, &u.DisplayName, &created, &hash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return User{}, "", errNotFound
|
|
}
|
|
if err != nil {
|
|
return User{}, "", err
|
|
}
|
|
u.CreatedAt = formatTime(created)
|
|
return u, hash, nil
|
|
}
|
|
|
|
// ---- сессии ----
|
|
|
|
func (s *Store) createSession(ctx context.Context, tokenHash []byte, userID string, ttlSecs int) (time.Time, error) {
|
|
// Оппортунистическая чистка давно истёкших строк; индекс по expires_at делает её дешёвой.
|
|
_, _ = s.pool.Exec(ctx, `DELETE FROM sessions WHERE expires_at < now() - interval '1 day'`)
|
|
var expires time.Time
|
|
err := s.pool.QueryRow(ctx,
|
|
`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2::uuid, now() + make_interval(secs => $3::float8)) RETURNING expires_at`,
|
|
tokenHash, userID, float64(ttlSecs)).Scan(&expires)
|
|
return expires, err
|
|
}
|
|
|
|
// sessionUser возвращает владельца действующей (не истёкшей и не отозванной) сессии.
|
|
// Срок проверяется по часам PostgreSQL, поэтому он не зависит от рестарта API.
|
|
func (s *Store) sessionUser(ctx context.Context, tokenHash []byte) (User, error) {
|
|
var u User
|
|
var created time.Time
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT u.id::text, u.username, u.display_name, u.created_at
|
|
FROM sessions s JOIN users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > now()`,
|
|
tokenHash).Scan(&u.ID, &u.Username, &u.DisplayName, &created)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return User{}, errNotFound
|
|
}
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
u.CreatedAt = formatTime(created)
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) revokeSession(ctx context.Context, tokenHash []byte) error {
|
|
_, err := s.pool.Exec(ctx,
|
|
`UPDATE sessions SET revoked_at = now() WHERE token_hash = $1 AND revoked_at IS NULL`, tokenHash)
|
|
return err
|
|
}
|
|
|
|
// ---- чаты ----
|
|
|
|
// createChat — составная операция: чат и ВСЕ участники появляются в одной транзакции.
|
|
// Любая ошибка (например, несуществующий участник → FK) откатывает всё: «половинчатых» чатов не бывает.
|
|
func (s *Store) createChat(ctx context.Context, c Chat, creatorID string) (Chat, error) {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return Chat{}, err
|
|
}
|
|
defer func() { _ = tx.Rollback(context.Background()) }() // no-op после Commit
|
|
|
|
var created time.Time
|
|
if err := tx.QueryRow(ctx,
|
|
`INSERT INTO chats (id, title, created_by) VALUES ($1::uuid, $2, $3::uuid) RETURNING created_at`,
|
|
c.ID, c.Title, creatorID).Scan(&created); err != nil {
|
|
return Chat{}, err
|
|
}
|
|
if _, err := tx.Exec(ctx,
|
|
`INSERT INTO chat_members (chat_id, user_id) SELECT $1::uuid, m::uuid FROM unnest($2::text[]) AS m`,
|
|
c.ID, c.MemberIDs); err != nil {
|
|
if isPgCode(err, "23503") { // foreign_key_violation: неизвестный участник
|
|
return Chat{}, errInvalidMembers
|
|
}
|
|
return Chat{}, err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return Chat{}, err
|
|
}
|
|
c.CreatedAt = formatTime(created)
|
|
return c, nil
|
|
}
|
|
|
|
const chatColumns = `c.id::text, c.title, c.created_at,
|
|
ARRAY(SELECT m2.user_id::text FROM chat_members m2 WHERE m2.chat_id = c.id ORDER BY m2.user_id)`
|
|
|
|
func scanChat(row pgx.Row) (Chat, time.Time, error) {
|
|
var c Chat
|
|
var created time.Time
|
|
if err := row.Scan(&c.ID, &c.Title, &created, &c.MemberIDs); err != nil {
|
|
return Chat{}, time.Time{}, err
|
|
}
|
|
c.CreatedAt = formatTime(created)
|
|
return c, created, nil
|
|
}
|
|
|
|
func (s *Store) getChat(ctx context.Context, actorID, chatID string) (Chat, error) {
|
|
c, _, err := scanChat(s.pool.QueryRow(ctx,
|
|
`SELECT `+chatColumns+` FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $1::uuid WHERE c.id = $2::uuid`,
|
|
actorID, chatID))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return Chat{}, errNotFound
|
|
}
|
|
return c, err
|
|
}
|
|
|
|
func (s *Store) isMember(ctx context.Context, actorID, chatID string) (bool, error) {
|
|
var ok bool
|
|
err := s.pool.QueryRow(ctx,
|
|
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid)`,
|
|
chatID, actorID).Scan(&ok)
|
|
return ok, err
|
|
}
|
|
|
|
// listChats: keyset-пагинация по (created_at, id); запрашивается limit+1 строк, чтобы точно знать, есть ли следующая.
|
|
func (s *Store) listChats(ctx context.Context, actorID string, limit int, after *time.Time, afterID string) ([]Chat, string, error) {
|
|
sql := `SELECT ` + chatColumns + ` FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $1::uuid`
|
|
args := []any{actorID}
|
|
if after != nil {
|
|
sql += ` WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)`
|
|
args = append(args, *after, afterID)
|
|
}
|
|
sql += ` ORDER BY c.created_at, c.id LIMIT ` + placeholder(len(args)+1)
|
|
args = append(args, limit+1)
|
|
rows, err := s.pool.Query(ctx, sql, args...)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
defer rows.Close()
|
|
items := []Chat{}
|
|
var lastTime time.Time
|
|
for rows.Next() {
|
|
c, created, err := scanChat(rows)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if len(items) == limit { // лишняя строка: следующая страница существует
|
|
return items, encodeCursor("chats", actorID, lastTime, items[len(items)-1].ID), rows.Err()
|
|
}
|
|
items = append(items, c)
|
|
lastTime = created
|
|
}
|
|
return items, "", rows.Err()
|
|
}
|
|
|
|
func placeholder(n int) string { return "$" + itoa(n) }
|
|
|
|
// ---- сообщения ----
|
|
|
|
func (s *Store) createMessage(ctx context.Context, m Message) (Message, error) {
|
|
var created time.Time
|
|
err := s.pool.QueryRow(ctx,
|
|
`INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1::uuid, $2::uuid, $3::uuid, $4) RETURNING created_at`,
|
|
m.ID, m.ChatID, m.SenderID, m.Text).Scan(&created)
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
m.CreatedAt = formatTime(created)
|
|
return m, nil
|
|
}
|
|
|
|
// createMessageIdempotent: ключ и сообщение — одна транзакция. Возвращает (сообщение, replayed, ошибка).
|
|
// errConflict — тот же ключ с другим телом. Дубль невозможен: PRIMARY KEY ключа сериализует
|
|
// конкурентные повторы (в том числе с разных реплик), проигравший ждёт коммита победителя.
|
|
func (s *Store) createMessageIdempotent(ctx context.Context, m Message, key, path string, reqHash []byte) (Message, bool, error) {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
defer func() { _ = tx.Rollback(context.Background()) }()
|
|
|
|
// Ключ старше 24 часов считается свободным.
|
|
if _, err := tx.Exec(ctx,
|
|
`DELETE FROM idempotency_keys WHERE user_id = $1::uuid AND method = 'POST' AND path = $2 AND key = $3
|
|
AND created_at < now() - interval '24 hours'`, m.SenderID, path, key); err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
tag, err := tx.Exec(ctx,
|
|
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash) VALUES ($1::uuid, 'POST', $2, $3, $4)
|
|
ON CONFLICT DO NOTHING`, m.SenderID, path, key, reqHash)
|
|
if err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
// Ключ уже занят закоммиченной записью: отдаём сохранённый результат или 409.
|
|
var stored []byte
|
|
var created time.Time
|
|
var prev Message
|
|
err := tx.QueryRow(ctx,
|
|
`SELECT k.request_hash, m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at
|
|
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
|
WHERE k.user_id = $1::uuid AND k.method = 'POST' AND k.path = $2 AND k.key = $3`,
|
|
m.SenderID, path, key).Scan(&stored, &prev.ID, &prev.ChatID, &prev.SenderID, &prev.Text, &created)
|
|
if err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
if !bytes.Equal(stored, reqHash) {
|
|
return Message{}, false, errConflict
|
|
}
|
|
prev.CreatedAt = formatTime(created)
|
|
return prev, true, nil
|
|
}
|
|
var created time.Time
|
|
if err := tx.QueryRow(ctx,
|
|
`INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1::uuid, $2::uuid, $3::uuid, $4) RETURNING created_at`,
|
|
m.ID, m.ChatID, m.SenderID, m.Text).Scan(&created); err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
if _, err := tx.Exec(ctx,
|
|
`UPDATE idempotency_keys SET message_id = $4::uuid WHERE user_id = $1::uuid AND method = 'POST' AND path = $2 AND key = $3`,
|
|
m.SenderID, path, key, m.ID); err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return Message{}, false, err
|
|
}
|
|
m.CreatedAt = formatTime(created)
|
|
return m, false, nil
|
|
}
|
|
|
|
func (s *Store) listMessages(ctx context.Context, chatID string, limit int, after *time.Time, afterID string) ([]Message, string, error) {
|
|
sql := `SELECT id::text, chat_id::text, sender_id::text, text, created_at FROM messages WHERE chat_id = $1::uuid`
|
|
args := []any{chatID}
|
|
if after != nil {
|
|
sql += ` AND (created_at, id) > ($2::timestamptz, $3::uuid)`
|
|
args = append(args, *after, afterID)
|
|
}
|
|
sql += ` ORDER BY created_at, id LIMIT ` + placeholder(len(args)+1)
|
|
args = append(args, limit+1)
|
|
rows, err := s.pool.Query(ctx, sql, args...)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
defer rows.Close()
|
|
items := []Message{}
|
|
var lastTime time.Time
|
|
for rows.Next() {
|
|
var m Message
|
|
var created time.Time
|
|
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created); err != nil {
|
|
return nil, "", err
|
|
}
|
|
if len(items) == limit {
|
|
return items, encodeCursor("messages", chatID, lastTime, items[len(items)-1].ID), rows.Err()
|
|
}
|
|
m.CreatedAt = formatTime(created)
|
|
items = append(items, m)
|
|
lastTime = created
|
|
}
|
|
return items, "", rows.Err()
|
|
}
|
|
|
|
// ready: БД отвечает и схема доведена до последней миграции.
|
|
func (s *Store) ready(ctx context.Context) error {
|
|
versions := migrationVersions()
|
|
var n int
|
|
if err := s.pool.QueryRow(ctx,
|
|
`SELECT count(*) FROM schema_migrations WHERE version = ANY($1::text[])`, versions).Scan(&n); err != nil {
|
|
return err
|
|
}
|
|
if n != len(versions) {
|
|
return errors.New("schema is not up to date")
|
|
}
|
|
return nil
|
|
}
|