ЛР4 - БВТ2303 - Голиков- на 4 #13

Closed
Maximillan_Mercer wants to merge 64 commits from Maximillan_Mercer/mtusi2026lab4-fork:solution/BVT2303-Golikov into main
Showing only changes of commit d62e74f3ac - Show all commits
+94
View File
@@ -1,12 +1,21 @@
package service
import (
"bytes"
"context"
"crypto/sha256"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"net/http"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
@@ -33,6 +42,91 @@ func NewAttachmentService(
}
}
// Upload принимает тело, валидирует PNG/JPEG по содержимому,
// кладёт в pending, загружает в S3, переводит в ready.
// При ошибке Put компенсирует MarkFailed.
func (s *AttachmentService) Upload(
ctx context.Context,
ownerID, chatID, filename string,
body io.Reader,
) (*domain.Attachment, error) {
if err := s.ensureMember(ctx, ownerID, chatID); err != nil {
return nil, err
}
if err := validateFilename(filename); err != nil {
return nil, err
}
limited := io.LimitReader(body, s.maxBytes+1)
buf, err := io.ReadAll(limited)
if err != nil {
return nil, &domain.UnavailableError{Reason: "не удалось прочитать тело загрузки"}
}
if int64(len(buf)) > s.maxBytes {
return nil, &domain.PayloadTooLargeError{Limit: s.maxBytes}
}
if len(buf) == 0 {
return nil, &domain.ValidationError{Field: "body", Message: "пустой файл"}
}
contentType := http.DetectContentType(buf)
if contentType != "image/png" && contentType != "image/jpeg" {
return nil, &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "image/png или image/jpeg",
}
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(buf))
if err != nil {
return nil, &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "image/png или image/jpeg",
}
}
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
return nil, &domain.PayloadTooLargeError{
Limit: s.maxPixels,
Message: "изображение превышает лимит пикселей",
}
}
sha := sha256.Sum256(buf)
id := uuid.NewString()
objectKey := "chats/" + chatID + "/" + id
now := time.Now().UTC()
a := &domain.Attachment{
ID: id,
ChatID: chatID,
OwnerID: ownerID,
Filename: filename,
ContentType: contentType,
SizeBytes: int64(len(buf)),
SHA256: sha[:],
ObjectKey: objectKey,
Status: domain.AttachmentStatusPending,
CreatedAt: now,
UpdatedAt: now,
}
if err := s.attachments.Create(ctx, a); err != nil {
return nil, err
}
if err := s.storage.Put(ctx, objectKey, bytes.NewReader(buf), int64(len(buf)), contentType); err != nil {
// Компенсация: pending → failed. Reconciler не будет трогать failed.
_ = s.attachments.MarkFailed(ctx, a.ID, "upload_failed")
return nil, err
}
if err := s.attachments.MarkReady(ctx, a.ID); err != nil {
// S3 has the object, DB still pending. Reconciler очистит по grace period.
return nil, err
}
a.Status = domain.AttachmentStatusReady
return a, nil
}
func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) {
a, err := s.attachments.GetByID(ctx, attachmentID)
if err != nil {