Files
mtusi2026lab3/internal/chat/store/postgres.go
T

231 lines
8.0 KiB
Go

// 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}
}
// afterClaim runs between the claiming statement and the replay lookup of
// AppendOnce; tests use it to delete the key in that window.
var afterClaim func()
// claimSQL stores the key and the message in one statement. A key older than
// the retention period is taken over for the new message. The key row is
// inserted first: when it already exists and is still valid, claimed is
// empty and so is the message insert. One statement holds the key's lock
// only while the server executes it, never across a round trip to a replica
// that might die in between.
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`
// AppendOnce stores m under key unless the sender already used the key in
// this chat within ttl; it returns the message the key is bound to, m itself
// or the earlier one. Deciding whether the earlier message answers the same
// request is the caller's job.
//
// The lookup of an existing key is a second statement: within the claiming
// one, a plain SELECT would see the snapshot taken before a concurrent
// request committed the key. Between the two statements the cleaner may
// delete a key at the ttl boundary; the operation then starts over once,
// which stores m under the now free key.
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
for range 2 {
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
}
if afterClaim != nil {
afterClaim()
}
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 errors.Is(err, pgx.ErrNoRows) {
continue
}
if err != nil {
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
}
return stored, nil
}
return chat.Message{}, errors.New("idempotency key vanished twice between claim and lookup")
}
// DeleteExpiredKeys removes up to limit keys older than ttl. SKIP LOCKED lets
// replicas cleaning at the same time, and requests holding a key, pass each
// other instead of waiting.
func (r *Messages) DeleteExpiredKeys(ctx context.Context, ttl 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(ttl), 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
}