// 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 ( "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-lab2/internal/cursor" "mtusi.ru/messenger-lab2/internal/model" "mtusi.ru/messenger-lab2/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") ) // 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-lab2" // 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 } // 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 } 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 }