refactor: isolate attachment lifecycle

This commit is contained in:
2026-10-09 13:13:59 +03:00
parent ad36ab8a92
commit cc4ac1ddd7
33 changed files with 1672 additions and 982 deletions
+252
View File
@@ -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
}
}
@@ -0,0 +1,195 @@
package attachment
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"log/slog"
"testing"
"time"
"github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
func TestUploadLifecycle(t *testing.T) {
data := pngFixture(t, 2, 2)
events := make([]string, 0, 3)
repository := &repositoryStub{events: &events}
objects := &objectStub{events: &events}
service := newTestService(t, repository, objects, 1024, 4)
result, err := service.Upload(context.Background(), upload(data, "image/png"))
require.NoError(t, err)
require.Equal(t, model.AttachmentReady, result.Status)
require.Equal(t, []string{"pending", "put", "ready"}, events)
}
func TestUploadValidation(t *testing.T) {
data := pngFixture(t, 2, 2)
tests := []struct {
name string
contentType string
data []byte
maxBytes int64
maxPixels int64
want error
}{
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, want: model.ErrPayloadTooLarge},
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, want: model.ErrPayloadTooLarge},
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
service := newTestService(t, &repositoryStub{}, &objectStub{}, test.maxBytes, test.maxPixels)
input := upload(test.data, test.contentType)
_, err := service.Upload(context.Background(), input)
require.ErrorIs(t, err, test.want)
})
}
}
func TestUploadUsesSeparateBodyAndDecodeBudgets(t *testing.T) {
data := pngFixture(t, 2, 2)
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
require.True(t, service.bodyMemory.TryAcquire(1024))
_, err := service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrCapacity)
service.bodyMemory.Release(1024)
require.True(t, service.decodeMemory.TryAcquire(32))
_, err = service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrCapacity)
service.decodeMemory.Release(32)
}
func TestUploadCleansPendingMetadataWhenObjectWriteFails(t *testing.T) {
data := pngFixture(t, 2, 2)
repository := &repositoryStub{}
objects := &objectStub{putErr: errors.New("s3 unavailable")}
service := newTestService(t, repository, objects, 1024, 4)
_, err := service.Upload(context.Background(), upload(data, "image/png"))
require.ErrorIs(t, err, model.ErrUnavailable)
require.True(t, repository.pendingDeleted)
}
func TestUploadReturnsCommittedMetadataAfterAmbiguousReadyUpdate(t *testing.T) {
data := pngFixture(t, 2, 2)
repository := &repositoryStub{markErr: errors.New("connection lost"), lookupReady: true}
objects := &objectStub{}
service := newTestService(t, repository, objects, 1024, 4)
result, err := service.Upload(context.Background(), upload(data, "image/png"))
require.NoError(t, err)
require.Equal(t, model.AttachmentReady, result.Status)
require.False(t, objects.deleted)
}
func newTestService(t *testing.T, repository Repository, objects ObjectStore, maxBytes, maxPixels int64) *Service {
t.Helper()
service, err := NewService(
slog.New(slog.NewTextHandler(io.Discard, nil)), repository, objects,
Config{
MaxBytes: maxBytes, MaxPixels: maxPixels, BodyMemoryBytes: maxBytes,
DecodeMemoryBytes: maxPixels * 8, CleanupTimeout: time.Second,
},
)
require.NoError(t, err)
return service
}
func upload(data []byte, contentType string) Upload {
return Upload{
ChatID: "chat", OwnerID: "owner", Filename: "photo.png", ContentType: contentType,
ContentLength: int64(len(data)), Body: bytes.NewReader(data),
}
}
type repositoryStub struct {
events *[]string
markErr error
lookupReady bool
pendingDeleted bool
pending model.Attachment
}
func (*repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
return model.Chat{}, nil
}
func (s *repositoryStub) CreatePendingAttachment(_ context.Context, attachment model.Attachment) (model.Attachment, error) {
attachment.Status = model.AttachmentPending
s.pending = attachment
s.record("pending")
return attachment, nil
}
func (s *repositoryStub) MarkAttachmentReady(context.Context, string, string) (model.Attachment, error) {
if s.markErr != nil {
return model.Attachment{}, s.markErr
}
s.pending.Status = model.AttachmentReady
s.record("ready")
return s.pending, nil
}
func (s *repositoryStub) DeletePendingAttachment(context.Context, string, string) error {
s.pendingDeleted = true
return nil
}
func (s *repositoryStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
if s.lookupReady {
s.pending.Status = model.AttachmentReady
return s.pending, nil
}
return model.Attachment{}, model.ErrNotFound
}
func (s *repositoryStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
return s.pending, nil
}
func (s *repositoryStub) record(event string) {
if s.events != nil {
*s.events = append(*s.events, event)
}
}
type objectStub struct {
events *[]string
putErr error
deleted bool
}
func (s *objectStub) Put(context.Context, string, string, []byte) error {
if s.events != nil {
*s.events = append(*s.events, "put")
}
return s.putErr
}
func (*objectStub) Get(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), nil
}
func (s *objectStub) Delete(context.Context, string) error {
s.deleted = true
return nil
}
func pngFixture(t *testing.T, width, height int) []byte {
t.Helper()
var data bytes.Buffer
value := image.NewRGBA(image.Rect(0, 0, width, height))
value.Set(0, 0, color.White)
require.NoError(t, png.Encode(&data, value))
return data.Bytes()
}