Files
mtusi2026lab4/internal/store/attachments.go
T
Mlvn fef1c30050 Заменить lab4 на aws-sdk S3-вложения, уровень 4 и трек 2 reconciler.
Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
2026-11-12 18:25:21 +03:00

302 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Метаданные вложений (lab4): таблицы attachments и message_attachments.
//
// Разделение ответственности:
// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id};
// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ.
//
// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go):
// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler),
// а не строка без файла (она бы отдавала пользователю ошибку при скачивании).
package store
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// StatusReady — единственный статус lab4: 201 возвращается только после сохранения
// и оригинала в S3, и метаданных в PostgreSQL.
const StatusReady = "ready"
// Attachment — строка таблицы attachments.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string // image/png | image/jpeg, определён по содержимому
SizeBytes int64
SHA256 string // lowercase hex
ObjectKey string // внутренний, клиенту не отдаётся
Status string
ErrorCode *string
Width int
Height int
CreatedAt time.Time
UpdatedAt time.Time
}
// 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()
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, 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.Width, a.Height, a.CreatedAt)
if err != nil {
return mapWriteErr(err)
}
if tag.RowsAffected() != 1 {
return ErrNotFound
}
a.UpdatedAt = a.CreatedAt
return nil
}
// 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.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.Width, &a.Height,
&a.CreatedAt, &a.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, mapWriteErr(err)
}
return &a, nil
}
// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться
// «полуфабрикатов» (строк метаданных без успешной загрузки).
func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) {
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
defer cancel()
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
}
// 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
}
rows, err := q.Query(ctx, `
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY($1)
ORDER BY message_id, position`, messageIDs)
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())
}
// 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
}
// ---------------------------------------------------------------------------
// Методы для 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.created_at,
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
FROM attachments a
WHERE a.object_key > $1
ORDER BY a.object_key
LIMIT $2`, afterKey, 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.CreatedAt, &r.Used); err != nil {
return nil, mapWriteErr(err)
}
out = append(out, r)
}
return out, mapWriteErr(rows.Err())
}
// 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)`, key).Scan(&ok)
return ok, mapWriteErr(err)
}
// 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 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)
}
return tag.RowsAffected() == 1, nil
}