// 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-lab4/internal/cursor" "mtusi.ru/messenger-lab4/internal/model" "mtusi.ru/messenger-lab4/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") ErrAttachmentNotReady = errors.New("attachment is not ready") ) // 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-lab4" // 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" } func isIdempotencyViolation(err error) bool { var pgErr *pgconn.PgError return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "message_idempotency_pkey" } // 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(), } } // CreateMessageIdempotent appends a message, its attachment links and the // idempotency result in one PostgreSQL transaction. A committed transaction // therefore always contains the message, every link and the key record; a // failed one contains none of them. The idempotency unique index serialises // concurrent replays: the loser blocks, then rolls back and reads the committed // winner, so a concurrent repeat can never create a second message. // // 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 and links, 201; // - a different body with the same key is a conflict, 409; // - a transient failure touches neither table, 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, attachmentIDs []string) (model.Message, bool, error) { if attachmentIDs == nil { attachmentIDs = []string{} } message := model.Message{ ID: uuid.New(), ChatID: chatID, SenderID: senderID, Text: text, // A non-nil empty slice is required: the public Message schema has // attachment_ids: [] as an array, never null. AttachmentIDs: append([]string{}, attachmentIDs...), } 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()) }() // Validate every attachment against the message chat before writing any // row. The composite foreign key is the second line of defence; this query // lets the handler distinguish "foreign/unknown" (404) from "not ready" // (409) without leaking whether a foreign attachment id exists. if len(attachmentIDs) > 0 { rows, queryErr := tx.Query(ctx, ` SELECT id::text, status FROM attachments WHERE chat_id = $1::uuid AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`, chatID, attachmentIDs) if queryErr != nil { return model.Message{}, false, s.classify(queryErr) } statuses := make(map[string]string, len(attachmentIDs)) for rows.Next() { var id, status string if scanErr := rows.Scan(&id, &status); scanErr != nil { rows.Close() return model.Message{}, false, s.classify(scanErr) } statuses[id] = status } if rows.Err() != nil { rows.Close() return model.Message{}, false, s.classify(rows.Err()) } rows.Close() if len(statuses) != len(attachmentIDs) { return model.Message{}, false, ErrNotFound } for _, status := range statuses { if status != "ready" { return model.Message{}, false, ErrAttachmentNotReady } } } created := time.Now().UTC() var stored time.Time 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, created, ).Scan(&stored) if err != nil { if isForeignKeyViolation(err) { return model.Message{}, false, ErrNotFound } return model.Message{}, false, s.classify(err) } if len(attachmentIDs) > 0 { batch := &pgx.Batch{} for position, attachmentID := range attachmentIDs { batch.Queue(` INSERT INTO message_attachments (message_id, attachment_id, chat_id, position) VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`, message.ID, attachmentID, chatID, position) } results := tx.SendBatch(ctx, batch) for range attachmentIDs { if _, execErr := results.Exec(); execErr != nil { _ = results.Close() if isForeignKeyViolation(execErr) { return model.Message{}, false, ErrNotFound } return model.Message{}, false, s.classify(execErr) } } if closeErr := results.Close(); closeErr != nil { if isForeignKeyViolation(closeErr) { return model.Message{}, false, ErrNotFound } return model.Message{}, false, s.classify(closeErr) } } _, 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)`, senderID, method, path, key, requestHash, message.ID, created) if err != nil { if isIdempotencyViolation(err) { // This transaction never committed. Roll it back explicitly before // reading the winner; PostgreSQL has already released the row lock // when it reported the unique violation. _ = tx.Rollback(ctx) storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key) if replayErr != nil { return model.Message{}, false, replayErr } if !found { 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 } return model.Message{}, false, s.classify(err) } if err := tx.Commit(ctx); err != nil { return model.Message{}, false, s.classify(err) } message.CreatedAt = model.Time{Time: stored.UTC()} return message, false, 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, COALESCE(( SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id ), '{}') 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, &message.AttachmentIDs) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, model.Message{}, false, nil } return nil, model.Message{}, false, s.classify(err) } if message.AttachmentIDs == nil { message.AttachmentIDs = []string{} } 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 m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at, COALESCE(( SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id ), '{}') FROM (` // 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() where := `WHERE chat_id = $1::uuid` args := []any{chatID, limit + 1} order := `ORDER BY created_at, id LIMIT $2` if position != nil { where = `WHERE chat_id = $1::uuid AND (created_at, id) > ($2::timestamptz, $3::uuid)` args = []any{chatID, position.At, position.ID, limit + 1} order = `ORDER BY created_at, id LIMIT $4` } query := messagesPageSelect + ` SELECT id, chat_id, sender_id, text, created_at FROM messages ` + where + ` ` + order + ` ) m LEFT JOIN message_attachments ma ON ma.message_id = m.id GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at ORDER BY m.created_at, m.id` 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, &message.AttachmentIDs); err != nil { return model.MessagePage{}, s.classify(err) } if message.AttachmentIDs == nil { message.AttachmentIDs = []string{} } 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 }