Files
mtusi2026lab4-fork/backend/internal/service/attachment.go
T
Голиков Maximillian Антон d62e74f3ac feat(service):lab4 add AttachmentService.Upload with S3 and compensation
- Upload: LimitReader -> DetectContentType -> DecodeConfig -> sha256
- Create(pending) -> Put -> MarkReady
- MarkFailed on Put error (compensation, avoid hanging pending rows)
- Download: member check + status ready via ObjectStorage
- Get: member check by chat_id
2026-10-21 19:04:22 +03:00

185 lines
5.0 KiB
Go

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
}
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,
}
}
// 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 {
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 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
}