// AGENT: Concrete PostgreSQL store: plain parameterized SQL, one bounded pool, // explicit transaction boundaries. It returns contract AppErrors so HTTP status // mapping stays in one place. package store import ( "context" "errors" "net" "time" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" ) type Store struct { pool *pgxpool.Pool timeout time.Duration } func New(pool *pgxpool.Pool, timeout time.Duration) *Store { return &Store{pool: pool, timeout: timeout} } func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) { return context.WithTimeout(ctx, s.timeout) } func (s *Store) Ping(ctx context.Context) error { pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() return s.pool.Ping(pingCtx) } func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() user := model.User{ ID: uuid.New(), Username: username, DisplayName: displayName, PasswordHash: passwordHash, CreatedAt: common.NowUTC(), } _, err := s.pool.Exec(ctx, ` INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`, user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt)) if err != nil { // AGENT: The unique index is the real guard. Two concurrent registrations // with the same username both reach INSERT; exactly one commits, the other // gets SQLSTATE 23505 and is mapped to 409 instead of a 500. if isUniqueViolation(err) { return model.User{}, common.Conflict("username already taken") } return model.User{}, dbError(err) } return user, nil } func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() return s.scanUser(s.pool.QueryRow(ctx, ` SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id)) } func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() return s.scanUser(s.pool.QueryRow(ctx, ` SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username)) } type rowScanner interface { Scan(dest ...any) error } func (s *Store) scanUser(row rowScanner) (model.User, error) { var user model.User var createdAt time.Time if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil { if errors.Is(err, pgx.ErrNoRows) { return model.User{}, common.NotFound("user not found") } return model.User{}, dbError(err) } user.CreatedAt = common.RFCFormTime(createdAt.UTC()) return user, nil } // CreateChat inserts the chat and every membership row in one transaction. // Any unknown member aborts the whole transaction, so a partially created chat // can never be observed. func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return model.Chat{}, dbError(err) } defer func() { _ = tx.Rollback(context.Background()) }() for _, memberID := range memberIDs { var exists int err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists) if errors.Is(err, pgx.ErrNoRows) { return model.Chat{}, common.BadRequest("member_id refers to non-existent user") } if err != nil { return model.Chat{}, dbError(err) } } chat := model.Chat{ ID: uuid.New(), Title: title, MemberIDs: append([]uuid.UUID(nil), memberIDs...), CreatedAt: common.NowUTC(), } if _, err = tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil { return model.Chat{}, dbError(err) } for _, memberID := range memberIDs { if _, err = tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, chat.ID, memberID); err != nil { return model.Chat{}, dbError(err) } } if err = tx.Commit(ctx); err != nil { return model.Chat{}, dbError(err) } return chat, nil } func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() var chat model.Chat var createdAt time.Time err := s.pool.QueryRow(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 WHERE c.id = $1`, chatID, userID). Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs) if errors.Is(err, pgx.ErrNoRows) { return model.Chat{}, common.NotFound("chat not found") } if err != nil { return model.Chat{}, dbError(err) } chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) return chat, nil } func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) { ctx, cancel := s.withTimeout(ctx) defer cancel() cursorTime, cursorID := cursorValues(cursor) rows, err := s.pool.Query(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 WHERE (c.created_at, c.id) > ($2, $3) ORDER BY c.created_at, c.id LIMIT $4`, userID, cursorTime, cursorID, limit+1) if err != nil { return nil, dbError(err) } defer rows.Close() chats := 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 nil, dbError(err) } chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) chats = append(chats, chat) } if err = rows.Err(); err != nil { return nil, dbError(err) } hasMore := len(chats) > limit if hasMore { chats = chats[:limit] } return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil } func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() var exists int err := s.pool.QueryRow(ctx, `SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&exists) if errors.Is(err, pgx.ErrNoRows) { return false, nil } if err != nil { return false, dbError(err) } return true, nil } // CreateMessage uses INSERT ... SELECT so the membership check and the insert // are a single atomic statement: no window where the user is removed between // check and write. Zero affected rows means the chat is missing or foreign. func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() message := model.Message{ ID: uuid.New(), ChatID: chatID, SenderID: senderID, Text: text, CreatedAt: common.NowUTC(), } tag, err := s.pool.Exec(ctx, ` INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`, message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt)) if err != nil { return model.Message{}, dbError(err) } if tag.RowsAffected() == 0 { return model.Message{}, common.NotFound("chat not found") } return message, nil } func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) { isMember, err := s.IsMember(ctx, userID, chatID) if err != nil { return nil, err } if !isMember { return nil, common.NotFound("chat not found") } // AGENT: Cursor context is checked only after membership, so a foreign // caller gets 404 and cannot probe cursor validity against someone else's chat. if cursor != nil && cursor.ContextID != chatID { return nil, common.BadRequest("bad cursor value") } ctx, cancel := s.withTimeout(ctx) defer cancel() // AGENT: limit+1 is fetched so next_cursor is known to be non-null without a // second COUNT query; the extra row is never returned to the client. cursorTime, cursorID := cursorValues(cursor) rows, err := s.pool.Query(ctx, ` SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`, chatID, cursorTime, cursorID, limit+1) if err != nil { return nil, dbError(err) } defer rows.Close() messages := 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 nil, dbError(err) } message.CreatedAt = common.RFCFormTime(createdAt.UTC()) messages = append(messages, message) } if err = rows.Err(); err != nil { return nil, dbError(err) } hasMore := len(messages) > limit if hasMore { messages = messages[:limit] } return &common.Page[model.Message]{ Items: messages, NextCursor: common.NextCursor(messages, hasMore, chatID), }, nil } func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) { if cursor == nil { return time.Time{}, uuid.Nil } return cursor.Time, cursor.ID } func isUniqueViolation(err error) bool { var pgErr *pgconn.PgError return errors.As(err, &pgErr) && pgErr.Code == "23505" } // dbError separates a drained dependency (503) from a real bug (500). SQL // details never reach the client; callers only emit the AppError message. func dbError(err error) error { if err == nil { return nil } var pgErr *pgconn.PgError if errors.As(err, &pgErr) { switch pgErr.Code { case "23505": return common.Conflict("resource already exists") case "23503", "23514", "22P02": return common.BadRequest("request conflicts with stored data") } } var netErr net.Error if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || pgconn.SafeToRetry(err) || errors.Is(err, pgx.ErrTxClosed) { return common.Unavailable("database unavailable") } return common.Internal() }