Заменить lab4 на aws-sdk S3-вложения, уровень 4 и трек 2 reconciler.
Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
This commit is contained in:
+175
-83
@@ -1,12 +1,12 @@
|
||||
// Вложения lab4: метаданные в PostgreSQL, байты в S3 (пакет blob).
|
||||
// Метаданные вложений (lab4): таблицы attachments и message_attachments.
|
||||
//
|
||||
// Согласованность двух хранилищ строится на порядке «сначала S3, потом БД»:
|
||||
// 1. PUT объекта в S3 по серверному ключу;
|
||||
// 2. INSERT строки attachments.
|
||||
// Разделение ответственности:
|
||||
// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id};
|
||||
// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ.
|
||||
//
|
||||
// Если PUT прошёл, а INSERT нет, остаётся объект без строки (orphan). API пытается удалить
|
||||
// его сразу, а если не вышло, его удалит reconciler после grace period. Обратный порядок
|
||||
// опаснее: строка без объекта отдавала бы клиенту 201 на файл, которого нет.
|
||||
// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go):
|
||||
// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler),
|
||||
// а не строка без файла (она бы отдавала пользователю ошибку при скачивании).
|
||||
package store
|
||||
|
||||
import (
|
||||
@@ -18,68 +18,85 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ErrNotReady — вложение существует в этом чате, но ещё не ready (в lab4 недостижимо,
|
||||
// зарезервировано под асинхронную обработку lab5).
|
||||
var ErrNotReady = errors.New("attachment not ready")
|
||||
// StatusReady — единственный статус lab4: 201 возвращается только после сохранения
|
||||
// и оригинала в S3, и метаданных в PostgreSQL.
|
||||
const StatusReady = "ready"
|
||||
|
||||
// Attachment — метаданные оригинала. ObjectKey во внешний JSON не попадает.
|
||||
// Attachment — строка таблицы attachments.
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentType string // image/png | image/jpeg, определён по содержимому
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
SHA256 string // lowercase hex
|
||||
ObjectKey string // внутренний, клиенту не отдаётся
|
||||
Status string
|
||||
ErrorCode *string
|
||||
Width int
|
||||
Height int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CreateAttachment пишет метаданные после успешного PUT в S3. ID и ObjectKey задаёт вызывающий:
|
||||
// ключ нужен до записи в БД. Членство в чате проверяется в самом INSERT — если автора уже
|
||||
// нет в чате, строка не появится и вернётся ErrNotFound.
|
||||
// AttachmentObjectKey строит ключ объекта. Ключ целиком определяется сервером:
|
||||
// имя файла клиента в нём не участвует (нет path traversal и коллизий имён),
|
||||
// а префикс chat-id группирует объекты чата для будущей очистки.
|
||||
func AttachmentObjectKey(chatID, attachmentID uuid.UUID) string {
|
||||
return "attachments/" + chatID.String() + "/" + attachmentID.String()
|
||||
}
|
||||
|
||||
// CreateAttachment вставляет метаданные уже загруженного в S3 объекта.
|
||||
//
|
||||
// INSERT ... SELECT ... WHERE EXISTS проверяет членство атомарно с вставкой:
|
||||
// между «проверили участие» в HTTP-слое и записью строки состав чата мог бы измениться,
|
||||
// а так условие и запись — один оператор. 0 строк → ErrNotFound (404).
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {
|
||||
if a.CreatedAt.IsZero() {
|
||||
// Миллисекундная точность — та же, что печатается в JSON.
|
||||
a.CreatedAt = nowUTC()
|
||||
}
|
||||
if a.Status == "" {
|
||||
a.Status = StatusReady
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
now := nowUTC()
|
||||
a.Status = "ready"
|
||||
a.ErrorCode = nil
|
||||
a.CreatedAt, a.UpdatedAt = now, now
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at
|
||||
)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $10
|
||||
object_key, status, error_code, width, height, created_at, updated_at)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $11, $12, $12
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||
a.ObjectKey, a.Status, a.CreatedAt)
|
||||
a.ObjectKey, a.Status, a.Width, a.Height, a.CreatedAt)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAttachment отдаёт вложение только участнику его чата. Чужому и несуществующему —
|
||||
// одинаковый ErrNotFound (HTTP 404): наличие чужого файла не раскрываем.
|
||||
func (s *Store) GetAttachment(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) {
|
||||
// GetAttachmentForUser возвращает вложение ТОЛЬКО участнику его чата.
|
||||
// Чужое и несуществующее неразличимы (ErrNotFound → 404, не 403): иначе можно было
|
||||
// бы по коду ответа проверять, существует ли чужой файл.
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var a Attachment
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.object_key, a.status, a.error_code, a.created_at, a.updated_at
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes,
|
||||
a.sha256, a.object_key, a.status, a.error_code, a.width, a.height,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1`, id, userID).Scan(
|
||||
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
|
||||
&a.ObjectKey, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes,
|
||||
&a.SHA256, &a.ObjectKey, &a.Status, &a.ErrorCode, &a.Width, &a.Height,
|
||||
&a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
@@ -89,48 +106,97 @@ func (s *Store) GetAttachment(ctx context.Context, id, userID uuid.UUID) (*Attac
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// EnsureChatMember — публичная проверка «пользователь состоит в чате» (ErrNotFound иначе).
|
||||
func (s *Store) EnsureChatMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
return s.ensureMember(ctx, chatID, userID)
|
||||
}
|
||||
|
||||
// ListAttachmentIDsForMessage возвращает ID вложений сообщения в порядке запроса.
|
||||
// Пустой результат — непустой срез нулевой длины, чтобы JSON дал [], а не null.
|
||||
func (s *Store) ListAttachmentIDsForMessage(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться
|
||||
// «полуфабрикатов» (строк метаданных без успешной загрузки).
|
||||
func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
byMsg, err := attachmentIDsByMessage(ctx, s.pool, []uuid.UUID{messageID})
|
||||
var n int
|
||||
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE chat_id = $1`, chatID).Scan(&n); err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// querier — общая часть pgx.Tx и pgxpool.Pool: так одни и те же функции читают
|
||||
// связи сообщений и внутри транзакции (идемпотентный replay), и вне её (история).
|
||||
type querier interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
// lockMessageAttachments проверяет вложения будущего сообщения внутри его транзакции.
|
||||
//
|
||||
// - WHERE id = ANY($1) AND chat_id = $2: вложение другого чата и несуществующее
|
||||
// одинаково «не находятся» → ErrNotFound (404). Это и есть привязка файла к чату.
|
||||
// - FOR SHARE блокирует найденные строки до COMMIT: параллельное удаление
|
||||
// (reconciler) подождёт и затем упрётся в внешний ключ message_attachments.
|
||||
// - Если нашлось меньше строк, чем запрошено, — хотя бы одно чужое/неизвестное.
|
||||
// - Любой статус, кроме ready, → ErrAttachmentNotReady (409).
|
||||
//
|
||||
// ids уже проверены HTTP-слоем на уникальность и количество (≤10).
|
||||
func lockMessageAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT id, status FROM attachments
|
||||
WHERE id = ANY($1) AND chat_id = $2
|
||||
ORDER BY id
|
||||
FOR SHARE`, ids, chatID)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
var status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != StatusReady {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
rows.Close()
|
||||
if found != len(ids) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return ErrAttachmentNotReady
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadMessageAttachmentIDs — вложения одного сообщения в исходном порядке (position).
|
||||
// Никогда не возвращает nil: пустой срез сериализуется в [], а не в null.
|
||||
func loadMessageAttachmentIDs(ctx context.Context, q querier, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
byMsg, err := attachmentIDsByMessage(ctx, q, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return byMsg[messageID], nil
|
||||
}
|
||||
|
||||
// querier — общая часть pgxpool.Pool и pgx.Tx.
|
||||
type querier interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
// attachmentIDsByMessage — один запрос на страницу сообщений (без N+1).
|
||||
// Все ключи результата заполнены: у сообщений без вложений значение — пустой срез.
|
||||
//
|
||||
// q — пул или транзакция: внутри транзакции запрос обязан идти по её соединению, иначе при
|
||||
// маленьком пуле транзакция занимает соединение и ждёт второе.
|
||||
// attachmentIDsByMessage одним запросом читает связи для набора сообщений.
|
||||
// Для сообщений без вложений вернётся пустой (не nil) срез.
|
||||
func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) {
|
||||
out := make(map[uuid.UUID][]uuid.UUID, len(messageIDs))
|
||||
for _, id := range messageIDs {
|
||||
out[id] = []uuid.UUID{}
|
||||
}
|
||||
if len(messageIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
strs := make([]string, len(messageIDs))
|
||||
for i, id := range messageIDs {
|
||||
out[id] = []uuid.UUID{}
|
||||
strs[i] = id.String()
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position`, strs)
|
||||
WHERE message_id = ANY($1)
|
||||
ORDER BY message_id, position`, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
@@ -145,27 +211,51 @@ func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UU
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// AttachmentRef — строка attachments для reconciler: только то, что нужно для сверки с S3.
|
||||
type AttachmentRef struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
SizeBytes int64
|
||||
CreatedAt time.Time
|
||||
Referenced bool // есть ли хотя бы одно сообщение со ссылкой на файл
|
||||
// attachMessageAttachments дозаполняет AttachmentIDs у страницы сообщений (ListMessages).
|
||||
func (s *Store) attachMessageAttachments(ctx context.Context, items []Message) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]uuid.UUID, len(items))
|
||||
for i := range items {
|
||||
ids[i] = items[i].ID
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, s.pool, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAttachmentRefs — keyset-страница по id. Страницы небольшие: у соединения
|
||||
// statement_timeout 3 с, один огромный SELECT на большой таблице под него не уложится.
|
||||
func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit int) ([]AttachmentRef, error) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Методы для reconciler (internal/reconcile). Они здесь, а не в reconcile, потому
|
||||
// что SQL и работа с пулом принадлежат пакету store.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// AttachmentRef — минимальная информация о строке для сверки с S3.
|
||||
type AttachmentRef struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
// Used — на вложение ссылается хотя бы одно сообщение. Такое вложение удалять нельзя.
|
||||
Used bool
|
||||
}
|
||||
|
||||
// ListAttachmentRefsAfter — keyset-страница строк в байтовом порядке object_key
|
||||
// (колонка COLLATE "C" — порядок совпадает с листингом S3). afterKey="" — с начала.
|
||||
func (s *Store) ListAttachmentRefsAfter(ctx context.Context, afterKey string, limit int) ([]AttachmentRef, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT a.id, a.object_key, a.size_bytes, a.created_at,
|
||||
SELECT a.id, a.object_key, a.created_at,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a
|
||||
WHERE a.id > $1
|
||||
ORDER BY a.id
|
||||
LIMIT $2`, after, limit)
|
||||
WHERE a.object_key > $1
|
||||
ORDER BY a.object_key
|
||||
LIMIT $2`, afterKey, limit)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
@@ -173,7 +263,7 @@ func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit i
|
||||
var out []AttachmentRef
|
||||
for rows.Next() {
|
||||
var r AttachmentRef
|
||||
if err := rows.Scan(&r.ID, &r.ObjectKey, &r.SizeBytes, &r.CreatedAt, &r.Referenced); err != nil {
|
||||
if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
@@ -181,27 +271,29 @@ func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit i
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// AttachmentKeyExists — повторная проверка перед удалением orphan: между листингом S3
|
||||
// и удалением объект мог получить строку (загрузка закончилась). Это страховка поверх grace.
|
||||
func (s *Store) AttachmentKeyExists(ctx context.Context, objectKey string) (bool, error) {
|
||||
// AttachmentKeyExists — повторная проверка непосредственно перед удалением orphan-объекта:
|
||||
// сужает окно гонки «reconciler решил, что строки нет, а загрузка как раз сделала INSERT».
|
||||
func (s *Store) AttachmentKeyExists(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, objectKey).Scan(&ok)
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// DeleteUnreferencedAttachment удаляет строку, только если на неё нет ссылок из сообщений.
|
||||
// Условие NOT EXISTS в самом DELETE закрывает гонку «сообщение прикрепили, пока мы решали».
|
||||
// Возвращает true, если строка была удалена.
|
||||
func (s *Store) DeleteUnreferencedAttachment(ctx context.Context, id uuid.UUID) (bool, error) {
|
||||
// DeleteUnusedAttachment удаляет строку вложения, только если выполнены ОБА условия:
|
||||
// она старше olderThan (не «свежая») и на неё нет ссылок из сообщений (не «используемая»).
|
||||
// Возвращает true, если строка удалена. Внешний ключ message_attachments страхует
|
||||
// от гонки с параллельной отправкой сообщения: такой DELETE упадёт, а не потеряет данные.
|
||||
func (s *Store) DeleteUnusedAttachment(ctx context.Context, id uuid.UUID, olderThan time.Time) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, id)
|
||||
AND a.created_at < $2
|
||||
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`,
|
||||
id, olderThan)
|
||||
if err != nil {
|
||||
return false, mapWriteErr(err)
|
||||
}
|
||||
|
||||
@@ -1,28 +1,42 @@
|
||||
-- Вложения lab4. Метаданные в PostgreSQL, байты в приватном S3-bucket (MinIO).
|
||||
-- Ключ объекта назначает сервер: originals/<attachment_id>.
|
||||
-- filename только для отображения, в ключ не попадает.
|
||||
-- Вложения lab4. Метаданные - в PostgreSQL, байты - в приватном S3-bucket (MinIO).
|
||||
-- Ключ объекта назначает сервер: attachments/{chat_id}/{attachment_id}.
|
||||
-- filename - только отображаемое имя, в ключ и в путь не попадает.
|
||||
--
|
||||
-- ВНИМАНИЕ: файл режется по символу точки с запятой (см. splitSQL в migrate.go),
|
||||
-- поэтому в комментариях и литералах здесь нет этого символа.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
-- Файл заранее привязан к чату: доступ к нему определяется членством в этом чате.
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL,
|
||||
-- Тип определён по СОДЕРЖИМОМУ файла, а не по заголовку запроса.
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
-- lowercase hex SHA-256 оригинала.
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
-- COLLATE "C": байтовый порядок совпадает с лексикографическим порядком ListObjectsV2.
|
||||
-- Reconciler сливает два отсортированных потока (S3 и эта колонка) без загрузки в память.
|
||||
object_key text COLLATE "C" NOT NULL,
|
||||
-- lab4 знает только ready (201 после сохранения байтов и метаданных).
|
||||
-- Состояния queued/processing/failed появятся в lab5+ расширением CHECK.
|
||||
status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready')),
|
||||
error_code text,
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_object_key_unique UNIQUE (object_key)
|
||||
);
|
||||
|
||||
-- Проверка вложений сообщения идёт по PK, индекс по чату нужен списку и будущей очистке.
|
||||
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id);
|
||||
|
||||
-- Связь сообщение - вложение. position хранит порядок attachment_ids из запроса.
|
||||
-- Одно вложение можно прикрепить к нескольким сообщениям своего чата (контракт не запрещает).
|
||||
-- Внешние ключи не дают удалить вложение, на которое ссылается сообщение: reconciler
|
||||
-- физически не может снести «используемое» вложение даже при ошибке в его логике.
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
@@ -30,4 +44,4 @@ CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id)
|
||||
|
||||
+46
-76
@@ -8,10 +8,6 @@
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Вложения (lab4) — файл attachments.go: метаданные в PostgreSQL, байты в S3. Сообщение
|
||||
// ссылается на вложения через message_attachments; ссылки пишутся в той же транзакции,
|
||||
// что и само сообщение и ключ идемпотентности.
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
@@ -66,14 +62,15 @@ type Chat struct {
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
// AttachmentIDs всегда непустой срез нулевой длины, если вложений нет (JSON даёт []).
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
// AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API
|
||||
// (контракт: attachment_ids обязателен, по умолчанию []).
|
||||
AttachmentIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
@@ -318,11 +315,12 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
// Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null.
|
||||
AttachmentIDs: []uuid.UUID{},
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
@@ -346,20 +344,22 @@ type IdempotentMessage struct {
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение со вложениями и запоминает ответ по ключу.
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message (с его вложениями);
|
||||
// 4. иначе проверить членство в чате и вложения: каждое должно существовать, лежать
|
||||
// в ЭТОМ чате и быть ready (чужое/неизвестное — ErrNotFound, не ready — ErrNotReady);
|
||||
// 5. INSERT message + message_attachments + idempotency_keys в той же транзакции;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready,
|
||||
// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT;
|
||||
// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же
|
||||
// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет;
|
||||
// 6. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// attachmentIDs уже без дубликатов (проверяет HTTP-слой), порядок сохраняется.
|
||||
// Пустой текст допустим только вместе с вложениями — это тоже проверяет HTTP-слой.
|
||||
// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound
|
||||
// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл.
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
@@ -371,9 +371,6 @@ func (s *Store) CreateMessageIdempotent(
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -405,7 +402,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, tx, []uuid.UUID{msgID})
|
||||
// Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ.
|
||||
replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -418,8 +416,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
AttachmentIDs: byMsg[msgID],
|
||||
CreatedAt: msgCreated,
|
||||
AttachmentIDs: replayIDs,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
@@ -437,39 +435,10 @@ func (s *Store) CreateMessageIdempotent(
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
attStrs := make([]string, len(attachmentIDs))
|
||||
for i, id := range attachmentIDs {
|
||||
attStrs[i] = id.String()
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// chat_id = $2 — вложение другого чата неотличимо от несуществующего (404, не 403).
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2`, attStrs, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var status string
|
||||
if err := rows.Scan(&status); err != nil {
|
||||
rows.Close()
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != "ready" {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if found != len(attStrs) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return nil, ErrNotReady
|
||||
}
|
||||
// Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату,
|
||||
// а не информацию о существовании файлов.
|
||||
if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
@@ -477,8 +446,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
@@ -486,25 +455,28 @@ func (s *Store) CreateMessageIdempotent(
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// WITH ORDINALITY сохраняет порядок attachment_ids из запроса.
|
||||
// Порядок attachment_ids клиента сохраняется в position.
|
||||
for i, aid := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
SELECT $1, u.id, (u.ord - 1)::smallint
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)`, msg.ID, attStrs); err != nil {
|
||||
VALUES ($1, $2, $3)`, msg.ID, aid, i); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
// response_body заполняем каноническим Message JSON уже здесь, чтобы replay
|
||||
// не зависел от повторной сериализации в HTTP-слое с другим порядком полей.
|
||||
attachmentStrs := make([]string, len(msg.AttachmentIDs))
|
||||
for i, aid := range msg.AttachmentIDs {
|
||||
attachmentStrs[i] = aid.String()
|
||||
}
|
||||
bodyJSON, err := json.Marshal(map[string]any{
|
||||
"id": msg.ID.String(),
|
||||
"chat_id": msg.ChatID.String(),
|
||||
"sender_id": msg.SenderID.String(),
|
||||
"text": msg.Text,
|
||||
"attachment_ids": attStrs,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
"attachment_ids": attachmentStrs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -576,18 +548,10 @@ func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limi
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
// Вложения страницы — одним запросом, а не по запросу на сообщение.
|
||||
ids := make([]uuid.UUID, len(items))
|
||||
for i := range items {
|
||||
ids[i] = items[i].ID
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, s.pool, ids)
|
||||
if err != nil {
|
||||
// Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы).
|
||||
if err := s.attachMessageAttachments(ctx, items); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
@@ -608,6 +572,12 @@ func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// IsChatMember — проверка членства для HTTP-слоя (например, до чтения тела загрузки:
|
||||
// постороннему не нужно тратить на себя RAM и трафик). ErrNotFound — не участник.
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
return s.ensureMember(ctx, chatID, userID)
|
||||
}
|
||||
|
||||
func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
Reference in New Issue
Block a user