package attachment import ( "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "image" _ "image/jpeg" _ "image/png" "io" "log/slog" "math" "mime" "net/http" "time" "github.com/google/uuid" "golang.org/x/sync/semaphore" "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" ) type Repository interface { ChatForUser(context.Context, string, string) (model.Chat, error) CreatePendingAttachment(context.Context, model.Attachment) (model.Attachment, error) QueueAttachmentWithJobAndOutbox(context.Context, string, string, model.AttachmentJob, string, string) (model.Attachment, error) DeletePendingAttachment(context.Context, string, string) error AttachmentForUser(context.Context, string, string) (model.Attachment, error) AttachmentVariantForUser(context.Context, string, string, string) (model.Attachment, model.Variant, error) } type ObjectStore interface { Put(context.Context, string, string, []byte) error Get(context.Context, string) (io.ReadCloser, error) Delete(context.Context, string) error } type Config struct { MaxBytes int64 MaxPixels int64 BodyMemoryBytes int64 DecodeMemoryBytes int64 CleanupTimeout time.Duration PipelineVersion int } type Upload struct { ChatID string OwnerID string Filename string ContentType string ContentLength int64 Body io.Reader TraceContext telemetry.MessageCarrier } type Content struct { Attachment model.Attachment Variant model.Variant Body io.ReadCloser } type Service struct { repository Repository objects ObjectStore config Config bodyMemory *semaphore.Weighted decodeMemory *semaphore.Weighted logger *slog.Logger } func NewService(logger *slog.Logger, repository Repository, objects ObjectStore, config Config) (*Service, error) { if config.MaxBytes < 1 || config.MaxPixels < 1 || config.MaxPixels > math.MaxInt64/8 || config.CleanupTimeout <= 0 || config.PipelineVersion < 1 { return nil, errors.New("invalid attachment service configuration") } if config.BodyMemoryBytes < config.MaxBytes { return nil, errors.New("attachment body memory must fit one maximum upload") } if config.DecodeMemoryBytes < config.MaxPixels*8 { return nil, errors.New("attachment decode memory must fit one maximum image") } return &Service{ repository: repository, objects: objects, config: config, bodyMemory: semaphore.NewWeighted(config.BodyMemoryBytes), decodeMemory: semaphore.NewWeighted(config.DecodeMemoryBytes), logger: logger, }, nil } func (s *Service) Upload(ctx context.Context, input Upload) (model.Attachment, error) { if _, err := s.repository.ChatForUser(ctx, input.ChatID, input.OwnerID); err != nil { return model.Attachment{}, mapDependencyError(err) } data, contentType, release, err := s.readImage(input) if err != nil { return model.Attachment{}, err } defer release() attachmentID := uuid.NewString() stagingKey := "staging/" + attachmentID + "/" + uuid.NewString() digest := sha256.Sum256(data) pending, err := s.repository.CreatePendingAttachment(ctx, model.Attachment{ ID: attachmentID, ChatID: input.ChatID, OwnerID: input.OwnerID, Filename: input.Filename, ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ObjectKey: stagingKey, StagingKey: stagingKey, Status: model.AttachmentPending, PipelineVersion: s.config.PipelineVersion, }) if err != nil { return model.Attachment{}, mapDependencyError(err) } if err := s.objects.Put(ctx, stagingKey, contentType, data); err != nil { s.logger.ErrorContext(ctx, "attachment staging write failed", "attachment_id", pending.ID, "error", err) s.deletePending(ctx, pending.ID, stagingKey) return model.Attachment{}, model.ErrUnavailable } createdAt := time.Now().UTC() queued, err := s.repository.QueueAttachmentWithJobAndOutbox(ctx, pending.ID, stagingKey, model.AttachmentJob{ ID: uuid.NewString(), AttachmentID: pending.ID, PipelineVersion: s.config.PipelineVersion, Attempt: 1, Status: model.AttachmentJobQueued, AvailableAt: createdAt, CreatedAt: createdAt, }, input.TraceContext.Traceparent, input.TraceContext.Tracestate) if err != nil { s.logger.ErrorContext(ctx, "attachment queue transaction failed", "attachment_id", pending.ID, "error", err) return model.Attachment{}, mapDependencyError(err) } return queued, nil } func (s *Service) deletePending(ctx context.Context, attachmentID, stagingKey string) { cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), s.config.CleanupTimeout) defer cancel() if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, stagingKey); err != nil { s.logger.ErrorContext(cleanupCtx, "pending attachment cleanup failed", "attachment_id", attachmentID, "error", err) } } func (s *Service) Metadata(ctx context.Context, attachmentID, userID string) (model.Attachment, error) { attachment, err := s.repository.AttachmentForUser(ctx, attachmentID, userID) if err != nil { return model.Attachment{}, mapDependencyError(err) } return attachment, nil } func (s *Service) Content(ctx context.Context, attachmentID, userID, variantName string) (Content, error) { attachment, variant, err := s.repository.AttachmentVariantForUser(ctx, attachmentID, userID, variantName) if err != nil { return Content{}, mapDependencyError(err) } body, err := s.objects.Get(ctx, variant.ObjectKey) if err != nil { return Content{}, model.ErrUnavailable } return Content{Attachment: attachment, Variant: variant, Body: body}, nil } func (s *Service) readImage(input Upload) ([]byte, string, func(), error) { mediaType, parameters, err := mime.ParseMediaType(input.ContentType) if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" { return nil, "", nil, model.ErrUnsupportedMedia } if input.ContentLength > s.config.MaxBytes { return nil, "", nil, model.ErrPayloadTooLarge } reservation := s.config.MaxBytes if !s.bodyMemory.TryAcquire(reservation) { return nil, "", nil, model.ErrCapacity } releaseBody := func() { s.bodyMemory.Release(reservation) } data, err := io.ReadAll(io.LimitReader(input.Body, s.config.MaxBytes+1)) if err != nil { releaseBody() return nil, "", nil, model.ErrInvalidInput } if int64(len(data)) > s.config.MaxBytes { releaseBody() return nil, "", nil, model.ErrPayloadTooLarge } if len(data) == 0 { releaseBody() return nil, "", nil, model.ErrUnsupportedMedia } detected := http.DetectContentType(data) if detected != mediaType { releaseBody() return nil, "", nil, model.ErrUnsupportedMedia } imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data)) if err != nil || imageContentType(format) != mediaType { releaseBody() return nil, "", nil, model.ErrUnsupportedMedia } if imageConfig.Width < 1 || imageConfig.Height < 1 || int64(imageConfig.Width) > s.config.MaxPixels/int64(imageConfig.Height) { releaseBody() return nil, "", nil, model.ErrPayloadTooLarge } pixels := int64(imageConfig.Width) * int64(imageConfig.Height) decodeBytes := pixels * 8 if !s.decodeMemory.TryAcquire(decodeBytes) { releaseBody() return nil, "", nil, model.ErrCapacity } if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType { s.decodeMemory.Release(decodeBytes) releaseBody() return nil, "", nil, model.ErrUnsupportedMedia } release := func() { s.decodeMemory.Release(decodeBytes) releaseBody() } return data, mediaType, release, nil } func imageContentType(format string) string { switch format { case "png": return "image/png" case "jpeg": return "image/jpeg" default: return "" } } func mapDependencyError(err error) error { switch { case errors.Is(err, model.ErrNotFound): return model.ErrNotFound case errors.Is(err, model.ErrConflict): return model.ErrConflict default: return model.ErrUnavailable } }