Заменить 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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user