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