Files
mtusi2026lab3/internal/store/store.go
T

632 lines
21 KiB
Go

// Package store is the PostgreSQL repository. Every statement uses positional
// parameters; identifiers are never interpolated into SQL. The pool is
// bounded and every operation carries a context timeout.
package store
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/puddle/v2"
"mtusi.ru/messenger-lab3/internal/cursor"
"mtusi.ru/messenger-lab3/internal/model"
"mtusi.ru/messenger-lab3/internal/uuid"
)
// Domain errors. The HTTP layer maps them to the contract's status codes.
var (
ErrNotFound = errors.New("object not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("unknown chat member")
ErrUnavailable = errors.New("database unavailable")
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
)
// Options bounds the pool and every query. Zero values fall back to safe
// defaults so the store is still testable from small programs.
type Options struct {
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
StatementTimeout time.Duration
QueryTimeout time.Duration
}
// Store owns a bounded pgx pool.
type Store struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
// Open parses the DSN and creates the pool. Parse errors deliberately do not
// echo the DSN: it contains the database password.
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
}
applyDefaults(&options)
config.MaxConns = options.MaxConns
config.MinConns = options.MinConns
config.MaxConnLifetime = 30 * time.Minute
config.MaxConnIdleTime = 5 * time.Minute
config.HealthCheckPeriod = 30 * time.Second
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab3"
// A statement timeout in the server session is the last line of defence
// against a runaway query; the caller's context is the first.
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
}
func applyDefaults(options *Options) {
if options.MaxConns <= 0 {
options.MaxConns = 8
}
if options.MinConns < 0 {
options.MinConns = 0
}
if options.MinConns > options.MaxConns {
options.MinConns = options.MaxConns
}
if options.ConnectTimeout <= 0 {
options.ConnectTimeout = 3 * time.Second
}
if options.StatementTimeout <= 0 {
options.StatementTimeout = 3 * time.Second
}
if options.QueryTimeout <= 0 {
options.QueryTimeout = 3 * time.Second
}
}
// Ping is used by /health/ready and by the startup readiness loop.
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
// Close waits for in-flight queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, s.queryTimeout)
}
// classify separates a dependency outage (contract 503 unavailable) from a
// genuine application bug (500 internal_error). Only the error class is mapped;
// the original error is logged server-side and never sent to a client.
func (s *Store) classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
pgErr.Code == "57P01", // admin shutdown
pgErr.Code == "57P02", // crash shutdown
pgErr.Code == "57P03", // cannot connect now
pgErr.Code == "57014", // query cancelled (statement_timeout)
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
// CreateUser inserts a user and relies on the unique index for both ordinary
// duplicates and concurrent registrations of the same username.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
RETURNING created_at`,
id, username, displayName, passwordHash, createdAt,
).Scan(&stored)
if err != nil {
if isUniqueViolation(err) {
return model.User{}, ErrUsernameTaken
}
return model.User{}, s.classify(err)
}
return model.User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// UserByUsername returns the public user and the Argon2id hash. The hash is
// used only by the login handler and is never serialised.
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var passwordHash string
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username,
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, "", ErrNotFound
}
return model.User{}, "", s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, passwordHash, nil
}
// UserByID resolves the identity stored in a server-side session.
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, created_at
FROM users WHERE id = $1::uuid`, id,
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
return model.User{}, s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, nil
}
// CreateChat inserts the chat and its membership in one transaction. A caller
// cannot observe a chat without members: either both are committed or neither.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var existing int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM users
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
).Scan(&existing); err != nil {
return model.Chat{}, s.classify(err)
}
if existing != len(memberIDs) {
return model.Chat{}, ErrUnknownMember
}
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
RETURNING created_at`, id, title, createdAt,
).Scan(&stored); err != nil {
return model.Chat{}, s.classify(err)
}
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
id, memberID, position)
}
results := tx.SendBatch(ctx, batch)
for range memberIDs {
if _, err := results.Exec(); err != nil {
_ = results.Close()
if isForeignKeyViolation(err) {
return model.Chat{}, ErrUnknownMember
}
return model.Chat{}, s.classify(err)
}
}
if err := results.Close(); err != nil {
return model.Chat{}, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, s.classify(err)
}
return model.Chat{
ID: id,
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// IsChatMember is used before parsing query parameters so a foreign chat is
// always 404, independent of the submitted cursor or limit.
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var member bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
)`, chatID, userID).Scan(&member)
if err != nil {
return false, s.classify(err)
}
return member, nil
}
// ChatForUser returns a chat only when the user is a member. A missing chat and
// a foreign chat are indistinguishable to the caller.
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1::uuid
GROUP BY c.id`, chatID, userID,
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
return model.Chat{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
return chat, nil
}
const chatsPageSelect = `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
JOIN chat_members cm ON cm.chat_id = c.id`
// Chats returns one keyset page of chats visible to the user.
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := chatsPageSelect + `
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $2`
args := []any{userID, limit + 1}
if position != nil {
query = chatsPageSelect + `
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4`
args = []any{userID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.ChatPage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return model.ChatPage{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return model.ChatPage{}, s.classify(err)
}
page := model.ChatPage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForChat(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
// only by the operator-only metrics listener, never by the public API.
type PoolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
// Count is the number of calls that had to wait for a free connection; a fast
// rising value while the API CPU is below its limit points at the database or
// the pool size, not at the HTTP layer.
func (s *Store) PoolStats() PoolStats {
stat := s.pool.Stat()
return PoolStats{
MaxConns: stat.MaxConns(),
TotalConns: stat.TotalConns(),
AcquiredConns: stat.AcquiredConns(),
IdleConns: stat.IdleConns(),
EmptyAcquireCount: stat.EmptyAcquireCount(),
CanceledAcquireCount: stat.CanceledAcquireCount(),
AcquireCount: stat.AcquireCount(),
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
NewConnsCount: stat.NewConnsCount(),
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
}
}
// CreateMessage appends a message. The composite foreign key also guarantees
// that the sender belongs to the chat at the database level.
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
}
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, time.Now().UTC(),
).Scan(&createdAt)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, ErrNotFound
}
return model.Message{}, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return message, nil
}
// CreateMessageIdempotent appends a message and records the idempotency
// result in one transaction. It is the lab3 replacement for CreateMessage on
// the public POST path.
//
// Behavior derived from contracts/README.md:
// - a new (user, method, path, key) creates a message and its record, 201;
// - the same semantic body replays the stored message, 201, exactly once;
// - a different body with the same key is a conflict, 409;
// - a transient failure rolls both statements back, so the client may
// safely retry the same key and never observe a duplicate side effect.
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string) (model.Message, bool, error) {
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
}
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, false, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var createdAt time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, time.Now().UTC(),
).Scan(&createdAt); err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(err)
}
tag, err := tx.Exec(ctx, `
INSERT INTO message_idempotency
(user_id, method, path, key, request_hash, message_id, created_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)
ON CONFLICT (user_id, method, path, key) DO NOTHING`,
senderID, method, path, key, requestHash, message.ID, time.Now().UTC(),
)
if err != nil {
return model.Message{}, false, s.classify(err)
}
if tag.RowsAffected() == 1 {
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return message, false, nil
}
// Another transaction owns this key. Roll back this speculative message,
// then read the committed record. A concurrent insert waits on the unique
// index inside Exec above, so the conflicting row is already committed
// when RowsAffected reports zero.
_ = tx.Rollback(context.Background())
storedHash, storedMessage, found, err := s.replayIdempotent(ctx, senderID, method, path, key)
if err != nil {
return model.Message{}, false, err
}
if !found {
// The conflicting row disappeared between the conflict and this read
// (only a retention prune can do that). Report a bounded transient
// error; no message was committed and the same key is safe to retry.
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
}
if !bytes.Equal(storedHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
return storedMessage, true, nil
}
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
var storedHash []byte
var message model.Message
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT i.request_hash, m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
userID, method, path, key,
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, model.Message{}, false, nil
}
return nil, model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return storedHash, message, true, nil
}
// PruneIdempotency removes records older than the contract's minimum
// retention. It runs opportunistically from every replica; the statement is
// safe to execute concurrently and is bounded to keep one delete short.
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx, `
DELETE FROM message_idempotency
WHERE ctid IN (
SELECT ctid FROM message_idempotency
WHERE created_at < now() - $1::interval
LIMIT 500
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
if err != nil {
return 0, s.classify(err)
}
return tag.RowsAffected(), nil
}
const messagesPageSelect = `
SELECT id::text, chat_id::text, sender_id::text, text, created_at
FROM messages
WHERE chat_id = $1::uuid`
// Messages returns one keyset page of a chat history. The caller has already
// verified membership; the query itself never loads the whole history.
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := messagesPageSelect + `
ORDER BY created_at, messages.id
LIMIT $2`
args := []any{chatID, limit + 1}
if position != nil {
query = messagesPageSelect + `
AND (created_at, messages.id) > ($2::timestamptz, $3::uuid)
ORDER BY created_at, messages.id
LIMIT $4`
args = []any{chatID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.MessagePage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil {
return model.MessagePage{}, s.classify(err)
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return model.MessagePage{}, s.classify(err)
}
page := model.MessagePage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForMessage(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}