forked from mtusi2026/mtusi2026lab5
141 lines
5.9 KiB
Go
141 lines
5.9 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
|
)
|
|
|
|
// routeUploadAttachment освобождён от общего лимита тела: свой лимит применяется в сервисе, после
|
|
// аутентификации и проверки доступа.
|
|
const routeUploadAttachment = "/api/v1/chats/:chat_id/attachments"
|
|
|
|
// transferTimeout — предел на передачу одного файла. Общие таймауты сервера (10 с) рассчитаны на
|
|
// JSON и оборвали бы загрузку 10 МиБ на медленном канале. Предел обязателен: иначе медленный клиент
|
|
// занимал бы слот загрузки неограниченно долго.
|
|
const transferTimeout = 60 * time.Second
|
|
|
|
type attachmentsHandler struct {
|
|
attachments service.AttachmentsService
|
|
}
|
|
|
|
// rejectedBodyDrainLimit — сколько байт отклонённой загрузки дочитывается впустую. Клиент обычно
|
|
// сначала отправляет всё тело и только потом читает ответ: если перестать читать, он зависнет и
|
|
// вместо 413 получит обрыв. Дочитывание идёт в никуда, поэтому память не расходует, а его время
|
|
// ограничено transferTimeout. Тело больше этого предела приводит к закрытию соединения.
|
|
const rejectedBodyDrainLimit = 64 << 20
|
|
|
|
func extendDeadlines(c echo.Context) {
|
|
rc := http.NewResponseController(c.Response())
|
|
deadline := time.Now().Add(transferTimeout)
|
|
// Ошибка значит, что соединение не поддерживает дедлайны: тогда действуют общие таймауты.
|
|
_ = rc.SetReadDeadline(deadline)
|
|
_ = rc.SetWriteDeadline(deadline)
|
|
}
|
|
|
|
// uploadTransfer стоит снаружи аутентификации, поэтому покрывает и отказы 401. Небольшой ответ об
|
|
// ошибке остаётся в буфере сервера и уходит клиенту после дочитывания.
|
|
func uploadTransfer(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
extendDeadlines(c)
|
|
err := next(c)
|
|
_, _ = io.CopyN(io.Discard, c.Request().Body, rejectedBodyDrainLimit)
|
|
return err
|
|
}
|
|
}
|
|
|
|
func (h *attachmentsHandler) upload(c echo.Context) error {
|
|
req := c.Request()
|
|
// Несколько filename неоднозначны: пустое значение сервис отклонит как неверное имя.
|
|
var filename string
|
|
if values := c.QueryParams()["filename"]; len(values) == 1 {
|
|
filename = values[0]
|
|
}
|
|
att, err := h.attachments.Upload(req.Context(), service.UploadInput{
|
|
CallerID: c.Get(middleware.AuthUserIDKey).(string),
|
|
ChatID: c.Param("chat_id"),
|
|
Filename: filename,
|
|
ContentType: req.Header.Get(echo.HeaderContentType),
|
|
ContentLength: req.ContentLength,
|
|
Body: req.Body,
|
|
})
|
|
if err != nil {
|
|
return WriteError(c, err)
|
|
}
|
|
return c.JSON(http.StatusAccepted, toAttachmentResponse(att))
|
|
}
|
|
|
|
func (h *attachmentsHandler) get(c echo.Context) error {
|
|
att, err := h.attachments.Get(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"))
|
|
if err != nil {
|
|
return WriteError(c, err)
|
|
}
|
|
return c.JSON(http.StatusOK, toAttachmentResponse(att))
|
|
}
|
|
|
|
func (h *attachmentsHandler) content(c echo.Context) error {
|
|
extendDeadlines(c)
|
|
variant := service.VariantOriginal
|
|
if values, ok := c.QueryParams()["variant"]; ok {
|
|
variant = values[0]
|
|
}
|
|
ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout)
|
|
defer cancel()
|
|
|
|
att, body, err := h.attachments.Content(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"), variant)
|
|
if err != nil {
|
|
return WriteError(c, err)
|
|
}
|
|
defer body.Close()
|
|
|
|
header := c.Response().Header()
|
|
header.Set(echo.HeaderContentLength, strconv.FormatInt(att.SizeBytes, 10))
|
|
// Файл загрузил пользователь: браузер не должен угадывать тип или показывать его как страницу.
|
|
header.Set("X-Content-Type-Options", "nosniff")
|
|
header.Set("Cache-Control", "private, no-store")
|
|
if cd := mime.FormatMediaType("attachment", map[string]string{"filename": att.Filename}); cd != "" {
|
|
header.Set(echo.HeaderContentDisposition, cd)
|
|
} else {
|
|
header.Set(echo.HeaderContentDisposition, "attachment")
|
|
}
|
|
// Обрыв после начала передачи клиент увидит как неполный ответ: длина объявлена заранее.
|
|
return c.Stream(http.StatusOK, att.ContentType, body)
|
|
}
|
|
|
|
func toAttachmentResponse(a domain.Attachment) dto.AttachmentResponse {
|
|
return dto.AttachmentResponse{
|
|
ID: a.ID,
|
|
ChatID: a.ChatID,
|
|
OwnerID: a.OwnerID,
|
|
Filename: a.Filename,
|
|
ContentType: a.ContentType,
|
|
SizeBytes: a.SizeBytes,
|
|
SHA256: a.SHA256,
|
|
Status: a.Status,
|
|
Variants: attachmentVariants(a),
|
|
ErrorCode: a.ErrorCode,
|
|
CreatedAt: dto.NewTimestamp(a.CreatedAt),
|
|
UpdatedAt: dto.NewTimestamp(a.UpdatedAt),
|
|
}
|
|
}
|
|
|
|
func attachmentVariants(a domain.Attachment) []dto.VariantResponse {
|
|
v := []dto.VariantResponse{}
|
|
if a.Status == domain.StatusReady {
|
|
for _, t := range a.Variants {
|
|
v = append(v, dto.VariantResponse{Name: t.Name, ContentType: t.ContentType, SizeBytes: t.SizeBytes, Width: t.Width, Height: t.Height, SHA256: t.SHA256})
|
|
}
|
|
}
|
|
return v
|
|
}
|