package service import ( "bytes" "context" "crypto/sha256" "encoding/json" "image" _ "image/jpeg" _ "image/png" "io" "net/http" "strings" "time" "unicode" "unicode/utf8" "github.com/google/uuid" "high-loud-apps-labs/internal/domain" ) type txRunner interface { WithTx(ctx context.Context, fn func(tx domain.Tx) error) error } type AttachmentService struct { attachments domain.AttachmentRepository chats domain.ChatRepository storage domain.ObjectStorage outbox domain.OutboxRepository failedJobs domain.FailedJobRepository tx txRunner maxBytes int64 maxPixels int64 } func NewAttachmentService( attachments domain.AttachmentRepository, chats domain.ChatRepository, storage domain.ObjectStorage, outbox domain.OutboxRepository, failedJobs domain.FailedJobRepository, tx txRunner, maxBytes, maxPixels int64, ) *AttachmentService { return &AttachmentService{ attachments: attachments, chats: chats, storage: storage, outbox: outbox, failedJobs: failedJobs, tx: tx, maxBytes: maxBytes, maxPixels: maxPixels, } } // 1. Валидация, sniff Content-Type, проверка пикселей по заголовку. // 2. Оригинал в S3 staging/{id}. // 3. Транзакция: INSERT attachments(status=queued) + INSERT outbox. 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() stagingKey := "staging/" + 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: "chats/" + chatID + "/" + id, Status: domain.AttachmentStatusQueued, StagingKey: stagingKey, PipelineVersion: 1, CreatedAt: now, UpdatedAt: now, } if err := s.storage.Put(ctx, stagingKey, bytes.NewReader(buf), int64(len(buf)), contentType); err != nil { return nil, err } payload, err := json.Marshal(domain.JobMessage{ AttachmentID: id, PipelineVersion: 1, Attempt: 1, }) if err != nil { return nil, err } err = s.tx.WithTx(ctx, func(tx domain.Tx) error { if err := s.attachments.CreateInTx(ctx, tx, a); err != nil { return err } return s.outbox.Enqueue(ctx, tx, &domain.OutboxEntry{ AggregateType: domain.OutboxAggregateAttachment, AggregateID: id, EventType: domain.OutboxEventProcess, Payload: payload, }) }) if err != nil { return nil, err } 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, variantName 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: "вложение не готово"} } if variantName == "original" || variantName == "" { return s.storage.Get(ctx, a.ObjectKey) } for _, v := range a.Variants { if v.Name == variantName { return s.storage.Get(ctx, v.ObjectKey) } } return nil, 0, "", &domain.NotFoundError{Entity: "variant", ID: variantName} } // Replay позволяет оператору перезапустить упавшую задачу. func (s *AttachmentService) Replay(ctx context.Context, userID, attachmentID string) error { a, err := s.Get(ctx, userID, attachmentID) if err != nil { return err } if a.Status != domain.AttachmentStatusFailed { return &domain.ConflictError{Reason: "перезапустить можно только failed-вложение"} } // Формируем новое сообщение payload, err := json.Marshal(domain.JobMessage{ AttachmentID: a.ID, PipelineVersion: a.PipelineVersion, Attempt: 1, // Сбрасываем счетчик попыток }) if err != nil { return err } err = s.tx.WithTx(ctx, func(tx domain.Tx) error { if err := s.attachments.ResetForReplay(ctx, tx, a.ID); err != nil { return err } // Помечаем в реестре упавших задач (внутри транзакции) if err := s.failedJobs.ResolveInTx(ctx, tx, a.ID); err != nil { return err } return s.outbox.Enqueue(ctx, tx, &domain.OutboxEntry{ AggregateType: domain.OutboxAggregateAttachment, AggregateID: a.ID, EventType: domain.OutboxEventProcess, Payload: payload, }) }) if err != nil { return err } return nil } 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 }