package application import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "image" _ "image/jpeg" _ "image/png" "io" "os" "mtusi2026lab4/internal/domain" "github.com/google/uuid" ) const attachmentPutFailedCode = "object_store_put_failed" const attachmentFinalizeFailedCode = "metadata_finalize_failed" func (s *Service) UploadAttachment( ctx context.Context, command UploadAttachmentCommand, ) (domain.Attachment, error) { if s.objectStore == nil { return domain.Attachment{}, ErrStorageUnavailable } 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() limitedBody := io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1) sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), limitedBody) 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", ContentType: actualContentType, SizeBytes: sizeBytes, SHA256: sha256Hex, Width: imageConfig.Width, Height: imageConfig.Height, Status: domain.AttachmentStatusPending, Variants: make([]domain.AttachmentVariant, 0), CreatedAt: now, UpdatedAt: now, } attachment, err = s.repository.CreateAttachment(ctx, attachment) if err != nil { return domain.Attachment{}, err } if _, err = stagedFile.Seek(0, io.SeekStart); err != nil { s.cleanupFailedAttachment(ctx, attachment, attachmentFinalizeFailedCode, false) return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err) } err = s.objectStore.Put(ctx, ObjectPut{ Key: attachment.ObjectKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile, }) if err != nil { s.cleanupFailedAttachment(ctx, attachment, attachmentPutFailedCode, true) return domain.Attachment{}, fmt.Errorf("%w: put object", ErrStorageUnavailable) } readyAttachment, err := s.repository.MarkAttachmentReady(ctx, attachment.ID, s.now().UTC()) if err != nil { // The UPDATE may already have committed even when its response was lost. // Deleting the object here could turn durable ready metadata into a // permanently broken attachment. A best-effort read may recover a 201; // otherwise both sides are preserved for the grace-period reconciler. if resolved, ok := s.resolveAmbiguousAttachmentFinalize(ctx, attachment); ok { return resolved, nil } return domain.Attachment{}, fmt.Errorf("finalize attachment metadata: %w", err) } if readyAttachment.Variants == nil { readyAttachment.Variants = make([]domain.AttachmentVariant, 0) } return readyAttachment, 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 (s *Service) resolveAmbiguousAttachmentFinalize( requestContext context.Context, attachment domain.Attachment, ) (domain.Attachment, bool) { resolveContext, cancel := context.WithTimeout( context.WithoutCancel(requestContext), s.attachmentCleanupTimeout, ) defer cancel() stored, err := s.repository.GetAttachment( resolveContext, attachment.ID, attachment.OwnerID, ) if err != nil || stored.Status != domain.AttachmentStatusReady { return domain.Attachment{}, false } if stored.Variants == nil { stored.Variants = make([]domain.AttachmentVariant, 0) } return stored, true } func contentTypeForImageFormat(format string) (string, bool) { switch format { case "png": return "image/png", true case "jpeg": return "image/jpeg", true default: return "", false } } func (s *Service) cleanupFailedAttachment( requestContext context.Context, attachment domain.Attachment, errorCode string, deleteObject bool, ) { metadataContext, metadataCancel := context.WithTimeout( context.WithoutCancel(requestContext), s.attachmentCleanupTimeout, ) _ = s.repository.MarkAttachmentFailed( metadataContext, attachment.ID, errorCode, s.now().UTC(), ) metadataCancel() if !deleteObject { return } deleteContext, deleteCancel := context.WithTimeout( context.WithoutCancel(requestContext), s.attachmentCleanupTimeout, ) defer deleteCancel() _ = s.objectStore.Delete(deleteContext, attachment.ObjectKey) }