Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.

Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready;
компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
Mlvn
2026-11-12 18:08:47 +03:00
parent ec540a1a72
commit 7cbb75c897
43 changed files with 6075 additions and 36 deletions
+209
View File
@@ -0,0 +1,209 @@
// Вложения lab4: метаданные в PostgreSQL, байты в S3 (пакет blob).
//
// Согласованность двух хранилищ строится на порядке «сначала S3, потом БД»:
// 1. PUT объекта в S3 по серверному ключу;
// 2. INSERT строки attachments.
//
// Если PUT прошёл, а INSERT нет, остаётся объект без строки (orphan). API пытается удалить
// его сразу, а если не вышло, его удалит reconciler после grace period. Обратный порядок
// опаснее: строка без объекта отдавала бы клиенту 201 на файл, которого нет.
package store
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// ErrNotReady — вложение существует в этом чате, но ещё не ready (в lab4 недостижимо,
// зарезервировано под асинхронную обработку lab5).
var ErrNotReady = errors.New("attachment not ready")
// Attachment — метаданные оригинала. ObjectKey во внешний JSON не попадает.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
ObjectKey string
Status string
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
// CreateAttachment пишет метаданные после успешного PUT в S3. ID и ObjectKey задаёт вызывающий:
// ключ нужен до записи в БД. Членство в чате проверяется в самом INSERT — если автора уже
// нет в чате, строка не появится и вернётся ErrNotFound.
func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {
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
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)
if err != nil {
return mapWriteErr(err)
}
if tag.RowsAffected() != 1 {
return ErrNotFound
}
return nil
}
// GetAttachment отдаёт вложение только участнику его чата. Чужому и несуществующему —
// одинаковый ErrNotFound (HTTP 404): наличие чужого файла не раскрываем.
func (s *Store) GetAttachment(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
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)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, mapWriteErr(err)
}
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) {
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
defer cancel()
byMsg, err := attachmentIDsByMessage(ctx, s.pool, []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 — пул или транзакция: внутри транзакции запрос обязан идти по её соединению, иначе при
// маленьком пуле транзакция занимает соединение и ждёт второе.
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))
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)
if err != nil {
return nil, mapWriteErr(err)
}
defer rows.Close()
for rows.Next() {
var mid, aid uuid.UUID
if err := rows.Scan(&mid, &aid); err != nil {
return nil, mapWriteErr(err)
}
out[mid] = append(out[mid], aid)
}
return out, mapWriteErr(rows.Err())
}
// AttachmentRef — строка attachments для reconciler: только то, что нужно для сверки с S3.
type AttachmentRef struct {
ID uuid.UUID
ObjectKey string
SizeBytes int64
CreatedAt time.Time
Referenced bool // есть ли хотя бы одно сообщение со ссылкой на файл
}
// ListAttachmentRefs — keyset-страница по id. Страницы небольшие: у соединения
// statement_timeout 3 с, один огромный SELECT на большой таблице под него не уложится.
func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, 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,
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)
if err != nil {
return nil, mapWriteErr(err)
}
defer rows.Close()
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 {
return nil, mapWriteErr(err)
}
out = append(out, r)
}
return out, mapWriteErr(rows.Err())
}
// AttachmentKeyExists — повторная проверка перед удалением orphan: между листингом S3
// и удалением объект мог получить строку (загрузка закончилась). Это страховка поверх grace.
func (s *Store) AttachmentKeyExists(ctx context.Context, objectKey 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)
return ok, mapWriteErr(err)
}
// DeleteUnreferencedAttachment удаляет строку, только если на неё нет ссылок из сообщений.
// Условие NOT EXISTS в самом DELETE закрывает гонку «сообщение прикрепили, пока мы решали».
// Возвращает true, если строка была удалена.
func (s *Store) DeleteUnreferencedAttachment(ctx context.Context, id uuid.UUID) (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)
if err != nil {
return false, mapWriteErr(err)
}
return tag.RowsAffected() == 1, nil
}