forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
)
|
||||
|
||||
const currentAttachmentPipelineVersion = 1
|
||||
|
||||
func (s *Service) UploadAttachment(ctx context.Context, command UploadAttachmentCommand) (domain.Attachment, error) {
|
||||
if s.objectStore == nil {
|
||||
return domain.Attachment{}, ErrStorageUnavailable
|
||||
}
|
||||
queueRepository, ok := s.repository.(AttachmentQueueRepository)
|
||||
if !ok {
|
||||
return domain.Attachment{}, fmt.Errorf("attachment queue repository is not configured")
|
||||
}
|
||||
if command.Body == nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput)
|
||||
}
|
||||
if err := domain.ValidateAttachmentFilename(command.Filename); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err)
|
||||
}
|
||||
if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable)
|
||||
}
|
||||
defer releaseAttachmentSlot(s.attachmentUploadSlots)
|
||||
|
||||
stagedFile, err := os.CreateTemp("", "mtusi-attachment-*")
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err)
|
||||
}
|
||||
stagedPath := stagedFile.Name()
|
||||
defer func() {
|
||||
_ = stagedFile.Close()
|
||||
_ = os.Remove(stagedPath)
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1))
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput)
|
||||
}
|
||||
if sizeBytes > domain.MaxAttachmentSizeBytes {
|
||||
return domain.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err)
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(stagedFile)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage)
|
||||
}
|
||||
actualContentType, supported := contentTypeForImageFormat(format)
|
||||
if !supported || actualContentType != command.DeclaredContentType {
|
||||
return domain.Attachment{}, ErrUnsupportedMediaType
|
||||
}
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 {
|
||||
return domain.Attachment{}, ErrInvalidImage
|
||||
}
|
||||
if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) {
|
||||
return domain.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
sha256Hex := hex.EncodeToString(hasher.Sum(nil))
|
||||
if err = domain.ValidateReadyAttachmentMetadata(command.Filename, actualContentType, sizeBytes, sha256Hex, imageConfig.Width, imageConfig.Height); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err)
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err)
|
||||
}
|
||||
if err = s.validateCompleteImage(ctx, stagedFile); err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable)
|
||||
}
|
||||
return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage)
|
||||
}
|
||||
|
||||
now := s.now().UTC()
|
||||
attachmentID := uuid.NewString()
|
||||
attachment := domain.Attachment{
|
||||
ID: attachmentID,
|
||||
ChatID: command.ChatID,
|
||||
OwnerID: command.ActorID,
|
||||
Filename: command.Filename,
|
||||
ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original",
|
||||
StagingKey: "staging/" + attachmentID + "/original",
|
||||
ContentType: actualContentType,
|
||||
SizeBytes: sizeBytes,
|
||||
SHA256: sha256Hex,
|
||||
Width: imageConfig.Width,
|
||||
Height: imageConfig.Height,
|
||||
PipelineVersion: currentAttachmentPipelineVersion,
|
||||
Status: domain.AttachmentStatusQueued,
|
||||
Variants: make([]domain.AttachmentVariant, 0),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err)
|
||||
}
|
||||
if err = s.objectStore.Put(ctx, ObjectPut{Key: attachment.StagingKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile}); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: put durable staging object", ErrStorageUnavailable)
|
||||
}
|
||||
traceCarrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
|
||||
job := domain.AttachmentJob{
|
||||
SchemaVersion: 1,
|
||||
JobID: uuid.NewString(),
|
||||
Type: domain.AttachmentJobType,
|
||||
AttachmentID: attachment.ID,
|
||||
PipelineVersion: attachment.PipelineVersion,
|
||||
Attempt: 1,
|
||||
MaxAttempts: s.jobMaxAttempts,
|
||||
Status: domain.AttachmentJobQueued,
|
||||
AvailableAt: now,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
TraceParent: traceCarrier.Get("traceparent"),
|
||||
TraceState: traceCarrier.Get("tracestate"),
|
||||
}
|
||||
attachment, err = queueRepository.CreateQueuedAttachment(ctx, attachment, job)
|
||||
if err != nil {
|
||||
// A failed COMMIT response is ambiguous. Preserve staging so a committed
|
||||
// job can still finish and an uncommitted orphan can be retained/cleaned.
|
||||
return domain.Attachment{}, fmt.Errorf("persist queued attachment: %w", err)
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error {
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func releaseAttachmentSlot(slots chan struct{}) { <-slots }
|
||||
|
||||
func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error {
|
||||
if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil {
|
||||
return err
|
||||
}
|
||||
defer releaseAttachmentSlot(s.attachmentDecodeSlots)
|
||||
_, _, err := image.Decode(body)
|
||||
return err
|
||||
}
|
||||
|
||||
func contentTypeForImageFormat(format string) (string, bool) {
|
||||
switch format {
|
||||
case "png":
|
||||
return "image/png", true
|
||||
case "jpeg":
|
||||
return "image/jpeg", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user