// Package store holds the repository implementations of the chats module. // // Keyset pages use `id > COALESCE($after, nil uuid)`: every UUIDv7 is // greater than the nil UUID, so one query serves the first page and the // following ones, and the condition stays a range the index can scan. Ids // are UUIDv7 and created_at derives from them, so ordering by id is the // contract order (created_at, id). Errors pass through postgres.Classify, so // an unreachable database surfaces as unavailability. package store import ( "context" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "messenger/internal/chat" "messenger/internal/platform/postgres" ) type Chats struct { pool *pgxpool.Pool } var _ chat.ChatRepository = (*Chats)(nil) func NewChats(pool *pgxpool.Pool) *Chats { return &Chats{pool: pool} } func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID) error { return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error { if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, c.ID, c.Title, c.CreatedAt); err != nil { return fmt.Errorf("insert chat: %w", err) } if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) SELECT $1, unnest($2::uuid[])`, c.ID, memberIDs); err != nil { return fmt.Errorf("insert chat members: %w", err) } return nil })) } func (r *Chats) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) { row := r.pool.QueryRow(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) FROM chats c WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, userID) c, err := scanChat(row) if errors.Is(err, pgx.ErrNoRows) { return chat.ChatWithMembers{}, chat.ErrNotFound } if err != nil { return chat.ChatWithMembers{}, fmt.Errorf("select chat: %w", postgres.Classify(err)) } return c, nil } func (r *Chats) IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) { var ok bool err := r.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, userID).Scan(&ok) if err != nil { return false, fmt.Errorf("check membership: %w", postgres.Classify(err)) } return ok, nil } func (r *Chats) ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) { rows, err := r.pool.Query(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) FROM chat_members own JOIN chats c ON c.id = own.chat_id WHERE own.user_id = $1 AND own.chat_id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid) ORDER BY own.chat_id LIMIT $3`, userID, after, limit) if err != nil { return nil, fmt.Errorf("select chats: %w", postgres.Classify(err)) } chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.ChatWithMembers, error) { return scanChat(row) }) if err != nil { return nil, fmt.Errorf("read chats: %w", postgres.Classify(err)) } return chats, nil } func scanChat(row pgx.Row) (chat.ChatWithMembers, error) { var c chat.ChatWithMembers if err := row.Scan(&c.ID, &c.Title, &c.CreatedAt, &c.MemberIDs); err != nil { return chat.ChatWithMembers{}, err } return c, nil } type Messages struct { pool *pgxpool.Pool } var _ chat.MessageRepository = (*Messages)(nil) func NewMessages(pool *pgxpool.Pool) *Messages { return &Messages{pool: pool} } // claimSQL binds the key and inserts the message in one statement, so the // key's lock never spans a round trip. An expired key is taken over; a valid // one leaves claimed, and so the message insert, empty. const claimSQL = ` WITH claimed AS ( INSERT INTO message_idempotency_keys AS k (user_id, chat_id, key, message_id) VALUES ($1, $2, $3, $4) ON CONFLICT (user_id, chat_id, key) DO UPDATE SET message_id = EXCLUDED.message_id, created_at = now() WHERE k.created_at < now() - $5::interval RETURNING message_id) INSERT INTO messages (chat_id, id, sender_id, text, created_at) SELECT $2, message_id, $1, $6, $7 FROM claimed` // The bound message is read by a second statement: the claim's snapshot // cannot see a key that a concurrent request has just committed. func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) { tag, err := r.pool.Exec(ctx, claimSQL, m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt) if err != nil { return chat.Message{}, fmt.Errorf("insert message: %w", postgres.Classify(err)) } if tag.RowsAffected() == 1 { return m, nil } var stored chat.Message err = r.pool.QueryRow(ctx, ` SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at FROM message_idempotency_keys k JOIN messages m ON m.chat_id = k.chat_id AND m.id = k.message_id WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`, m.SenderID, m.ChatID, key).Scan(&stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt) if err != nil { return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err)) } return stored, nil } // DeleteExpiredKeys skips rows locked by another cleaner or a request rather // than waiting for them. func (r *Messages) DeleteExpiredKeys(ctx context.Context, olderThan time.Duration, limit int) (int64, error) { tag, err := r.pool.Exec(ctx, ` DELETE FROM message_idempotency_keys WHERE (user_id, chat_id, key) IN ( SELECT user_id, chat_id, key FROM message_idempotency_keys WHERE created_at < now() - $1::interval ORDER BY created_at LIMIT $2 FOR UPDATE SKIP LOCKED)`, interval(olderThan), limit) if err != nil { return 0, fmt.Errorf("delete expired keys: %w", postgres.Classify(err)) } return tag.RowsAffected(), nil } // interval renders d for a ::interval parameter. func interval(d time.Duration) string { return fmt.Sprintf("%d milliseconds", d.Milliseconds()) } // ListByChat is the history query; scripts/explain-history.sql runs the same // statement for the EXPLAIN evidence. func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) { rows, err := r.pool.Query(ctx, ` SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid) ORDER BY id LIMIT $3`, chatID, after, limit) if err != nil { return nil, fmt.Errorf("select messages: %w", postgres.Classify(err)) } messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) { var m chat.Message err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt) return m, err }) if err != nil { return nil, fmt.Errorf("read messages: %w", postgres.Classify(err)) } return messages, nil }