forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/blob"
|
||||
"messenger/internal/imagecheck"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
type attachmentJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []struct{} `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (a *API) routeAttachment(w http.ResponseWriter, r *http.Request, rest string) {
|
||||
if _, ok := a.authenticate(w, r); !ok {
|
||||
return
|
||||
}
|
||||
rest = strings.Trim(rest, "/")
|
||||
if rest == "" || strings.Count(rest, "/") > 1 {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
id, content, hasContent := strings.Cut(rest, "/")
|
||||
if hasContent && content != "content" {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
if _, ok := canonicalUUID(id); !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
return
|
||||
}
|
||||
if hasContent {
|
||||
a.downloadAttachment(w, r, id)
|
||||
return
|
||||
}
|
||||
a.getAttachment(w, r, id)
|
||||
}
|
||||
|
||||
func (a *API) uploadAttachment(w http.ResponseWriter, r *http.Request, rawChatID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
chatID, ok := a.chatID(w, r, rawChatID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), chatID, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if !validFilename(filename) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректное имя файла", 0)
|
||||
return
|
||||
}
|
||||
media := ""
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
media = strings.ToLower(strings.TrimSpace(strings.Split(ct, ";")[0]))
|
||||
}
|
||||
if media != "image/png" && media != "image/jpeg" {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен PNG или JPEG", 0)
|
||||
return
|
||||
}
|
||||
// Не отвечаем до чтения: иначе клиент ещё шлёт тело и видит обрыв вместо 413.
|
||||
// Читаем не больше лимита плюс один байт. Лишний байт - отказ, без записи в bucket.
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxUpload+1))
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Загрузка прервана", 0)
|
||||
return
|
||||
}
|
||||
if int64(len(body)) > a.maxUpload {
|
||||
a.fail(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "Файл больше 10 МиБ", 0)
|
||||
return
|
||||
}
|
||||
if len(body) == 0 {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Пустое изображение", 0)
|
||||
return
|
||||
}
|
||||
width, height, err := imagecheck.Inspect(media, body, a.maxPixels)
|
||||
if err != nil {
|
||||
if errors.Is(err, imagecheck.ErrPixels) {
|
||||
a.fail(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "Слишком много пикселей", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Файл не является PNG или JPEG", 0)
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
key, err := newObjectKey()
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
if err := a.blobs.Put(r.Context(), key, media, body); err != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
row, err := a.store.InsertAttachment(r.Context(), store.Attachment{
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Filename: filename,
|
||||
ContentType: media,
|
||||
SizeBytes: int64(len(body)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: key,
|
||||
Width: width,
|
||||
Height: height,
|
||||
})
|
||||
if err != nil {
|
||||
// PUT уже прошёл, COMMIT нет: сразу убираем объект. Если удаление не удалось,
|
||||
// ключ останется сиротой до сверки и не попадёт в ответ 201.
|
||||
if delErr := a.blobs.Delete(r.Context(), key); delErr != nil {
|
||||
a.log.Error("orphan object", "request_id", requestIDFrom(r))
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asAttachment(row))
|
||||
}
|
||||
|
||||
func (a *API) getAttachment(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
row, ok := a.visibleAttachment(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asAttachment(row))
|
||||
}
|
||||
|
||||
func (a *API) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
row, ok := a.visibleAttachment(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
variant := "original"
|
||||
if r.URL.Query().Has("variant") {
|
||||
variant = r.URL.Query().Get("variant")
|
||||
}
|
||||
switch variant {
|
||||
case "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
default:
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный вариант", 0)
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
rc, err := a.blobs.Get(r.Context(), row.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, blob.ErrNotFound) {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
w.Header().Set("Content-Type", row.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(row.SizeBytes, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, rc); err != nil {
|
||||
a.log.Error("download", "request_id", requestIDFrom(r))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) visibleAttachment(w http.ResponseWriter, r *http.Request, rawID string) (store.Attachment, bool) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
id, ok := canonicalUUID(rawID)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
row, err := a.store.AttachmentVisible(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
return row, true
|
||||
}
|
||||
|
||||
func (a *API) attachmentIDList(w http.ResponseWriter, r *http.Request, raw []string) ([]string, bool) {
|
||||
if len(raw) > 10 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Слишком много вложений", 0)
|
||||
return nil, false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(raw))
|
||||
out := make([]string, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
id, ok := canonicalUUID(item)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор вложения", 0)
|
||||
return nil, false
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Повторяющееся вложение", 0)
|
||||
return nil, false
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func asAttachment(row store.Attachment) attachmentJSON {
|
||||
return attachmentJSON{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: row.ContentType,
|
||||
SizeBytes: row.SizeBytes,
|
||||
SHA256: row.SHA256,
|
||||
Status: row.Status,
|
||||
Variants: []struct{}{},
|
||||
ErrorCode: nil,
|
||||
CreatedAt: formatTime(row.CreatedAt),
|
||||
UpdatedAt: formatTime(row.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func validFilename(name string) bool {
|
||||
if !utf8.ValidString(name) {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(name)
|
||||
if n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
if r < 0x20 || r == 0x7f || r == '/' || r == '\\' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func newObjectKey() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "o/" + hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
Reference in New Issue
Block a user