Заменить lab4 на aws-sdk S3-вложения, уровень 4 и трек 2 reconciler.
Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
This commit is contained in:
+258
-315
@@ -1,43 +1,35 @@
|
||||
package api
|
||||
|
||||
// Вложения lab4: загрузка, метаданные, скачивание.
|
||||
// HTTP-слой вложений lab4.
|
||||
//
|
||||
// Загрузка (POST /chats/{id}/attachments?filename=...) идёт строго по шагам, и каждый шаг
|
||||
// отсекает запрос как можно раньше и дешевле:
|
||||
// Модель согласованности двух хранилищ (S3 + PostgreSQL), т.к. общей транзакции у них нет:
|
||||
//
|
||||
// 1. Bearer-аутентификация (requireUser), затем членство в чате: посторонний получает 404;
|
||||
// 2. filename: 1–255 code points, без «/», «\», NUL и управляющих символов — иначе 400;
|
||||
// 3. заявленный Content-Type — только image/png или image/jpeg, иначе 415;
|
||||
// 4. тело копируется в спул (временный файл, при его отказе — память) с одновременным SHA-256
|
||||
// и жёстким лимитом MaxUploadBytes+1: больше лимита — 413. Тело не буферизуется целиком
|
||||
// в куче через ReadAll, поэтому пик RAM на загрузку — буфер копирования, а не размер файла;
|
||||
// 5. тип по содержимому (http.DetectContentType) обязан совпасть с заявленным, иначе 415 (подмена MIME);
|
||||
// 6. размеры берутся из заголовка PNG/JPEG БЕЗ декодирования пикселей; больше
|
||||
// MaxImagePixels — 413. Это делается до любой «распаковки»: bomb 60000×60000 весит килобайты;
|
||||
// 7. дешёвая структурная проверка (PNG: CRC всех чанков и IEND, JPEG: EOI) ловит обрезанные
|
||||
// и повреждённые файлы — 415;
|
||||
// 8. PUT в S3 по серверному ключу originals/<uuid>, затем INSERT метаданных. Только после
|
||||
// обоих шагов — 201. Если INSERT не удался, объект удаляется сразу, а при отказе удаления
|
||||
// его подберёт reconciler (cmd/reconcile) после grace period.
|
||||
// 1. проверяем всё, что можно, ДО записи (доступ, имя, тип, размер, содержимое);
|
||||
// 2. PUT оригинала в S3 по ключу attachments/{chat}/{id};
|
||||
// 3. INSERT метаданных в PostgreSQL;
|
||||
// 4. только после этого — 201 ready.
|
||||
//
|
||||
// До шага 8 в S3 ничего не пишется, поэтому оборванная загрузка клиента не оставляет объектов.
|
||||
// Что если процесс/сеть упали между 2 и 3, или INSERT вернул ошибку?
|
||||
// - Остаётся лишний ОБЪЕКТ без строки (orphan). Строки без файла не бывает —
|
||||
// ради этого PUT делается ПЕРВЫМ. Пользователь не увидит «битое» вложение,
|
||||
// а лишний объект безвреден: на него никто не ссылается.
|
||||
// - При ошибке INSERT мы сразу пытаемся удалить объект (компенсация, compensateOrphan).
|
||||
// - Если и удаление не удалось (процесс убит, S3 моргнул) — объект подберёт reconciler
|
||||
// (`/server -reconcile`): он удаляет объекты без строки старше S3_ORPHAN_GRACE_SECONDS.
|
||||
// Grace нужен, чтобы не снести объект, у которого INSERT ещё «в полёте».
|
||||
// - Обрыв соединения клиентом во время передачи тела: до PUT мы ничего не пишем,
|
||||
// а PUT/INSERT привязаны к контексту запроса и отменяются.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
_ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -46,194 +38,274 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/objectstore"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxMessageAttachments = 10
|
||||
maxFilenameRunes = 255
|
||||
// После превышения лимита дочитываем (и выбрасываем) не больше этого объёма:
|
||||
// клиент успевает получить 413, а не «connection reset» посреди своей отправки.
|
||||
drainOnOverflow = 64 << 20
|
||||
// drainLimit — сколько байт «лишнего» тела дочитываем при раннем отказе (413/415/400).
|
||||
// Если сервер ответил и закрыл соединение, пока клиент ещё пишет, клиент получит
|
||||
// RST вместо читаемого 413. Дочитывание ограничено, чтобы это не стало каналом
|
||||
// для бесплатной траты трафика.
|
||||
drainLimit = 16 << 20
|
||||
// slotWait — сколько загрузка ждёт свободный слот буферизации, прежде чем получить 429.
|
||||
// Меньше таймаутов HAProxy (15 с), чтобы клиент получил осмысленный ответ.
|
||||
slotWait = 8 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
errBadImage = errors.New("not a valid png/jpeg image")
|
||||
errTooManyPixels = errors.New("image has too many pixels")
|
||||
errTooLarge = errors.New("upload exceeds size limit")
|
||||
)
|
||||
// WithUploadConcurrency задаёт, сколько загрузок реплика обрабатывает одновременно.
|
||||
//
|
||||
// Зачем: тело загрузки целиком буферизуется в RAM (оно нужно для проверки содержимого и
|
||||
// SHA-256 ДО записи в S3, иначе мусор попадал бы в bucket). Без ограничения N клиентов
|
||||
// заняли бы N*10 MiB. Со слотами пик ≈ n*10 MiB (+ декод маленьких картинок),
|
||||
// остальные загрузки ждут в очереди, не читая тело.
|
||||
func (s *Server) WithUploadConcurrency(n int) *Server {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
s.uploadSlots = make(chan struct{}, n)
|
||||
return s
|
||||
}
|
||||
|
||||
// handleUploadAttachment — POST /api/v1/chats/{chat_id}/attachments?filename=...
|
||||
func (s *Server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
uid := userFrom(r)
|
||||
if err := s.Store.EnsureChatMember(r.Context(), chatID, uid); err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
|
||||
// 1. Сначала доступ к ресурсу (контракт: аутентификация → доступ → остальное).
|
||||
// Посторонний получает 404 до того, как мы потратим на него RAM и трафик.
|
||||
if err := s.Store.IsChatMember(r.Context(), chatID, uid); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
s.rejectUpload(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if !validFilename(filename) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid filename")
|
||||
return
|
||||
}
|
||||
declared, ok := declaredImageType(r.Header.Get("Content-Type"))
|
||||
// 2. filename — только для отображения. Опасные символы отклоняем сразу (400):
|
||||
// даже зная, что в путь/ключ он не попадает, не храним то, что опасно показывать.
|
||||
filename, ok := validFilename(r.URL.Query().Get("filename"))
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "only image/png and image/jpeg are accepted")
|
||||
return
|
||||
}
|
||||
// Клиент заранее заявил размер сильно больше лимита — не читаем ни байта.
|
||||
if r.ContentLength > s.MaxUploadBytes+drainOnOverflow {
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid filename")
|
||||
return
|
||||
}
|
||||
|
||||
sp, err := spoolBody(r.Body, s.MaxUploadBytes)
|
||||
// 3. Заголовок Content-Type должен быть image/png или image/jpeg. Это лишь заявка
|
||||
// клиента: настоящий тип определяется по содержимому (шаг 6) и должен с ней совпасть.
|
||||
declared, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || (declared != "image/png" && declared != "image/jpeg") {
|
||||
s.rejectUpload(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content type must be image/png or image/jpeg")
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Лимит размера до чтения тела: честный Content-Length > 10 MiB отвергаем сразу.
|
||||
if r.ContentLength > maxUploadBytes {
|
||||
s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
return
|
||||
}
|
||||
|
||||
// 5. Слот буферизации. Ждём не дольше slotWait, иначе 429 (контракт его допускает).
|
||||
release, ok := s.acquireUploadSlot(r.Context())
|
||||
if !ok {
|
||||
if r.Context().Err() != nil {
|
||||
return // клиент ушёл
|
||||
}
|
||||
w.Header().Set("Retry-After", "1")
|
||||
s.rejectUpload(w, r, http.StatusTooManyRequests, "rate_limited", "too many concurrent uploads")
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
// 6. Ограниченное чтение тела. MaxBytesReader гарантирует, что и при chunked-запросе
|
||||
// без Content-Length (где честную длину проверить нельзя) мы не прочитаем больше 10 MiB.
|
||||
origBody := r.Body
|
||||
data, err := readLimitedBody(w, r, maxUploadBytes)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errTooLarge):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
default:
|
||||
// Обрыв чтения тела или таймаут клиента. Ничего не записано ни в S3, ни в БД.
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "could not read request body")
|
||||
}
|
||||
return
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
if err := inspectImage(sp.reader(), sp.size, declared, s.MaxImagePixels); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errTooManyPixels):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels")
|
||||
default:
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "invalid or unsupported image")
|
||||
var tooBig *http.MaxBytesError
|
||||
if errors.As(err, &tooBig) {
|
||||
// Дочитываем (ограниченно) ИСХОДНОЕ тело: обёртка MaxBytesReader после
|
||||
// превышения лимита читать уже не даёт.
|
||||
r.Body = origBody
|
||||
s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
return
|
||||
}
|
||||
// Обрыв загрузки клиентом/таймаут чтения: ничего ещё не записано ни в S3, ни в БД.
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "upload interrupted")
|
||||
return
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
// 7. Проверка СОДЕРЖИМОГО: формат, пиксели, целостность. Пользовательская ошибка
|
||||
// здесь — всегда 4xx, никогда 500.
|
||||
info, err := inspectImage(data)
|
||||
switch {
|
||||
case errors.Is(err, errTooManyPixels):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels")
|
||||
return
|
||||
case err != nil:
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "file is not a valid png/jpeg image")
|
||||
return
|
||||
case info.ContentType != declared:
|
||||
// «Подмена MIME»: заголовок говорит jpeg, а внутри png (или наоборот).
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content does not match declared content type")
|
||||
return
|
||||
}
|
||||
|
||||
// 8. SHA-256 и ключ. Ключ полностью серверный: filename в нём не участвует.
|
||||
sum := sha256.Sum256(data)
|
||||
attID := uuid.New()
|
||||
key := store.AttachmentObjectKey(chatID, attID)
|
||||
|
||||
// 9. Оригинал в S3. Ошибка хранилища — 503 без подробностей.
|
||||
if err := s.Objects.Put(r.Context(), key, bytes.NewReader(data), int64(len(data)), info.ContentType); err != nil {
|
||||
log.Printf("request_id=%s attachment_put_failed err=%v", requestID(r), err)
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
// Точка отказа «между S3 и PG» — для тестов компенсации. В проде hook == nil.
|
||||
if s.AfterObjectPut != nil {
|
||||
s.AfterObjectPut(key)
|
||||
}
|
||||
|
||||
// 10. Метаданные в PostgreSQL. Дальше data больше не нужна — освобождаем RAM как можно раньше.
|
||||
att := &store.Attachment{
|
||||
ID: id,
|
||||
ID: attID,
|
||||
ChatID: chatID,
|
||||
OwnerID: uid,
|
||||
Filename: filename,
|
||||
ContentType: declared,
|
||||
SizeBytes: sp.size,
|
||||
SHA256: sp.sum,
|
||||
ObjectKey: blob.KeyPrefix + id.String(),
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: int64(len(data)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: key,
|
||||
Status: store.StatusReady,
|
||||
Width: info.Width,
|
||||
Height: info.Height,
|
||||
}
|
||||
data = nil
|
||||
if err := s.Store.CreateAttachment(r.Context(), att); err != nil {
|
||||
// Компенсация: строки нет → объект бесполезен. Удаляем сразу и независимо от
|
||||
// контекста запроса (он мог быть отменён — как раз из-за этого INSERT и упал).
|
||||
s.compensateOrphan(r, key)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
|
||||
// 1) S3. Тело отдаём как ReadSeeker: minio-go шлёт один PUT без буферизации в памяти.
|
||||
if err := s.Blob.Put(r.Context(), att.ObjectKey, sp.reader(), sp.size, declared); err != nil {
|
||||
s.writeBlobErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// 2) PostgreSQL. Ошибка здесь оставила бы объект без строки — убираем его сразу.
|
||||
if err := s.Store.CreateAttachment(r.Context(), att); err != nil {
|
||||
s.compensateOrphan(r, att.ObjectKey)
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
// 11. Теперь честно: и байты, и метаданные сохранены.
|
||||
writeJSON(w, http.StatusCreated, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// compensateOrphan удаляет объект, для которого не удалось записать метаданные.
|
||||
// Контекст отвязан от запроса: клиент мог отключиться, а чистить всё равно нужно.
|
||||
// Если и удаление не удалось (S3 мигнул), объект останется до reconciler — это допустимо.
|
||||
// compensateOrphan убирает объект, для которого не удалось записать метаданные.
|
||||
// Контекст новый и короткий. Если удаление не прошло — это не ошибка запроса:
|
||||
// объект станет orphan и будет удалён reconciler'ом после grace-периода.
|
||||
func (s *Server) compensateOrphan(r *http.Request, key string) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Blob.Delete(ctx, key); err != nil {
|
||||
log.Printf("request_id=%s orphan_cleanup_failed key=%s (reconciler will remove after grace)", requestID(r), key)
|
||||
if err := s.Objects.Delete(ctx, key); err != nil {
|
||||
log.Printf("request_id=%s attachment_compensation_failed key=%s (reconciler удалит orphan после grace) err=%v",
|
||||
requestID(r), key, err)
|
||||
return
|
||||
}
|
||||
log.Printf("request_id=%s attachment_compensated key=%s (PG insert не удался, объект удалён)", requestID(r), key)
|
||||
}
|
||||
|
||||
// handleGetAttachment — GET /api/v1/attachments/{id}: метаданные участнику чата.
|
||||
func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachment(w, r)
|
||||
att, ok := s.loadAttachmentForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// handleDownloadAttachment отдаёт оригинал побайтно через API, без редиректа на S3:
|
||||
// приватный bucket сам по себе не заменяет проверку членства в чате.
|
||||
// handleDownloadAttachment — GET /api/v1/attachments/{id}/content: байты через API, без redirect.
|
||||
// Прямой доступ к bucket не нужен ни клиенту, ни другой реплике: любая реплика читает
|
||||
// из общего S3, поэтому остановка загрузившей реплики ничего не ломает.
|
||||
func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachment(w, r)
|
||||
att, ok := s.loadAttachmentForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// variant по умолчанию original. В lab4 вариантов нет (variants=[]), значит любой
|
||||
// другой — «отсутствующий вариант ready-объекта», то есть 404.
|
||||
if v := r.URL.Query().Get("variant"); v != "" && v != "original" {
|
||||
// variant: в lab4 есть только original. Известные имена вариантов lab5+ у ready-объекта
|
||||
// отсутствуют → 404, неизвестное имя → 400.
|
||||
switch v := r.URL.Query().Get("variant"); v {
|
||||
case "", "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
switch att.Status {
|
||||
case "ready":
|
||||
default:
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid variant")
|
||||
return
|
||||
}
|
||||
if att.Status != store.StatusReady {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
|
||||
return
|
||||
}
|
||||
rc, err := s.Blob.Get(r.Context(), att.ObjectKey)
|
||||
|
||||
body, _, err := s.Objects.Get(r.Context(), att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, blob.ErrNotFound) {
|
||||
// Строка есть, объекта нет — несогласованность, её чинит reconciler.
|
||||
log.Printf("request_id=%s attachment_object_missing id=%s", requestID(r), att.ID)
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
// Строка есть, объекта нет — расхождение БД/S3 (его ловит reconciler).
|
||||
// Это не ошибка пользователя; наружу — общий 500 без деталей.
|
||||
log.Printf("request_id=%s attachment_object_missing attachment_id=%s", requestID(r), att.ID)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
s.writeBlobErr(w, r, err)
|
||||
log.Printf("request_id=%s attachment_get_failed err=%v", requestID(r), err)
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
defer body.Close()
|
||||
|
||||
h := w.Header()
|
||||
// Тип берём из БД (определён по содержимому при загрузке), а не из S3 и не из имени.
|
||||
h.Set("Content-Type", att.ContentType)
|
||||
h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
|
||||
// nosniff: браузер не должен «угадывать» иной тип у отданных байт.
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "private, no-store")
|
||||
h.Set("ETag", `"`+att.SHA256+`"`)
|
||||
// filename показываем только в заголовке, закодированным по RFC 5987 (FormatMediaType).
|
||||
if cd := mime.FormatMediaType("inline", map[string]string{"filename": att.Filename}); cd != "" {
|
||||
h.Set("Content-Disposition", cd)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, rc); err != nil {
|
||||
// Заголовки уже ушли; клиент увидит обрыв. В лог — без деталей S3.
|
||||
log.Printf("request_id=%s attachment_stream_error id=%s", requestID(r), att.ID)
|
||||
// Потоково: в памяти реплики лежит только буфер копирования, не весь файл.
|
||||
if _, err := io.Copy(w, body); err != nil {
|
||||
// Заголовки уже отправлены, статус не изменить; клиент увидит обрыв.
|
||||
log.Printf("request_id=%s attachment_stream_interrupted", requestID(r))
|
||||
}
|
||||
}
|
||||
|
||||
// loadAttachment разбирает {attachment_id} и проверяет членство в чате вложения.
|
||||
func (s *Server) loadAttachment(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) {
|
||||
// loadAttachmentForRequest разбирает {attachment_id} и проверяет доступ участника.
|
||||
// Невалидный UUID — 400; чужое/несуществующее — 404.
|
||||
func (s *Server) loadAttachmentForRequest(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) {
|
||||
id, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id")
|
||||
return nil, false
|
||||
}
|
||||
att, err := s.Store.GetAttachment(r.Context(), id, userFrom(r))
|
||||
att, err := s.Store.GetAttachmentForUser(r.Context(), id, userFrom(r))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return nil, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
// writeBlobErr: недоступный S3 — 503, остальное — 500. Текст ошибки клиенту не уходит.
|
||||
func (s *Server) writeBlobErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, blob.ErrUnavailable) {
|
||||
log.Printf("request_id=%s s3_unavailable", requestID(r))
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
log.Printf("request_id=%s blob_error_type=%T", requestID(r), err)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
|
||||
// attachmentDTO — публичное представление. object_key и bucket НЕ раскрываются.
|
||||
func attachmentDTO(a *store.Attachment) map[string]any {
|
||||
var errCode any
|
||||
if a.ErrorCode != nil {
|
||||
errCode = *a.ErrorCode
|
||||
}
|
||||
return map[string]any{
|
||||
"id": a.ID.String(),
|
||||
"chat_id": a.ChatID.String(),
|
||||
@@ -243,206 +315,77 @@ func attachmentDTO(a *store.Attachment) map[string]any {
|
||||
"size_bytes": a.SizeBytes,
|
||||
"sha256": a.SHA256,
|
||||
"status": a.Status,
|
||||
"variants": []any{},
|
||||
"error_code": errCode,
|
||||
"created_at": formatTime(a.CreatedAt),
|
||||
"updated_at": formatTime(a.UpdatedAt),
|
||||
// lab4: производных вариантов нет (они появятся с воркером в lab5+).
|
||||
"variants": []any{},
|
||||
"error_code": a.ErrorCode,
|
||||
"created_at": formatTime(a.CreatedAt),
|
||||
"updated_at": formatTime(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
// validFilename: 1–255 code points, валидный UTF-8, не «пустой» после TrimSpace.
|
||||
// «/», «\», NUL и управляющие символы запрещены: имя только отображается и никогда не
|
||||
// становится путём или ключом S3. «.» и «..» отвергаются как заведомо опасные.
|
||||
func validFilename(name string) bool {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" {
|
||||
return false
|
||||
// acquireUploadSlot занимает место в очереди буферизации. Возвращает функцию освобождения.
|
||||
func (s *Server) acquireUploadSlot(ctx context.Context) (func(), bool) {
|
||||
timer := time.NewTimer(slotWait)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case s.uploadSlots <- struct{}{}:
|
||||
return func() { <-s.uploadSlots }, true
|
||||
case <-ctx.Done():
|
||||
return nil, false
|
||||
case <-timer.C:
|
||||
return nil, false
|
||||
}
|
||||
if n := utf8.RuneCountInString(name); n < 1 || n > maxFilenameRunes {
|
||||
return false
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return false
|
||||
}
|
||||
for _, c := range name {
|
||||
if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// declaredImageType возвращает заявленный Content-Type без параметров, если он разрешён.
|
||||
func declaredImageType(header string) (string, bool) {
|
||||
mt, _, err := mime.ParseMediaType(header)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
switch mt {
|
||||
case "image/png", "image/jpeg":
|
||||
return mt, true
|
||||
}
|
||||
return "", false
|
||||
// rejectUpload отвечает ошибкой на запрос с ещё не прочитанным телом.
|
||||
// Перед ответом ограниченно дочитываем тело (см. drainLimit): иначе клиент, который
|
||||
// ещё пишет большой файл, получит сброс соединения вместо понятного статуса.
|
||||
func (s *Server) rejectUpload(w http.ResponseWriter, r *http.Request, status int, code, msg string) {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, drainLimit))
|
||||
writeError(w, r, status, code, msg)
|
||||
}
|
||||
|
||||
// spooled — принятое тело: размер, SHA-256 и произвольный доступ для проверок и PUT.
|
||||
type spooled struct {
|
||||
ra io.ReaderAt
|
||||
size int64
|
||||
sum string
|
||||
cleanup func()
|
||||
}
|
||||
|
||||
func (s *spooled) reader() *io.SectionReader { return io.NewSectionReader(s.ra, 0, s.size) }
|
||||
func (s *spooled) Close() { s.cleanup() }
|
||||
|
||||
// spoolBody читает тело не больше max байт. Временный файл защищает кучу от 10 одновременных
|
||||
// загрузок по 10 MiB; если /tmp недоступен, откатываемся на память (всё равно ограниченную max).
|
||||
func spoolBody(body io.Reader, max int64) (*spooled, error) {
|
||||
h := sha256.New()
|
||||
f, ferr := os.CreateTemp("", "upload-*")
|
||||
var (
|
||||
dst io.Writer
|
||||
buf *bytes.Buffer
|
||||
cleanup = func() {}
|
||||
)
|
||||
if ferr == nil {
|
||||
cleanup = func() { _ = f.Close(); _ = os.Remove(f.Name()) }
|
||||
dst = io.MultiWriter(f, h)
|
||||
} else {
|
||||
buf = &bytes.Buffer{}
|
||||
dst = io.MultiWriter(buf, h)
|
||||
// readLimitedBody читает тело не больше limit байт.
|
||||
//
|
||||
// Если клиент заявил Content-Length, буфер выделяется ОДИН раз нужного размера
|
||||
// (+MinRead, чтобы bytes.Buffer не удваивал ёмкость перед самым EOF и не копировал
|
||||
// 10 MiB в 20 MiB). Для chunked-тела размер неизвестен — буфер растёт, но лимит
|
||||
// MaxBytesReader всё равно ограничивает его сверху.
|
||||
func readLimitedBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, error) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
var buf bytes.Buffer
|
||||
if cl := r.ContentLength; cl > 0 && cl <= limit {
|
||||
buf.Grow(int(cl) + bytes.MinRead)
|
||||
}
|
||||
n, err := io.Copy(dst, io.LimitReader(body, max+1))
|
||||
if err != nil {
|
||||
cleanup()
|
||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n > max {
|
||||
cleanup()
|
||||
_, _ = io.CopyN(io.Discard, body, drainOnOverflow)
|
||||
return nil, errTooLarge
|
||||
}
|
||||
sp := &spooled{size: n, sum: hex.EncodeToString(h.Sum(nil)), cleanup: cleanup}
|
||||
if f != nil && ferr == nil {
|
||||
sp.ra = f
|
||||
} else {
|
||||
sp.ra = bytes.NewReader(buf.Bytes())
|
||||
}
|
||||
return sp, nil
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// inspectImage проверяет содержимое. Порядок важен: тип → размеры из заголовка (лимит
|
||||
// пикселей до любой распаковки) → структура файла.
|
||||
func inspectImage(sr *io.SectionReader, size int64, declared string, maxPixels int64) error {
|
||||
head := make([]byte, 512)
|
||||
n, _ := sr.ReadAt(head, 0)
|
||||
detected := ""
|
||||
if n > 0 {
|
||||
detected = http.DetectContentType(head[:n])
|
||||
// validFilename проверяет отображаемое имя: 1–255 code points, валидный UTF-8,
|
||||
// не пустое/не пробельное, без '/', '\', NUL и управляющих символов.
|
||||
// Дополнительно отвергаем разделители строк и bidi-переопределения (U+202A–202E,
|
||||
// U+2066–2069): через них имя «photognp.exe» выглядит иначе, чем записано.
|
||||
func validFilename(raw string) (string, bool) {
|
||||
if raw == "" || !utf8.ValidString(raw) {
|
||||
return "", false
|
||||
}
|
||||
if size < 1 || (detected != "image/png" && detected != "image/jpeg") || detected != declared {
|
||||
return errBadImage
|
||||
if n := utf8.RuneCountInString(raw); n < 1 || n > 255 {
|
||||
return "", false
|
||||
}
|
||||
|
||||
var w, h int64
|
||||
switch detected {
|
||||
case "image/png":
|
||||
// IHDR всегда первый чанк: 8 байт сигнатуры, 4 длина, 4 тип, затем width/height.
|
||||
// Читаем сами: image/png.DecodeConfig отвергает файл с битым CRC раньше, чем
|
||||
// мы успели бы честно ответить «слишком много пикселей».
|
||||
if n < 24 || string(head[12:16]) != "IHDR" || binary.BigEndian.Uint32(head[8:12]) != 13 {
|
||||
return errBadImage
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return "", false
|
||||
}
|
||||
for _, c := range raw {
|
||||
switch {
|
||||
case c == '/', c == '\\', c == 0, unicode.IsControl(c):
|
||||
return "", false
|
||||
case c == 0x2028, c == 0x2029:
|
||||
return "", false
|
||||
case c >= 0x202A && c <= 0x202E, c >= 0x2066 && c <= 0x2069:
|
||||
return "", false
|
||||
}
|
||||
w = int64(binary.BigEndian.Uint32(head[16:20]))
|
||||
h = int64(binary.BigEndian.Uint32(head[20:24]))
|
||||
case "image/jpeg":
|
||||
cfg, _, err := image.DecodeConfig(io.NewSectionReader(sr, 0, size))
|
||||
if err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
w, h = int64(cfg.Width), int64(cfg.Height)
|
||||
}
|
||||
if w < 1 || h < 1 {
|
||||
return errBadImage
|
||||
}
|
||||
if w*h > maxPixels {
|
||||
return errTooManyPixels
|
||||
}
|
||||
|
||||
if detected == "image/png" {
|
||||
return verifyPNG(io.NewSectionReader(sr, 0, size), size)
|
||||
}
|
||||
return verifyJPEGTail(sr, size)
|
||||
}
|
||||
|
||||
// verifyPNG обходит чанки и проверяет их CRC без декомпрессии IDAT: обрезанный или
|
||||
// испорченный PNG отвергается за один линейный проход по файлу.
|
||||
func verifyPNG(r io.Reader, size int64) error {
|
||||
br := bufio.NewReaderSize(r, 64<<10)
|
||||
if _, err := br.Discard(8); err != nil { // сигнатура уже проверена DetectContentType
|
||||
return errBadImage
|
||||
}
|
||||
consumed := int64(8)
|
||||
var (
|
||||
hdr [8]byte
|
||||
crcBuf [4]byte
|
||||
first = true
|
||||
sawIDAT bool
|
||||
sawIEND bool
|
||||
crcHasher = crc32.NewIEEE()
|
||||
)
|
||||
for !sawIEND {
|
||||
if _, err := io.ReadFull(br, hdr[:]); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
length := int64(binary.BigEndian.Uint32(hdr[0:4]))
|
||||
ctype := string(hdr[4:8])
|
||||
if length > size-consumed-12 {
|
||||
return errBadImage
|
||||
}
|
||||
if first && ctype != "IHDR" {
|
||||
return errBadImage
|
||||
}
|
||||
first = false
|
||||
crcHasher.Reset()
|
||||
_, _ = crcHasher.Write(hdr[4:8])
|
||||
if _, err := io.CopyN(crcHasher, br, length); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
if _, err := io.ReadFull(br, crcBuf[:]); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
if crcHasher.Sum32() != binary.BigEndian.Uint32(crcBuf[:]) {
|
||||
return errBadImage
|
||||
}
|
||||
consumed += 12 + length
|
||||
switch ctype {
|
||||
case "IDAT":
|
||||
sawIDAT = true
|
||||
case "IEND":
|
||||
sawIEND = true
|
||||
}
|
||||
}
|
||||
// Данные после IEND — признак полиглота или склейки файлов, не принимаем.
|
||||
if !sawIDAT || consumed != size {
|
||||
return errBadImage
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyJPEGTail требует маркер конца изображения EOI (FF D9) в хвосте файла.
|
||||
// Допускаются нулевые/мусорные байты выравнивания после него (до 1 KiB).
|
||||
func verifyJPEGTail(sr *io.SectionReader, size int64) error {
|
||||
tailLen := int64(1024)
|
||||
if size < tailLen {
|
||||
tailLen = size
|
||||
}
|
||||
tail := make([]byte, tailLen)
|
||||
if _, err := sr.ReadAt(tail, size-tailLen); err != nil && !errors.Is(err, io.EOF) {
|
||||
return errBadImage
|
||||
}
|
||||
if bytes.LastIndex(tail, []byte{0xFF, 0xD9}) < 0 {
|
||||
return errBadImage
|
||||
}
|
||||
return nil
|
||||
return raw, true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
_ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig / image.Decode
|
||||
_ "image/png" // регистрирует декодер PNG
|
||||
)
|
||||
|
||||
// Лимиты контракта lab4.
|
||||
const (
|
||||
// maxUploadBytes = 10 MiB = 10 485 760 байт. Превышение — 413.
|
||||
maxUploadBytes = 10 << 20
|
||||
// maxImagePixels — 40 млн декодированных пикселей. Превышение — 413.
|
||||
// Проверяется по заголовку (image.DecodeConfig) ДО любой распаковки: PNG размером
|
||||
// в несколько КБ может «раскрыться» в гигабайты (decompression bomb).
|
||||
maxImagePixels = 40_000_000
|
||||
// fullDecodeMaxPixels — до этого размера дополнительно делаем ПОЛНЫЙ декод, чтобы
|
||||
// поймать повреждённые данные внутри потока (битый zlib/Huffman при целых заголовках).
|
||||
// Для больших картинок полный декод стоил бы сотни МБ RAM на одну загрузку
|
||||
// (40 Мпикс * 4–8 байт) — это ровно то, что запрещает требование про ограниченную RAM,
|
||||
// поэтому там остаются дешёвые структурные проверки (CRC всех чанков PNG, маркеры/EOI JPEG).
|
||||
fullDecodeMaxPixels = 2_000_000
|
||||
)
|
||||
|
||||
var (
|
||||
// errNotImage — не PNG/JPEG или файл повреждён → 415.
|
||||
errNotImage = errors.New("not a valid png/jpeg image")
|
||||
// errTooManyPixels — больше 40 млн пикселей → 413.
|
||||
errTooManyPixels = errors.New("too many pixels")
|
||||
)
|
||||
|
||||
// imageInfo — результат проверки содержимого.
|
||||
type imageInfo struct {
|
||||
ContentType string // image/png | image/jpeg — по СОДЕРЖИМОМУ, не по заголовку запроса
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
// inspectImage определяет формат и размеры и отвергает повреждённые файлы.
|
||||
//
|
||||
// Порядок важен:
|
||||
// 1. image.DecodeConfig читает только заголовок: формат + width/height без выделения
|
||||
// пиксельного буфера. Не PNG/JPEG (в т.ч. GIF, WebP, текст, нули) → errNotImage.
|
||||
// 2. Лимит пикселей проверяется сразу и ДО структурной проверки и декода.
|
||||
// 3. Структурная проверка (дёшево, O(n) по байтам, без распаковки).
|
||||
// 4. Полный декод только для небольших изображений (см. fullDecodeMaxPixels).
|
||||
func inspectImage(data []byte) (imageInfo, error) {
|
||||
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
var info imageInfo
|
||||
switch format {
|
||||
case "png":
|
||||
info.ContentType = "image/png"
|
||||
case "jpeg":
|
||||
info.ContentType = "image/jpeg"
|
||||
default:
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
info.Width, info.Height = cfg.Width, cfg.Height
|
||||
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if pixels > maxImagePixels {
|
||||
return imageInfo{}, errTooManyPixels
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "png":
|
||||
if !validPNGStructure(data) {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
case "jpeg":
|
||||
if !validJPEGStructure(data) {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
}
|
||||
|
||||
if pixels <= fullDecodeMaxPixels {
|
||||
if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// validPNGStructure обходит чанки PNG, не распаковывая данные:
|
||||
// сигнатура, первым IHDR (13 байт), у каждого чанка верный CRC-32, есть хотя бы один IDAT,
|
||||
// последний чанк — пустой IEND, после него ничего нет. Усечённый или «склеенный»
|
||||
// файл этой проверки не проходит.
|
||||
func validPNGStructure(data []byte) bool {
|
||||
const signature = "\x89PNG\r\n\x1a\n"
|
||||
if len(data) < len(signature)+12 || string(data[:len(signature)]) != signature {
|
||||
return false
|
||||
}
|
||||
pos := len(signature)
|
||||
first, sawIDAT := true, false
|
||||
for {
|
||||
if pos+8 > len(data) {
|
||||
return false // обрыв внутри заголовка чанка
|
||||
}
|
||||
length := int64(binary.BigEndian.Uint32(data[pos:]))
|
||||
if length > 0x7fffffff {
|
||||
return false // по спецификации длина < 2^31
|
||||
}
|
||||
end := int64(pos) + 8 + length + 4 // длина + тип + данные + CRC
|
||||
if end > int64(len(data)) {
|
||||
return false // обрыв внутри данных/CRC
|
||||
}
|
||||
chunkType := string(data[pos+4 : pos+8])
|
||||
// CRC считается по типу и данным, без поля длины.
|
||||
if crc32.ChecksumIEEE(data[pos+4:end-4]) != binary.BigEndian.Uint32(data[end-4:end]) {
|
||||
return false
|
||||
}
|
||||
if first {
|
||||
if chunkType != "IHDR" || length != 13 {
|
||||
return false
|
||||
}
|
||||
first = false
|
||||
}
|
||||
switch chunkType {
|
||||
case "IDAT":
|
||||
sawIDAT = true
|
||||
case "IEND":
|
||||
return sawIDAT && length == 0 && end == int64(len(data))
|
||||
}
|
||||
pos = int(end)
|
||||
}
|
||||
}
|
||||
|
||||
// validJPEGStructure — дешёвая проверка целостности JPEG без декода:
|
||||
// файл начинается с SOI (FFD8), заканчивается EOI (FFD9; нулевой «паддинг» в хвосте
|
||||
// допускается), и до SOS (начало данных скана) все сегменты имеют корректную длину.
|
||||
// Усечённый JPEG (потерян хвост) не проходит из-за отсутствия EOI.
|
||||
func validJPEGStructure(data []byte) bool {
|
||||
if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 {
|
||||
return false
|
||||
}
|
||||
end := len(data)
|
||||
for end > 0 && data[end-1] == 0x00 {
|
||||
end--
|
||||
}
|
||||
if end < 2 || data[end-2] != 0xFF || data[end-1] != 0xD9 {
|
||||
return false
|
||||
}
|
||||
i := 2
|
||||
for i < len(data) {
|
||||
if data[i] != 0xFF {
|
||||
return false
|
||||
}
|
||||
for i < len(data) && data[i] == 0xFF { // fill-байты 0xFF перед маркером
|
||||
i++
|
||||
}
|
||||
if i >= len(data) {
|
||||
return false
|
||||
}
|
||||
marker := data[i]
|
||||
i++
|
||||
switch {
|
||||
case marker == 0xDA: // SOS: дальше энтропийно-кодированные данные, маркеры не идут подряд
|
||||
return true
|
||||
case marker == 0xD9: // EOI до SOS — в файле нет изображения
|
||||
return false
|
||||
case marker == 0x01 || (marker >= 0xD0 && marker <= 0xD8): // маркеры без длины
|
||||
continue
|
||||
default:
|
||||
if i+2 > len(data) {
|
||||
return false
|
||||
}
|
||||
segLen := int(binary.BigEndian.Uint16(data[i:]))
|
||||
if segLen < 2 || i+segLen > len(data) {
|
||||
return false
|
||||
}
|
||||
i += segLen
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+38
-51
@@ -1,4 +1,4 @@
|
||||
// Package api — HTTP-слой lab4 (поверх lab3: LB, идемпотентность, сессии в Redis).
|
||||
// Package api — HTTP-слой lab4 (lab3 + вложения в S3).
|
||||
//
|
||||
// Порядок обработки запроса:
|
||||
// 1. X-Request-Id и X-Instance-Id на каждый ответ, включая ошибки;
|
||||
@@ -6,13 +6,11 @@
|
||||
// 3. маршрут;
|
||||
// 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают.
|
||||
//
|
||||
// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis и S3:
|
||||
// без них нельзя честно принять запись или узнать, кто делает запрос.
|
||||
// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis
|
||||
// и S3: без них нельзя честно принять запись, узнать, кто делает запрос, или принять/отдать
|
||||
// вложение (lab4: недоступный S3 → 503, балансировщик снимает реплику).
|
||||
//
|
||||
// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики.
|
||||
//
|
||||
// Вложения (attachments.go): сырой PNG/JPEG в теле POST, байты в приватном S3, метаданные в
|
||||
// PostgreSQL. Скачивание — только через этот API, без редиректа на S3.
|
||||
package api
|
||||
|
||||
import (
|
||||
@@ -36,7 +34,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/objectstore"
|
||||
"mtusi2026lab4/internal/session"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
@@ -54,43 +52,27 @@ const (
|
||||
challengeBearer = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
// Лимиты вложений по контракту lab4.
|
||||
const (
|
||||
DefaultMaxUploadBytes int64 = 10 << 20 // 10 MiB = 10 485 760
|
||||
DefaultMaxImagePixels int64 = 40_000_000
|
||||
)
|
||||
|
||||
// BlobStore — то, что API требует от S3-клиента. *blob.Client его реализует;
|
||||
// интерфейс нужен, чтобы тест мог подставить недоступное хранилище.
|
||||
type BlobStore interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
var _ BlobStore = (*blob.Client)(nil)
|
||||
|
||||
// Server связывает HTTP с PostgreSQL, Redis и S3.
|
||||
// Server связывает HTTP с PostgreSQL и Redis.
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Sessions *session.Store
|
||||
Blob BlobStore
|
||||
Objects *objectstore.Store // приватный S3-bucket с оригиналами вложений
|
||||
InstanceID string
|
||||
// Лимиты загрузки. По умолчанию контрактные; main.go может только ужесточить.
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
ready atomic.Bool
|
||||
ready atomic.Bool
|
||||
|
||||
// uploadSlots — семафор одновременных загрузок (ограничивает пик RAM, см. attachments.go).
|
||||
uploadSlots chan struct{}
|
||||
|
||||
// AfterObjectPut — тестовый hook: вызывается после успешного PUT в S3 и до INSERT в PG.
|
||||
// Позволяет в тестах смоделировать отказ «между S3 и БД». В проде всегда nil.
|
||||
AfterObjectPut func(key string)
|
||||
}
|
||||
|
||||
// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready.
|
||||
// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса.
|
||||
func New(st *store.Store, sessions *session.Store, bl BlobStore, instanceID string) *Server {
|
||||
s := &Server{
|
||||
Store: st, Sessions: sessions, Blob: bl, InstanceID: instanceID,
|
||||
MaxUploadBytes: DefaultMaxUploadBytes,
|
||||
MaxImagePixels: DefaultMaxImagePixels,
|
||||
}
|
||||
func New(st *store.Store, sessions *session.Store, objects *objectstore.Store, instanceID string) *Server {
|
||||
s := &Server{Store: st, Sessions: sessions, Objects: objects, InstanceID: instanceID}
|
||||
s.uploadSlots = make(chan struct{}, 4) // значение по умолчанию; main задаёт UPLOAD_MAX_CONCURRENCY
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
@@ -113,6 +95,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.handleGetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleListMessages))
|
||||
// lab4: вложения. Загрузка — сырой binary (не multipart), метаданные и байты — через API.
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", s.requireUser(s.handleUploadAttachment))
|
||||
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}", s.requireUser(s.handleGetAttachment))
|
||||
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", s.requireUser(s.handleDownloadAttachment))
|
||||
@@ -128,9 +111,11 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||
return
|
||||
}
|
||||
// S3 — обязательная зависимость синхронного пути (загрузка и скачивание вложений).
|
||||
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil ||
|
||||
s.Blob.Ping(r.Context()) != nil {
|
||||
// lab4: S3 — критичная зависимость обязательного синхронного пути (загрузка/скачивание).
|
||||
// Недоступное хранилище → 503, чтобы LB не слал трафик на реплику, которая не может
|
||||
// выполнить контракт; сообщения без вложений при этом тоже временно недоступны
|
||||
// (осознанное упрощение: readiness один на реплику, см. REPORT).
|
||||
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil || s.Objects.Ping(r.Context()) != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
@@ -346,9 +331,11 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// attachment_ids: 0–10 уникальных UUID; отсутствующий ключ, null и [] равны для хэша.
|
||||
if len(body.AttachmentIDs) > maxMessageAttachments {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachments")
|
||||
// attachment_ids: 0–10 уникальных UUID, по умолчанию []. Отсутствующий ключ, null и []
|
||||
// равны. UUID нормализуем (нижний регистр, канонический вид): иначе «ABC…» и «abc…»
|
||||
// давали бы разные хэши идемпотентности и дубль в uniqueItems.
|
||||
if len(body.AttachmentIDs) > 10 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachment_ids")
|
||||
return
|
||||
}
|
||||
attachmentIDs := make([]uuid.UUID, 0, len(body.AttachmentIDs))
|
||||
@@ -368,11 +355,11 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
attachmentIDs = append(attachmentIDs, id)
|
||||
canonicalIDs = append(canonicalIDs, id.String())
|
||||
}
|
||||
// Длина — по исходному тексту. Непустота — по TrimSpace, но только если вложений нет:
|
||||
// text="" с хотя бы одним вложением разрешён контрактом lab4.
|
||||
// Пробелы по краям сохраняются как есть, иначе «пробел + 4000 букв» проходил бы как 4000.
|
||||
// Непустота — по TrimSpace; длина и сохранение — по исходному тексту.
|
||||
// Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000.
|
||||
// lab4: пустой текст допустим, если есть хотя бы одно вложение (сообщение «только файл»).
|
||||
if utf8.RuneCountInString(body.Text) > 4000 ||
|
||||
(len(attachmentIDs) == 0 && strings.TrimSpace(body.Text) == "") {
|
||||
(strings.TrimSpace(body.Text) == "" && len(attachmentIDs) == 0) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
@@ -390,7 +377,7 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrNotReady) {
|
||||
if errors.Is(err, store.ErrAttachmentNotReady) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
|
||||
return
|
||||
}
|
||||
@@ -689,18 +676,18 @@ func chatDTO(c *store.Chat) map[string]any {
|
||||
}
|
||||
|
||||
func messageDTO(m *store.Message) map[string]any {
|
||||
// Всегда массив, даже пустой: клиент lab3 без вложений видит [] (контракт 1.4.0).
|
||||
att := make([]string, len(m.AttachmentIDs))
|
||||
// attachment_ids обязателен в ответе (контракт 1.4.0): всегда массив, не null.
|
||||
ids := make([]string, len(m.AttachmentIDs))
|
||||
for i, id := range m.AttachmentIDs {
|
||||
att[i] = id.String()
|
||||
ids[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"attachment_ids": att,
|
||||
"created_at": formatTime(m.CreatedAt),
|
||||
"attachment_ids": ids,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
package blob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Memory — in-memory BlobStore для student-tests без живого MinIO.
|
||||
// Не для production: нет persistence между процессами.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
objects map[string]memObj
|
||||
down bool
|
||||
bucketOK bool
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type memObj struct {
|
||||
data []byte
|
||||
modTime time.Time
|
||||
}
|
||||
|
||||
// NewMemory создаёт пустое хранилище с «живым» бакетом.
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{
|
||||
objects: make(map[string]memObj),
|
||||
bucketOK: true,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// SetUnavailable имитирует падение S3 (Ping/Put/Get → ErrUnavailable).
|
||||
func (m *Memory) SetUnavailable(v bool) { m.mu.Lock(); m.down = v; m.mu.Unlock() }
|
||||
|
||||
func (m *Memory) Bucket() string { return "memory" }
|
||||
|
||||
func (m *Memory) Ping(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down || !m.bucketOK {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Put(ctx context.Context, key string, r io.Reader, size int64, _ string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r, size+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int64(len(data)) != size {
|
||||
return ErrUnavailable
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: m.now()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(o.data)), nil
|
||||
}
|
||||
|
||||
func (m *Memory) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ObjectInfo{}, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ObjectInfo{}, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return ObjectInfo{}, ErrNotFound
|
||||
}
|
||||
return ObjectInfo{Key: key, Size: int64(len(o.data)), LastModified: o.modTime}, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(ctx context.Context, key string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
delete(m.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var out []ObjectInfo
|
||||
for k, o := range m.objects {
|
||||
if len(prefix) == 0 || (len(k) >= len(prefix) && k[:len(prefix)] == prefix) {
|
||||
out = append(out, ObjectInfo{Key: k, Size: int64(len(o.data)), LastModified: o.modTime})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Seed кладёт объект напрямую (для тестов reconciler).
|
||||
func (m *Memory) Seed(key string, data []byte, modTime time.Time) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if modTime.IsZero() {
|
||||
modTime = m.now()
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: modTime}
|
||||
}
|
||||
|
||||
var _ interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
} = (*Memory)(nil)
|
||||
@@ -1,197 +0,0 @@
|
||||
// Package blob — тонкая обёртка над MinIO (S3 API) для оригиналов вложений lab4.
|
||||
//
|
||||
// Байты файлов живут только здесь, а не в PostgreSQL и не на диске API-реплики.
|
||||
// Ключ объекта назначает сервер (originals/<uuid>); filename клиента в ключ не попадает.
|
||||
// Bucket приватный: прямого доступа без подписи нет, скачивание идёт через авторизованный API.
|
||||
//
|
||||
// Ошибки сведены к двум классам, чтобы HTTP-слой не знал про minio-go:
|
||||
// ErrNotFound — объекта нет (404/500 по контексту), ErrUnavailable — S3 недоступен (503).
|
||||
package blob
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// KeyPrefix — префикс ключей оригиналов. Reconciler обходит только его.
|
||||
const KeyPrefix = "originals/"
|
||||
|
||||
var (
|
||||
// ErrNotFound — такого объекта в бакете нет.
|
||||
ErrNotFound = errors.New("blob: not found")
|
||||
// ErrUnavailable — S3 не отвечает, отказал в доступе или вернул неожиданную ошибку.
|
||||
ErrUnavailable = errors.New("blob: unavailable")
|
||||
)
|
||||
|
||||
// Config — параметры подключения. Секреты приходят из окружения/файла, в логи не попадают.
|
||||
type Config struct {
|
||||
Endpoint string // host:port без схемы, например minio:9000
|
||||
UseSSL bool
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
// ObjectInfo — то, что reconciler и тесты знают об объекте.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Client — клиент одного бакета.
|
||||
type Client struct {
|
||||
mc *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// New создаёт клиента. Сеть не трогает: доступность проверяют Ping/EnsureBucket.
|
||||
//
|
||||
// Таймауты заданы явно. Без них connection refused ретраится minio-go десяток раз,
|
||||
// и «S3 лежит» вместо быстрого 503 превращается в зависший запрос.
|
||||
func New(cfg Config) (*Client, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" {
|
||||
return nil, fmt.Errorf("blob: endpoint and bucket are required")
|
||||
}
|
||||
tr := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 2 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 64,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 20 * time.Second,
|
||||
}
|
||||
mc, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Transport: tr,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("blob: init client: %w", err)
|
||||
}
|
||||
return &Client{mc: mc, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
// Bucket возвращает имя бакета (для логов и отчётов).
|
||||
func (c *Client) Bucket() string { return c.bucket }
|
||||
|
||||
// EnsureBucket создаёт бакет, если его нет. Идемпотентно.
|
||||
// В Compose бакет создаёт minio-init с root-правами, а у app-пользователя прав на
|
||||
// создание нет — функция нужна локальным тестам и ручному запуску на «голом» MinIO.
|
||||
func (c *Client) EnsureBucket(ctx context.Context) error {
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
if err := c.mc.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{}); err != nil {
|
||||
// Гонка двух инициализаторов: бакет уже создан соседом.
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
if code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Короткий таймаут: readiness не должна висеть.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil || !ok {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put кладёт объект известного размера. r должен уметь Seek (файл или bytes.Reader):
|
||||
// тогда minio-go отправляет тело одним запросом без буферизации в памяти.
|
||||
func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
// Один PUT для файлов до лимита lab4 (10 MiB): multipart не нужен.
|
||||
DisableMultipart: true,
|
||||
})
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// Get открывает объект на чтение. Существование проверяется сразу (Stat), чтобы HTTP-слой
|
||||
// успел вернуть 404/503 до отправки заголовков 200.
|
||||
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, classify(err)
|
||||
}
|
||||
if _, err := obj.Stat(); err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, classify(err)
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// Stat возвращает метаданные объекта или ErrNotFound.
|
||||
func (c *Client) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
st, err := c.mc.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete удаляет объект. Отсутствие объекта — не ошибка (S3 DELETE идемпотентен).
|
||||
func (c *Client) Delete(ctx context.Context, key string) error {
|
||||
err := c.mc.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{})
|
||||
if err != nil && errors.Is(classify(err), ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// ListKeys возвращает все объекты с префиксом (рекурсивно). Для reconciler:
|
||||
// стоимость обхода — O(число объектов), память — по записи на объект.
|
||||
func (c *Client) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
var out []ObjectInfo
|
||||
for o := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return nil, classify(o.Err)
|
||||
}
|
||||
out = append(out, ObjectInfo{Key: o.Key, Size: o.Size, LastModified: o.LastModified})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// classify сводит ошибки minio-go к ErrNotFound/ErrUnavailable. Текст исходной ошибки
|
||||
// наружу не возвращаем: в нём могут быть endpoint и имя бакета.
|
||||
func classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return ErrNotFound
|
||||
}
|
||||
if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound &&
|
||||
minio.ToErrorResponse(err).Code != "NoSuchBucket" {
|
||||
return ErrNotFound
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
+61
-62
@@ -1,7 +1,5 @@
|
||||
// Package config читает настройки процесса из окружения.
|
||||
//
|
||||
// Для lab4 добавлены S3_* и лимиты вложений.
|
||||
//
|
||||
// Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose.
|
||||
// Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом:
|
||||
// тогда в переменной лежит путь, а не сам секрет.
|
||||
@@ -28,21 +26,28 @@ type Config struct {
|
||||
RunMigrations bool
|
||||
IdempotencyTTL time.Duration
|
||||
|
||||
// Лимиты вложений (lab4). Контракт: 10 MiB и 40 млн пикселей.
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
// ReconcileGrace — минимальный возраст объекта/строки, прежде чем reconciler их тронет.
|
||||
ReconcileGrace time.Duration
|
||||
}
|
||||
// --- lab4: объектное хранилище (S3-совместимое, MinIO) ---
|
||||
|
||||
// S3 — параметры подключения к S3-совместимому хранилищу.
|
||||
type S3 struct {
|
||||
Endpoint string
|
||||
UseSSL bool
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
// S3Endpoint — URL S3 API внутри сети Compose (http://minio:9000).
|
||||
S3Endpoint string
|
||||
// S3Region — для SigV4 нужен любой регион; у MinIO по умолчанию us-east-1.
|
||||
S3Region string
|
||||
// S3Bucket — приватный bucket с оригиналами вложений.
|
||||
S3Bucket string
|
||||
// S3AccessKey/S3SecretKey — НЕ root MinIO, а отдельный пользователь messenger-api
|
||||
// с политикой только на этот bucket (создаётся сервисом minio-init).
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
// S3ForcePathStyle — path-style адресация (http://minio:9000/bucket/key).
|
||||
// У MinIO в Compose нет wildcard-DNS для bucket.minio, поэтому virtual-hosted не работает.
|
||||
S3ForcePathStyle bool
|
||||
// S3OrphanGrace — «льготный период» reconciler: объект без строки в БД младше этого
|
||||
// возраста считается ещё загружаемым (PUT уже был, INSERT ещё не успел) и не трогается.
|
||||
S3OrphanGrace time.Duration
|
||||
// UploadMaxConcurrency — сколько загрузок одна реплика буферизует в RAM одновременно.
|
||||
// Остальные ждут в очереди (см. api.Server.uploadSlots), поэтому пик памяти ограничен
|
||||
// сверху UploadMaxConcurrency * 10 MiB, а не числом клиентов.
|
||||
UploadMaxConcurrency int
|
||||
}
|
||||
|
||||
// Load собирает Config. Пустой URL без файла — ошибка запуска, а не тихий дефолт на чужой хост.
|
||||
@@ -84,6 +89,12 @@ func Load() (Config, error) {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
if err := loadS3(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
// X-Instance-Id стабилен на жизнь процесса. В Compose hostname = id контейнера,
|
||||
// поэтому stop-one.sh сопоставляет TARGET_INSTANCE_ID с Config.Hostname.
|
||||
cfg.InstanceID = strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
||||
if cfg.InstanceID == "" {
|
||||
host, herr := os.Hostname()
|
||||
@@ -93,47 +104,47 @@ func Load() (Config, error) {
|
||||
cfg.InstanceID = host
|
||||
}
|
||||
|
||||
cfg.MaxUploadBytes, err = getenvInt64("MAX_UPLOAD_BYTES", 10485760, 1, 10485760)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.MaxImagePixels, err = getenvInt64("MAX_IMAGE_PIXELS", 40000000, 1, 40000000)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
graceSec, err := getenvInt64("S3_RECONCILE_GRACE_SECONDS", 60, 0, 7*24*3600)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.ReconcileGrace = time.Duration(graceSec) * time.Second
|
||||
|
||||
// Миграции по умолчанию выключены у API-реплик: их гоняет одноразовый сервис migrate.
|
||||
// Для локальных тестов и -migrate флага включается явно.
|
||||
cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS"))
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadS3 читает настройки S3. Ключи — из S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY
|
||||
// либо из файлов *_FILE. Пустые ключи — ошибка запуска API (migrate без S3 обходится).
|
||||
func LoadS3() (S3, error) {
|
||||
var (
|
||||
c S3
|
||||
err error
|
||||
)
|
||||
c.Endpoint = getenv("S3_ENDPOINT", "minio:9000")
|
||||
// Endpoint может прийти со схемой http:// — minio-go ждёт host:port.
|
||||
c.Endpoint = strings.TrimPrefix(c.Endpoint, "https://")
|
||||
c.Endpoint = strings.TrimPrefix(c.Endpoint, "http://")
|
||||
c.Region = getenv("S3_REGION", "us-east-1")
|
||||
c.Bucket = getenv("S3_BUCKET", "messenger-attachments")
|
||||
c.UseSSL = truthy(os.Getenv("S3_USE_SSL"))
|
||||
c.AccessKey, err = getenvOrFile("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return c, err
|
||||
// loadS3 читает S3_* переменные. Ключи, как и DATABASE_URL, можно передать файлом
|
||||
// (S3_ACCESS_KEY_FILE / S3_SECRET_KEY_FILE): так секрет не попадает в `docker inspect`.
|
||||
// Пустой endpoint/ключ — ошибка запуска: тихий дефолт на «какой-нибудь» S3 опаснее падения.
|
||||
func loadS3(cfg *Config) error {
|
||||
var err error
|
||||
cfg.S3Endpoint = strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
|
||||
if cfg.S3Endpoint == "" {
|
||||
return fmt.Errorf("set S3_ENDPOINT")
|
||||
}
|
||||
c.SecretKey, err = getenvOrFile("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
|
||||
cfg.S3Region = getenv("S3_REGION", "us-east-1")
|
||||
cfg.S3Bucket = getenv("S3_BUCKET", "messenger")
|
||||
cfg.S3AccessKey, err = getenvOrFile("S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return c, err
|
||||
return err
|
||||
}
|
||||
return c, nil
|
||||
cfg.S3SecretKey, err = getenvOrFile("S3_SECRET_KEY", "S3_SECRET_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// По умолчанию path-style включён: для MinIO в Compose это единственный рабочий вариант.
|
||||
cfg.S3ForcePathStyle = truthy(getenv("S3_FORCE_PATH_STYLE", "1"))
|
||||
|
||||
// Grace по умолчанию 300 с: с запасом больше любой реальной загрузки (таймаут PUT 10 с)
|
||||
// и задержки между PUT и COMMIT. 0 допустим (удалять сразу) — нужен только тестам.
|
||||
graceSec, err := strconv.Atoi(getenv("S3_ORPHAN_GRACE_SECONDS", "300"))
|
||||
if err != nil || graceSec < 0 || graceSec > 7*24*3600 {
|
||||
return fmt.Errorf("invalid S3_ORPHAN_GRACE_SECONDS")
|
||||
}
|
||||
cfg.S3OrphanGrace = time.Duration(graceSec) * time.Second
|
||||
|
||||
cfg.UploadMaxConcurrency, err = strconv.Atoi(getenv("UPLOAD_MAX_CONCURRENCY", "4"))
|
||||
if err != nil || cfg.UploadMaxConcurrency < 1 || cfg.UploadMaxConcurrency > 64 {
|
||||
return fmt.Errorf("invalid UPLOAD_MAX_CONCURRENCY")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Addr — адрес Listen, обычно 0.0.0.0:8080 внутри контейнера.
|
||||
@@ -148,18 +159,6 @@ func getenv(key, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getenvInt64(key string, fallback, lo, hi int64) (int64, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(key))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || n < lo || n > hi {
|
||||
return 0, fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func getenvOrFile(directKey, fileKey string) (string, error) {
|
||||
if v := strings.TrimSpace(os.Getenv(directKey)); v != "" {
|
||||
return v, nil
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
// Package objectstore — тонкая обёртка над aws-sdk-go-v2 для приватного S3-bucket (MinIO).
|
||||
//
|
||||
// Зачем отдельный пакет:
|
||||
// - HTTP-слой и reconciler работают с узким набором операций (Put/Get/Delete/Head/List/
|
||||
// EnsureBucket/Ping) и с двумя доменными ошибками, а не с типами SDK;
|
||||
// - все таймауты и настройки «совместимости с MinIO» собраны в одном месте;
|
||||
// - наружу (в ответ клиенту, в лог) не уходят тексты ошибок SDK: в них бывают
|
||||
// endpoint, имя bucket и фрагменты запроса.
|
||||
//
|
||||
// Байты вложений живут ТОЛЬКО здесь. Ни локальный диск API-реплики, ни PostgreSQL
|
||||
// оригиналов не хранят: любая реплика после остановки соседней отдаёт тот же файл.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
)
|
||||
|
||||
// Доменные ошибки. HTTP-слой различает «нет объекта» и «хранилище недоступно».
|
||||
var (
|
||||
// ErrNotFound — объекта (или bucket) нет.
|
||||
ErrNotFound = errors.New("object not found")
|
||||
// ErrUnavailable — S3 недоступен, таймаут, отказ в доступе или любая иная ошибка
|
||||
// транспорта. Клиенту это всегда 503: он не должен видеть подробности.
|
||||
ErrUnavailable = errors.New("object store unavailable")
|
||||
)
|
||||
|
||||
// Таймауты операций. Подобраны под HAProxy (timeout server 15s): S3-запрос обязан
|
||||
// закончиться раньше, чем балансировщик оборвёт клиента, иначе получим 504 вместо
|
||||
// управляемого 503.
|
||||
const (
|
||||
pingTimeout = 700 * time.Millisecond // /health/ready опрашивается раз в секунду
|
||||
putTimeout = 10 * time.Second // до 10 MiB по локальной сети
|
||||
smallOpTimeout = 3 * time.Second // Head/Delete
|
||||
listTimeout = 10 * time.Second // страница List до 1000 ключей
|
||||
)
|
||||
|
||||
// Config — параметры подключения. Секреты приходят из окружения, в лог не пишутся.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
ForcePathStyle bool
|
||||
}
|
||||
|
||||
// Store — клиент одного bucket. Безопасен для конкурентного использования.
|
||||
type Store struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// ObjectInfo — метаданные объекта (из Head или List).
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string // пусто для List: он тип не возвращает
|
||||
LastModified time.Time
|
||||
ETag string
|
||||
}
|
||||
|
||||
// ListPage — одна страница List. NextToken пуст, когда страниц больше нет.
|
||||
type ListPage struct {
|
||||
Objects []ObjectInfo
|
||||
NextToken string
|
||||
}
|
||||
|
||||
// New создаёт клиента. Сетевых вызовов не делает: доступность проверяют Ping/EnsureBucket.
|
||||
func New(cfg Config) (*Store, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
|
||||
return nil, fmt.Errorf("objectstore: endpoint, bucket and credentials are required")
|
||||
}
|
||||
region := cfg.Region
|
||||
if region == "" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
|
||||
// Собственный HTTP-клиент: короткий dial-таймаут нужен, чтобы остановленный MinIO
|
||||
// давал отказ за ~2 с, а не за системные минуты. ResponseHeaderTimeout защищает от
|
||||
// «подвисшего» сервера, который принял соединение, но не отвечает.
|
||||
httpClient := awshttp.NewBuildableClient().
|
||||
WithDialerOptions(func(d *net.Dialer) {
|
||||
d.Timeout = 2 * time.Second
|
||||
d.KeepAlive = 30 * time.Second
|
||||
}).
|
||||
WithTransportOptions(func(tr *http.Transport) {
|
||||
tr.ResponseHeaderTimeout = 8 * time.Second
|
||||
tr.MaxIdleConnsPerHost = 16
|
||||
tr.IdleConnTimeout = 60 * time.Second
|
||||
})
|
||||
|
||||
awsCfg := aws.Config{
|
||||
Region: region,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
HTTPClient: httpClient,
|
||||
// Две попытки вместо трёх по умолчанию: повтор нужен для редких обрывов,
|
||||
// но при лежащем S3 мы хотим быстро ответить 503, а не копить backoff.
|
||||
RetryMaxAttempts: 2,
|
||||
}
|
||||
client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(cfg.Endpoint)
|
||||
// MinIO в Compose доступен только по имени хоста minio — bucket в имени хоста
|
||||
// (virtual-hosted) невозможен, поэтому path-style.
|
||||
o.UsePathStyle = cfg.ForcePathStyle
|
||||
// Свежие версии SDK по умолчанию добавляют CRC32-trailer ко всем PUT. Для
|
||||
// не-AWS бэкендов это источник несовместимостей; нам достаточно обычной SigV4
|
||||
// подписи полезной нагрузки (тело — seekable bytes.Reader).
|
||||
o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
|
||||
o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired
|
||||
})
|
||||
return &Store{client: client, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
// Bucket возвращает имя bucket (для логов bootstrap; клиенту не отдаётся).
|
||||
func (s *Store) Bucket() string { return s.bucket }
|
||||
|
||||
// Ping — проверка для /health/ready: HeadBucket. Требует s3:ListBucket, которое
|
||||
// есть в политике messenger-api. Короткий таймаут: readiness не должен висеть.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, pingTimeout)
|
||||
defer cancel()
|
||||
if _, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)}); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureBucket идемпотентно гарантирует существование bucket.
|
||||
//
|
||||
// Основной путь создания — сервис minio-init (root-учётка). API-пользователь по политике
|
||||
// НЕ может создавать buckets, поэтому здесь: HeadBucket → если нет, пробуем CreateBucket
|
||||
// (сработает на S3-бэкендах с более широкими правами, например в локальном dev) и
|
||||
// «уже существует/уже наш» считаем успехом. Повторный вызов безопасен.
|
||||
func (s *Store) EnsureBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !isNotFound(err) {
|
||||
return fmt.Errorf("head bucket: %w", classify(err))
|
||||
}
|
||||
_, err = s.client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(s.bucket)})
|
||||
if err != nil {
|
||||
var owned *types.BucketAlreadyOwnedByYou
|
||||
var exists *types.BucketAlreadyExists
|
||||
if errors.As(err, &owned) || errors.As(err, &exists) {
|
||||
return nil // гонка с другой репликой/minio-init: bucket уже есть
|
||||
}
|
||||
return fmt.Errorf("create bucket (запустите minio-init): %w", classify(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put кладёт объект целиком. body должен быть seekable (bytes.Reader): SDK тогда сам
|
||||
// считает хеш полезной нагрузки для SigV4 и умеет перечитать тело при retry.
|
||||
// Объект без ACL: bucket приватный, анонимный доступ запрещён политикой.
|
||||
func (s *Store) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, putTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
})
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// Get открывает поток объекта. Вызывающий ОБЯЗАН закрыть ReadCloser.
|
||||
// Таймаут здесь не навешиваем: контекст живёт, пока тело стримится клиенту
|
||||
// (его ограничивает ctx запроса и WriteTimeout HTTP-сервера).
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
info := ObjectInfo{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(out.ContentLength),
|
||||
ContentType: aws.ToString(out.ContentType),
|
||||
LastModified: aws.ToTime(out.LastModified),
|
||||
ETag: aws.ToString(out.ETag),
|
||||
}
|
||||
return out.Body, info, nil
|
||||
}
|
||||
|
||||
// Head возвращает метаданные без тела. ErrNotFound — объекта нет.
|
||||
func (s *Store) Head(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
out, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(out.ContentLength),
|
||||
ContentType: aws.ToString(out.ContentType),
|
||||
LastModified: aws.ToTime(out.LastModified),
|
||||
ETag: aws.ToString(out.ETag),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Delete удаляет объект. Отсутствующий объект — не ошибка (S3 DeleteObject идемпотентен),
|
||||
// что важно и для компенсации после сбоя PG, и для повторных запусков reconciler.
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil && isNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// List возвращает одну страницу ключей с префиксом prefix в лексикографическом порядке
|
||||
// (так S3 отдаёт ListObjectsV2). token — из предыдущей страницы, пустой для первой.
|
||||
// Именно порядок позволяет reconciler сливать листинг с отсортированной выборкой из БД
|
||||
// (merge-join) без загрузки всех ключей в память.
|
||||
func (s *Store) List(ctx context.Context, prefix, token string, maxKeys int32) (ListPage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, listTimeout)
|
||||
defer cancel()
|
||||
in := &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
MaxKeys: aws.Int32(maxKeys),
|
||||
}
|
||||
if token != "" {
|
||||
in.ContinuationToken = aws.String(token)
|
||||
}
|
||||
out, err := s.client.ListObjectsV2(ctx, in)
|
||||
if err != nil {
|
||||
return ListPage{}, classify(err)
|
||||
}
|
||||
page := ListPage{Objects: make([]ObjectInfo, 0, len(out.Contents))}
|
||||
for _, o := range out.Contents {
|
||||
page.Objects = append(page.Objects, ObjectInfo{
|
||||
Key: aws.ToString(o.Key),
|
||||
Size: aws.ToInt64(o.Size),
|
||||
LastModified: aws.ToTime(o.LastModified),
|
||||
ETag: aws.ToString(o.ETag),
|
||||
})
|
||||
}
|
||||
if aws.ToBool(out.IsTruncated) {
|
||||
page.NextToken = aws.ToString(out.NextContinuationToken)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// classify сводит ошибки SDK к двум доменным. Исходный текст не пробрасываем.
|
||||
func classify(err error) error {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case isNotFound(err):
|
||||
return ErrNotFound
|
||||
default:
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
// isNotFound распознаёт «нет объекта/bucket» по типам и кодам ответа S3.
|
||||
// HeadObject отдаёт безымянный 404 (types.NotFound), GetObject — NoSuchKey.
|
||||
func isNotFound(err error) bool {
|
||||
var noKey *types.NoSuchKey
|
||||
var notFound *types.NotFound
|
||||
var noBucket *types.NoSuchBucket
|
||||
if errors.As(err, &noKey) || errors.As(err, ¬Found) || errors.As(err, &noBucket) {
|
||||
return true
|
||||
}
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchKey", "NotFound", "NoSuchBucket":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// Package reconcile — сверка двух хранилищ вложений: S3 (байты) и PostgreSQL (метаданные).
|
||||
//
|
||||
// Почему сверка нужна вообще. Общей транзакции у S3 и PostgreSQL нет. Загрузка делает
|
||||
// PUT в S3, затем INSERT в БД (см. internal/api/attachments.go). Между шагами процесс может
|
||||
// умереть, а компенсирующее удаление — не сработать. Получаются два вида расхождений:
|
||||
//
|
||||
// orphan — объект в S3 есть, строки в БД нет. Безвредно для пользователя, но это вечный
|
||||
// мусор и расход места. Лечение: удалить объект, НО только старше grace-периода
|
||||
// (иначе можно снести объект, у которого INSERT ещё «в полёте»).
|
||||
// missing — строка в БД есть, объекта в S3 нет (удалён руками, потерян, сбой диска).
|
||||
// Пользователь получит ошибку при скачивании. Автоматически данные не вернуть,
|
||||
// поэтому по умолчанию только ОТЧЁТ. Опционально (PruneMissing) удаляется строка,
|
||||
// которая одновременно старая И неиспользуемая; «свежие» и «используемые»
|
||||
// сообщениями вложения не удаляются никогда.
|
||||
//
|
||||
// Алгоритм — merge-join двух ОТСОРТИРОВАННЫХ потоков (ключи S3 в лексикографическом порядке
|
||||
// и attachments.object_key COLLATE "C" в БД). Обе стороны читаются страницами, поэтому память
|
||||
// O(размер страницы), а не O(число объектов), а стоимость — O(n) по числу объектов
|
||||
// плюс HEAD только для редких кандидатов в missing.
|
||||
//
|
||||
// Безопасность:
|
||||
// - dry-run (DryRun) ничего не удаляет и не изменяет: только лог и отчёт;
|
||||
// - повторный запуск идемпотентен (после исправления расхождений находит 0);
|
||||
// - ключи вне схемы attachments/{uuid}/{uuid} никогда не удаляются;
|
||||
// - перед удалением orphan — повторная проверка строки в БД (сужает окно гонки);
|
||||
// - строки, на которые ссылаются сообщения, защищены ещё и внешним ключом PostgreSQL.
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/objectstore"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
// KeyPrefix — единственный префикс, который обходит reconciler.
|
||||
const KeyPrefix = "attachments/"
|
||||
|
||||
// pageSize — размер страницы и для S3 (максимум ListObjectsV2 — 1000), и для БД.
|
||||
const defaultPageSize = 1000
|
||||
|
||||
// maxSamples ограничивает число ключей-примеров в отчёте, чтобы вывод не разрастался.
|
||||
const maxSamples = 50
|
||||
|
||||
// Options — параметры запуска.
|
||||
type Options struct {
|
||||
// DryRun — ничего не менять, только сообщить, что было бы сделано.
|
||||
DryRun bool
|
||||
// Grace — минимальный возраст orphan-объекта (по LastModified в S3) и «неиспользуемой»
|
||||
// строки (по created_at), после которого их можно трогать. Берётся из S3_ORPHAN_GRACE_SECONDS.
|
||||
Grace time.Duration
|
||||
// PruneMissing — удалять строки без объекта, если они старше Grace и не прикреплены
|
||||
// ни к одному сообщению. Без флага missing только отчётность.
|
||||
PruneMissing bool
|
||||
// PageSize — для тестов; по умолчанию 1000.
|
||||
PageSize int
|
||||
// Now — для тестов; по умолчанию time.Now.
|
||||
Now func() time.Time
|
||||
// Logf — построчный лог (по умолчанию молчит). В main — log.Printf.
|
||||
Logf func(format string, args ...any)
|
||||
}
|
||||
|
||||
// Report — итог запуска. Печатается в JSON и годится как evidence.
|
||||
type Report struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GraceSeconds float64 `json:"grace_seconds"`
|
||||
PruneMissing bool `json:"prune_missing"`
|
||||
|
||||
// Стоимость обхода.
|
||||
S3ObjectsScanned int `json:"s3_objects_scanned"`
|
||||
DBRowsScanned int `json:"db_rows_scanned"`
|
||||
S3ListCalls int `json:"s3_list_calls"`
|
||||
DBPages int `json:"db_pages"`
|
||||
HeadCalls int `json:"s3_head_calls"`
|
||||
DeleteCalls int `json:"s3_delete_calls"`
|
||||
DurationMs int64 `json:"duration_ms"`
|
||||
|
||||
Matched int `json:"matched"` // и объект, и строка
|
||||
|
||||
// Orphan: объект без строки.
|
||||
OrphansFound int `json:"orphans_found"` // старше grace, подлежат удалению
|
||||
OrphansDeleted int `json:"orphans_deleted"` // реально удалено (0 в dry-run)
|
||||
OrphansFresh int `json:"orphans_fresh"` // моложе grace — не тронуты
|
||||
OrphansRaced int `json:"orphans_raced"` // перед удалением строка появилась — не тронуты
|
||||
UnknownKeys int `json:"unknown_keys"` // ключ вне схемы attachments/{uuid}/{uuid} — не тронуты
|
||||
OrphanSampleKey []string `json:"orphan_sample_keys,omitempty"`
|
||||
|
||||
// Missing: строка без объекта.
|
||||
MissingFound int `json:"missing_found"` // подтверждено HEAD
|
||||
MissingUsed int `json:"missing_used"` // прикреплено к сообщению — ТРЕБУЕТ внимания, не удаляется
|
||||
MissingFresh int `json:"missing_fresh"` // моложе grace — не тронуты
|
||||
MissingStale int `json:"missing_stale"` // старые и неиспользуемые — кандидаты на prune
|
||||
MissingPruned int `json:"missing_pruned"` // строк удалено (0 в dry-run и без PruneMissing)
|
||||
MissingRaced int `json:"missing_raced"` // HEAD нашёл объект — ложная тревога из-за гонки
|
||||
MissingSample []string `json:"missing_sample_keys,omitempty"`
|
||||
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
// Reconciler — зависимости.
|
||||
type Reconciler struct {
|
||||
DB *store.Store
|
||||
Objects *objectstore.Store
|
||||
Opts Options
|
||||
}
|
||||
|
||||
// Run выполняет один проход. Ошибка хранилища (S3/PG недоступны) прерывает проход:
|
||||
// частичный результат без явной причины хуже честной остановки; отчёт возвращается всегда.
|
||||
func (rc *Reconciler) Run(ctx context.Context) (*Report, error) {
|
||||
opts := rc.Opts
|
||||
if opts.PageSize <= 0 || opts.PageSize > defaultPageSize {
|
||||
opts.PageSize = defaultPageSize
|
||||
}
|
||||
if opts.Now == nil {
|
||||
opts.Now = time.Now
|
||||
}
|
||||
if opts.Logf == nil {
|
||||
opts.Logf = func(string, ...any) {}
|
||||
}
|
||||
rep := &Report{
|
||||
DryRun: opts.DryRun,
|
||||
GraceSeconds: opts.Grace.Seconds(),
|
||||
PruneMissing: opts.PruneMissing,
|
||||
}
|
||||
start := time.Now()
|
||||
defer func() { rep.DurationMs = time.Since(start).Milliseconds() }()
|
||||
|
||||
run := &run{rc: rc, opts: opts, rep: rep}
|
||||
err := run.mergeJoin(ctx)
|
||||
return rep, err
|
||||
}
|
||||
|
||||
type run struct {
|
||||
rc *Reconciler
|
||||
opts Options
|
||||
rep *Report
|
||||
}
|
||||
|
||||
// s3Cursor / dbCursor — «ленивые» итераторы по страницам с peek/advance.
|
||||
type s3Cursor struct {
|
||||
page []objectstore.ObjectInfo
|
||||
idx int
|
||||
token string
|
||||
begun bool
|
||||
done bool
|
||||
}
|
||||
|
||||
type dbCursor struct {
|
||||
page []store.AttachmentRef
|
||||
idx int
|
||||
after string
|
||||
done bool
|
||||
}
|
||||
|
||||
func (r *run) peekS3(ctx context.Context, c *s3Cursor) (*objectstore.ObjectInfo, error) {
|
||||
for c.idx >= len(c.page) {
|
||||
if c.done {
|
||||
return nil, nil
|
||||
}
|
||||
if c.begun && c.token == "" {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
p, err := r.rc.Objects.List(ctx, KeyPrefix, c.token, int32(r.opts.PageSize))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list s3: %w", err)
|
||||
}
|
||||
r.rep.S3ListCalls++
|
||||
c.begun, c.page, c.idx, c.token = true, p.Objects, 0, p.NextToken
|
||||
if len(p.Objects) == 0 && p.NextToken == "" {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return &c.page[c.idx], nil
|
||||
}
|
||||
|
||||
func (r *run) peekDB(ctx context.Context, c *dbCursor) (*store.AttachmentRef, error) {
|
||||
for c.idx >= len(c.page) {
|
||||
if c.done {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := r.rc.DB.ListAttachmentRefsAfter(ctx, c.after, r.opts.PageSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list db: %w", err)
|
||||
}
|
||||
r.rep.DBPages++
|
||||
if len(rows) == 0 {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
c.page, c.idx = rows, 0
|
||||
c.after = rows[len(rows)-1].ObjectKey
|
||||
}
|
||||
return &c.page[c.idx], nil
|
||||
}
|
||||
|
||||
func (r *run) mergeJoin(ctx context.Context) error {
|
||||
s3c, dbc := &s3Cursor{}, &dbCursor{}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
o, err := r.peekS3(ctx, s3c)
|
||||
if err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
d, err := r.peekDB(ctx, dbc)
|
||||
if err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
if o == nil && d == nil {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case d == nil || (o != nil && o.Key < d.ObjectKey):
|
||||
// Ключ есть в S3, а в БД его нет → кандидат в orphan.
|
||||
r.rep.S3ObjectsScanned++
|
||||
if err := r.handleOrphanCandidate(ctx, *o); err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
s3c.idx++
|
||||
case o == nil || d.ObjectKey < o.Key:
|
||||
// Строка есть, объекта нет → кандидат в missing.
|
||||
r.rep.DBRowsScanned++
|
||||
if err := r.handleMissingCandidate(ctx, *d); err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
dbc.idx++
|
||||
default:
|
||||
// Ключи равны: всё согласовано.
|
||||
r.rep.S3ObjectsScanned++
|
||||
r.rep.DBRowsScanned++
|
||||
r.rep.Matched++
|
||||
s3c.idx++
|
||||
dbc.idx++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *run) handleOrphanCandidate(ctx context.Context, o objectstore.ObjectInfo) error {
|
||||
// Чужие/неожиданные ключи не трогаем вообще: reconciler знает только свою схему ключей.
|
||||
if !validAttachmentKey(o.Key) {
|
||||
r.rep.UnknownKeys++
|
||||
r.opts.Logf("SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): %s", o.Key)
|
||||
return nil
|
||||
}
|
||||
age := r.opts.Now().Sub(o.LastModified)
|
||||
if age < r.opts.Grace {
|
||||
// PUT был недавно: INSERT мог ещё не закоммититься. Не трогаем.
|
||||
r.rep.OrphansFresh++
|
||||
r.opts.Logf("SKIP fresh orphan (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, o.Key)
|
||||
return nil
|
||||
}
|
||||
// Повторная проверка непосредственно перед удалением: за время прохода строка
|
||||
// могла появиться (долгая загрузка, медленный INSERT).
|
||||
exists, err := r.rc.DB.AttachmentKeyExists(ctx, o.Key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("recheck db: %w", err)
|
||||
}
|
||||
if exists {
|
||||
r.rep.OrphansRaced++
|
||||
return nil
|
||||
}
|
||||
r.rep.OrphansFound++
|
||||
r.sample(&r.rep.OrphanSampleKey, o.Key)
|
||||
if r.opts.DryRun {
|
||||
r.opts.Logf("DRY-RUN would delete orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key)
|
||||
return nil
|
||||
}
|
||||
r.rep.DeleteCalls++
|
||||
if err := r.rc.Objects.Delete(ctx, o.Key); err != nil {
|
||||
return fmt.Errorf("delete orphan: %w", err)
|
||||
}
|
||||
r.rep.OrphansDeleted++
|
||||
r.opts.Logf("DELETED orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *run) handleMissingCandidate(ctx context.Context, d store.AttachmentRef) error {
|
||||
// Подтверждаем HEAD: листинг S3 и страница БД читались в разные моменты, поэтому
|
||||
// «нет в листинге» ещё не значит «нет в S3» (загрузка могла завершиться между ними).
|
||||
r.rep.HeadCalls++
|
||||
_, err := r.rc.Objects.Head(ctx, d.ObjectKey)
|
||||
switch {
|
||||
case err == nil:
|
||||
r.rep.MissingRaced++
|
||||
return nil
|
||||
case errors.Is(err, objectstore.ErrNotFound):
|
||||
// действительно отсутствует — идём дальше
|
||||
default:
|
||||
return fmt.Errorf("head: %w", err)
|
||||
}
|
||||
|
||||
r.rep.MissingFound++
|
||||
r.sample(&r.rep.MissingSample, d.ObjectKey)
|
||||
age := r.opts.Now().Sub(d.CreatedAt)
|
||||
switch {
|
||||
case d.Used:
|
||||
// Вложение прикреплено к сообщению, а байт нет: потеря данных. Автоматически не чиним
|
||||
// и не удаляем строку (иначе сообщение осталось бы со ссылкой в никуда).
|
||||
r.rep.MissingUsed++
|
||||
r.opts.Logf("ALERT used attachment lost its object (id=%s, не удаляется): %s", d.ID, d.ObjectKey)
|
||||
case age < r.opts.Grace:
|
||||
r.rep.MissingFresh++
|
||||
r.opts.Logf("SKIP fresh missing (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, d.ObjectKey)
|
||||
default:
|
||||
r.rep.MissingStale++
|
||||
switch {
|
||||
case r.opts.DryRun:
|
||||
r.opts.Logf("DRY-RUN missing object, unused stale row (id=%s)%s: %s", d.ID, pruneHint(r.opts.PruneMissing), d.ObjectKey)
|
||||
case !r.opts.PruneMissing:
|
||||
r.opts.Logf("REPORT missing object, unused stale row (id=%s), prune выключен: %s", d.ID, d.ObjectKey)
|
||||
default:
|
||||
// Удаление защищено условиями created_at < cutoff и NOT EXISTS ссылок в SQL.
|
||||
deleted, err := r.rc.DB.DeleteUnusedAttachment(ctx, d.ID, r.opts.Now().Add(-r.opts.Grace))
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune row: %w", err)
|
||||
}
|
||||
if deleted {
|
||||
r.rep.MissingPruned++
|
||||
r.opts.Logf("PRUNED row without object (id=%s): %s", d.ID, d.ObjectKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneHint(prune bool) string {
|
||||
if prune {
|
||||
return " would be pruned"
|
||||
}
|
||||
return " (prune off, report only)"
|
||||
}
|
||||
|
||||
func (r *run) sample(dst *[]string, key string) {
|
||||
if len(*dst) < maxSamples {
|
||||
*dst = append(*dst, key)
|
||||
}
|
||||
}
|
||||
|
||||
// validAttachmentKey — ключ строго вида attachments/{uuid}/{uuid} в каноническом написании.
|
||||
func validAttachmentKey(key string) bool {
|
||||
rest, ok := cutPrefix(key, KeyPrefix)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
var chat, att string
|
||||
for i := 0; i < len(rest); i++ {
|
||||
if rest[i] == '/' {
|
||||
chat, att = rest[:i], rest[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
if chat == "" || att == "" {
|
||||
return false
|
||||
}
|
||||
c, err1 := uuid.Parse(chat)
|
||||
a, err2 := uuid.Parse(att)
|
||||
return err1 == nil && err2 == nil && c.String() == chat && a.String() == att
|
||||
}
|
||||
|
||||
func cutPrefix(s, prefix string) (string, bool) {
|
||||
if len(s) >= len(prefix) && s[:len(prefix)] == prefix {
|
||||
return s[len(prefix):], true
|
||||
}
|
||||
return s, false
|
||||
}
|
||||
+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