Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages

This commit is contained in:
Ivan Melnikov
2026-12-02 18:22:57 +03:00
parent 0ab3a341aa
commit e9bf138053
474 changed files with 206416 additions and 16 deletions
+139
View File
@@ -0,0 +1,139 @@
package store
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
// concurrent API replicas that start at the same time; it is released when the
// dedicated connection is returned or the session ends.
const advisoryLockKey int64 = 0x6d74756c616233 // "mtulab3"
type migration struct {
version int
name string
checksum string
sql string
}
// Migrate applies every embedded migration exactly once and records its
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
// A changed migration file is a startup error rather than a silent divergence.
func (s *Store) Migrate(ctx context.Context) error {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return s.classify(err)
}
defer conn.Release()
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
return s.classify(err)
}
defer func() {
// Use a background context: the request context may already be
// cancelled when a startup timeout fires, but the lock still has to be
// released explicitly before the connection is returned to the pool.
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
}()
if _, err := conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
name text NOT NULL,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return s.classify(err)
}
migrations, err := loadMigrations()
if err != nil {
return err
}
for _, item := range migrations {
var existing string
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
switch {
case err == nil:
if existing != item.checksum {
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
}
continue
case !errors.Is(err, pgx.ErrNoRows):
return s.classify(err)
}
tx, err := conn.Begin(ctx)
if err != nil {
return s.classify(err)
}
if _, err := tx.Exec(ctx, item.sql); err != nil {
_ = tx.Rollback(context.Background())
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
}
if _, err := tx.Exec(ctx,
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
item.version, item.name, item.checksum,
); err != nil {
_ = tx.Rollback(context.Background())
return s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return s.classify(err)
}
}
return nil
}
func loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return nil, err
}
items := make([]migration, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
if len(name) < 9 {
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
}
version, err := strconv.Atoi(name[:4])
if err != nil {
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
}
data, err := migrationFiles.ReadFile("migrations/" + name)
if err != nil {
return nil, err
}
sum := sha256.Sum256(data)
items = append(items, migration{
version: version,
name: strings.TrimSuffix(name[5:], ".sql"),
checksum: hex.EncodeToString(sum[:]),
sql: string(data),
})
}
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
for i := 1; i < len(items); i++ {
if items[i].version == items[i-1].version {
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
}
}
return items, nil
}
+64
View File
@@ -0,0 +1,64 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 3 {
t.Fatalf("loaded %d migrations, want 3", len(migrations))
}
if migrations[0].version != 1 || migrations[1].version != 2 || migrations[2].version != 3 {
t.Fatalf("migration order = %d,%d,%d", migrations[0].version, migrations[1].version, migrations[2].version)
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
if !strings.Contains(strings.ToLower(item.sql), "create ") {
t.Fatalf("migration %d has no schema statements", item.version)
}
}
// The checksum must be stable across process runs: it is what detects an
// edited migration after it has been applied.
again, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
for index := range migrations {
if migrations[index].checksum != again[index].checksum {
t.Fatal("migration checksums are not deterministic")
}
}
}
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
all := ""
for _, item := range migrations {
all += item.sql
}
for _, required := range []string{
"CREATE TABLE users",
"CREATE TABLE chats",
"CREATE TABLE chat_members",
"CREATE TABLE messages",
"CREATE UNIQUE INDEX users_username_key",
"messages_sender_membership_fk",
"messages_chat_created_id_idx",
"CREATE TABLE message_idempotency",
"PRIMARY KEY (user_id, method, path, key)",
} {
if !strings.Contains(all, required) {
t.Fatalf("migrations do not contain %q", required)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_format
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 100),
CONSTRAINT users_password_hash_present
CHECK (length(password_hash) > 0)
);
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
-- two concurrent registrations of the same username cannot both succeed.
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_length
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
-- "Chats of the current user" walks chat_members by user_id.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
-- The sender must be a member of the chat at the database level too, not
-- only in the HTTP handler.
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,15 @@
-- Indexes justified by the two keyset queries of the contract.
--
-- Message history:
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- The three-column index lets PostgreSQL start at the cursor position inside
-- one chat instead of scanning the whole history for every page.
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
-- Chat list:
-- ORDER BY created_at, id LIMIT $1
-- after joining chat_members for the current user.
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
@@ -0,0 +1,28 @@
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
--
-- The primary key is exactly the contract scope: acting user + HTTP method +
-- chat message path + Idempotency-Key. Different users or chats may reuse the
-- same key independently. request_hash lets a replay distinguish the same
-- semantic body (201 + original message) from a different body (409).
--
-- A row is written in the same transaction as the message it references, so a
-- committed row always has a committed message and an aborted request leaves
-- neither. created_at supports the 24-hour retention prune; contract requires
-- at least 24 h, this stand prunes only records older than that bound.
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
);
-- Retention housekeeping walks old rows; new inserts stay cheap.
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
+631
View File
@@ -0,0 +1,631 @@
// 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
}