forked from mtusi2026/mtusi2026lab4
refactor: isolate attachment lifecycle
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||
CreatePendingAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||
MarkAttachmentReady(context.Context, string, string) (model.Attachment, error)
|
||||
DeletePendingAttachment(context.Context, string, string) error
|
||||
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
|
||||
AttachmentForUser(context.Context, string, string) (model.Attachment, 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
|
||||
}
|
||||
|
||||
type Upload struct {
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type Content struct {
|
||||
Attachment model.Attachment
|
||||
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.CleanupTimeout <= 0 {
|
||||
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()
|
||||
objectKey := "attachments/" + uuid.NewString() + "/original"
|
||||
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: objectKey, Status: model.AttachmentPending,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
if err := s.objects.Put(ctx, objectKey, contentType, data); err != nil {
|
||||
s.deletePending(pending.ID, objectKey)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
attachment, err := s.repository.MarkAttachmentReady(ctx, pending.ID, objectKey)
|
||||
if err == nil {
|
||||
return attachment, nil
|
||||
}
|
||||
return s.resolveReadyOutcome(pending.ID, objectKey)
|
||||
}
|
||||
|
||||
func (s *Service) resolveReadyOutcome(attachmentID, objectKey string) (model.Attachment, error) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
stored, err := s.repository.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
|
||||
if err == nil && stored.Status == model.AttachmentReady {
|
||||
return stored, nil
|
||||
}
|
||||
if err == nil && stored.Status == model.AttachmentPending {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if deleteErr := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); deleteErr != nil {
|
||||
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("orphan attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", err)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
|
||||
func (s *Service) deletePending(attachmentID, objectKey string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); err != nil {
|
||||
s.logger.Error("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 string) (Content, error) {
|
||||
attachment, err := s.Metadata(ctx, attachmentID, userID)
|
||||
if err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
body, err := s.objects.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return Content{}, model.ErrUnavailable
|
||||
}
|
||||
return Content{Attachment: attachment, 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
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > s.config.MaxPixels {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user