Files
mtusi2026lab5/backend/internal/service/attachment.go
T

210 lines
5.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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"
)
type AttachmentService struct {
attachments domain.AttachmentRepository
chats domain.ChatRepository
storage domain.ObjectStorage
maxBytes int64
maxPixels int64
decodeSem chan struct{}
}
func NewAttachmentService(
attachments domain.AttachmentRepository,
chats domain.ChatRepository,
storage domain.ObjectStorage,
maxBytes, maxPixels int64,
) *AttachmentService {
return &AttachmentService{
attachments: attachments,
chats: chats,
storage: storage,
maxBytes: maxBytes,
maxPixels: maxPixels,
// 40M pixels × 4 bytes (RGBA8) = 160 MB per full decode.
// API_MEMORY=256M → только один decode безопасен.
decodeSem: make(chan struct{}, 1),
}
}
// 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: "изображение превышает лимит пикселей",
}
}
if err := s.verifyIntegrity(ctx, buf, contentType); err != nil {
return nil, err
}
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) verifyIntegrity(ctx context.Context, buf []byte, contentType string) error {
select {
case s.decodeSem <- struct{}{}:
case <-ctx.Done():
return &domain.UnavailableError{Reason: "ожидание декодирования"}
}
defer func() { <-s.decodeSem }()
if _, _, err := image.Decode(bytes.NewReader(buf)); err != nil {
return &domain.UnsupportedMediaTypeError{
MediaType: contentType,
Expected: "целостный " + contentType + " (без обрезки/повреждений)",
}
}
return nil
}
func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) {
a, err := s.attachments.GetByID(ctx, attachmentID)
if err != nil {
return nil, err
}
if err := s.ensureMember(ctx, userID, a.ChatID); err != nil {
return nil, err
}
return a, nil
}
func (s *AttachmentService) Download(
ctx context.Context,
userID, attachmentID string,
) (io.ReadCloser, int64, string, error) {
a, err := s.Get(ctx, userID, attachmentID)
if err != nil {
return nil, 0, "", err
}
if a.Status != domain.AttachmentStatusReady {
return nil, 0, "", &domain.ConflictError{Reason: "вложение не готово"}
}
return s.storage.Get(ctx, a.ObjectKey)
}
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID string) error {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return err
}
for _, m := range c.MemberIDs {
if m == userID {
return nil
}
}
return &domain.NotFoundError{Entity: "chat", ID: chatID}
}
func validateFilename(name string) error {
if strings.TrimSpace(name) == "" {
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
}
if utf8.RuneCountInString(name) > 255 {
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
}
if strings.ContainsAny(name, "/\\\x00") {
return &domain.ValidationError{Field: "filename", Message: "содержит недопустимые символы"}
}
for _, r := range name {
if unicode.IsControl(r) {
return &domain.ValidationError{Field: "filename", Message: "содержит управляющие символы"}
}
}
return nil
}