lab5: очередь RabbitMQ, outbox, worker, варианты, fault-injection

This commit is contained in:
2026-11-09 17:34:10 +03:00
parent 276dbdad8a
commit 5f4b10ac2b
96 changed files with 10573 additions and 1 deletions
+83
View File
@@ -0,0 +1,83 @@
package http
import (
"io"
"log/slog"
"net/http"
"strconv"
"github.com/charawein/mtusi2026lab5/internal/service"
"github.com/charawein/mtusi2026lab5/internal/transport/httputil"
)
type AttachmentHandler struct {
attachments *service.AttachmentService
}
func NewAttachmentHandler(attachments *service.AttachmentService) *AttachmentHandler {
return &AttachmentHandler{attachments: attachments}
}
// Upload: POST /api/v1/chats/{chat_id}/attachments?filename=... с сырыми байтами PNG/JPEG.
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
uid := httputil.UserIDFromContext(r.Context())
if uid == "" {
httputil.WriteError(w, r, service.ErrUnauthorized)
return
}
q := r.URL.Query()
if len(q["filename"]) != 1 {
httputil.WriteError(w, r, service.ErrInvalidInput)
return
}
// MaxBytesReader — второй рубеж: не дать прочитать больше лимита + 1 байт,
// даже если Content-Length солгал.
r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024+1)
a, err := h.attachments.Upload(r.Context(), uid, r.PathValue("chat_id"), q.Get("filename"),
r.Header.Get("Content-Type"), r.Body, r.ContentLength)
if err != nil {
httputil.WriteError(w, r, err)
return
}
// 202: оригинал устойчиво принят, обработка асинхронна; готовность — по GET.
httputil.WriteJSON(w, r, http.StatusAccepted, a)
}
// Get: GET /api/v1/attachments/{attachment_id} — метаданные.
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
uid := httputil.UserIDFromContext(r.Context())
a, err := h.attachments.Get(r.Context(), uid, r.PathValue("attachment_id"))
if err != nil {
httputil.WriteError(w, r, err)
return
}
httputil.WriteJSON(w, r, http.StatusOK, a)
}
// Content: GET /api/v1/attachments/{attachment_id}/content[?variant=original] — байты
// через авторизованный API, без redirect на S3.
func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) {
uid := httputil.UserIDFromContext(r.Context())
variant := r.URL.Query().Get("variant")
switch variant {
case "", "original", "thumbnail", "crop", "optimized":
default:
httputil.WriteError(w, r, service.ErrInvalidInput)
return
}
c, rc, err := h.attachments.Open(r.Context(), uid, r.PathValue("attachment_id"), variant)
if err != nil {
httputil.WriteError(w, r, err)
return
}
defer rc.Close()
w.Header().Set("Content-Type", c.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(c.Size, 10))
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
if n, err := io.Copy(w, rc); err != nil {
// Заголовок уже отправлен: клиент увидит обрыв по Content-Length.
slog.Warn("attachment download interrupted", "attachment_id", r.PathValue("attachment_id"), "sent", n, "err", err)
}
}