ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
attachmentService *service.AttachmentService
|
||||
uploadSlots chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(attachmentService *service.AttachmentService) *AttachmentHandler {
|
||||
uploadSlots := make(chan struct{}, 1)
|
||||
return &AttachmentHandler{attachmentService: attachmentService, uploadSlots: uploadSlots}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) CreateAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
filename := r.URL.Query().Get("filename")
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
select {
|
||||
case h.uploadSlots <- struct{}{}:
|
||||
defer func() { <-h.uploadSlots }()
|
||||
case <-time.After(1 * time.Second):
|
||||
w.Header().Set("Retry-After", "1")
|
||||
httputils.WriteError(w, http.StatusTooManyRequests, httputils.ErrorDetails{
|
||||
Code: "rate_limited",
|
||||
Message: "too many concurrent uploads, try again later",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
|
||||
file, err := os.CreateTemp("", "attachment-*")
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if err := os.Remove(file.Name()); err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
body := http.MaxBytesReader(w, r.Body, service.MaxAttachmentBytes)
|
||||
defer body.Close()
|
||||
size, err := io.Copy(file, uploadBodyReader{body})
|
||||
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
httputils.WriteError(w, http.StatusRequestEntityTooLarge, httputils.ErrorDetails{
|
||||
Code: "payload_too_large",
|
||||
Message: "payload_too_large",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
var readErr *uploadBodyReadError
|
||||
if !errors.As(err, &readErr) {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "invalid_request",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.attachmentService.CreateAttachment(r.Context(), chatID, userID, filename, contentType, file, size)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertAttachmentModelToResponse(attachment)
|
||||
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusAccepted, *response)
|
||||
if wrErr != nil {
|
||||
slog.Error("failed to write create attachment response", "error", wrErr, "requestID", requestID)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type uploadBodyReader struct{ io.Reader }
|
||||
|
||||
func (r uploadBodyReader) Read(p []byte) (int, error) {
|
||||
n, err := r.Reader.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, &uploadBodyReadError{err}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type uploadBodyReadError struct{ cause error }
|
||||
|
||||
func (e *uploadBodyReadError) Error() string { return e.cause.Error() }
|
||||
func (e *uploadBodyReadError) Unwrap() error { return e.cause }
|
||||
|
||||
func (h *AttachmentHandler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
attachmentID := r.PathValue("attachment_id")
|
||||
|
||||
attachment, err := h.attachmentService.GetAttachment(r.Context(), userID, attachmentID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusOK, *convertAttachmentModelToResponse(attachment))
|
||||
if wrErr != nil {
|
||||
slog.Error("failed to write get attachment response", "error", wrErr, "requestID", requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
attachmentID := r.PathValue("attachment_id")
|
||||
variant := r.URL.Query().Get("variant")
|
||||
|
||||
contentType, stream, err := h.attachmentService.GetAttachmentContent(r.Context(), userID, attachmentID, variant)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
defer stream.Close()
|
||||
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
_, err = io.Copy(w, stream)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("failed to copy attachment content to w", "error", err, "request_id", requestID)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user