292 lines
9.7 KiB
Go
292 lines
9.7 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/attachment"
|
|
"messenger/internal/chat"
|
|
"messenger/internal/platform/apperr"
|
|
"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. An expired
|
|
// key is taken over; a valid one leaves claimed and 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 transaction keeps attachment readiness, message joins and the key atomic.
|
|
// The replay uses a new statement snapshot to see a concurrent winner.
|
|
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
|
|
var stored chat.Message
|
|
err := pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
tag, err := tx.Exec(ctx, claimSQL,
|
|
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
|
|
if err != nil {
|
|
return fmt.Errorf("insert message: %w", err)
|
|
}
|
|
if tag.RowsAffected() == 1 {
|
|
// Only a new message creates attachment links. A replay returns the
|
|
// committed message even if its attachment has since failed.
|
|
if err := validateAttachments(ctx, tx, m.ChatID, m.AttachmentIDs); err != nil {
|
|
return err
|
|
}
|
|
if len(m.AttachmentIDs) > 0 {
|
|
_, err := tx.Exec(ctx, `
|
|
INSERT INTO message_attachments (chat_id, message_id, attachment_id, ordinal)
|
|
SELECT $1, $2, id, (ord - 1)::smallint
|
|
FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)`,
|
|
m.ChatID, m.ID, m.AttachmentIDs)
|
|
if err != nil {
|
|
return fmt.Errorf("insert message attachments: %w", err)
|
|
}
|
|
}
|
|
stored = m
|
|
return nil
|
|
}
|
|
stored, err = scanMessage(tx.QueryRow(ctx, `
|
|
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
|
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
|
|
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))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
// A vanished key is available again; retry its atomic claim.
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("select message by key: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
})
|
|
if err != nil {
|
|
return chat.Message{}, postgres.Classify(err)
|
|
}
|
|
return stored, nil
|
|
}
|
|
|
|
func validateAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
// Lock attachment identities in the same order for every message. Pipeline
|
|
// version changes lock the attachment before replacing its current job.
|
|
rows, err := tx.Query(ctx, `
|
|
SELECT id FROM attachments WHERE chat_id=$1 AND id=ANY($2::uuid[])
|
|
ORDER BY id FOR SHARE`, chatID, ids)
|
|
if err != nil {
|
|
return fmt.Errorf("lock attachments: %w", err)
|
|
}
|
|
locked, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(locked) != len(ids) {
|
|
return apperr.NotFound("attachment not found")
|
|
}
|
|
// A separate statement sees the latest committed transition after a lock wait.
|
|
// Terminal failures take FOR UPDATE on the job or file. KEY SHARE orders
|
|
// validation with those transitions while allowing an outbox publish in flight.
|
|
rows, err = tx.Query(ctx, `SELECT status FROM attachment_states WHERE id=ANY($1::uuid[]) ORDER BY id FOR KEY SHARE`, ids)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
states, err := pgx.CollectRows(rows, pgx.RowTo[attachment.FileStatus])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(states) != len(ids) {
|
|
return apperr.Conflict("attachment processing state unavailable")
|
|
}
|
|
for _, state := range states {
|
|
switch state {
|
|
case attachment.FileQueued, attachment.FileProcessing, attachment.FileReady:
|
|
default:
|
|
return apperr.Conflict("attachment processing failed")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func scanMessage(row pgx.Row) (chat.Message, error) {
|
|
var m chat.Message
|
|
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
|
|
if len(m.AttachmentIDs) == 0 {
|
|
m.AttachmentIDs = nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// 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 keeps keyset pagination on messages and collects each ordered
|
|
// attachment array in the same statement.
|
|
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 m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
|
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
|
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
|
|
FROM messages m
|
|
WHERE m.chat_id = $1
|
|
AND m.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) {
|
|
return scanMessage(row)
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read messages: %w", postgres.Classify(err))
|
|
}
|
|
return messages, nil
|
|
}
|