API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
427 lines
14 KiB
Go
427 lines
14 KiB
Go
package attachment_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"io"
|
|
"log/slog"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/mock"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/platform/objectstore"
|
|
"mtusi-messenger/internal/service/attachment"
|
|
"mtusi-messenger/internal/service/attachment/mocks"
|
|
)
|
|
|
|
type storedObject struct {
|
|
data []byte
|
|
contentType string
|
|
metadata map[string]string
|
|
lastModified time.Time
|
|
}
|
|
|
|
type fakeStore struct {
|
|
objects map[string]storedObject
|
|
}
|
|
|
|
func newFakeStore() *fakeStore {
|
|
return &fakeStore{objects: make(map[string]storedObject)}
|
|
}
|
|
|
|
func (f *fakeStore) Put(
|
|
_ context.Context,
|
|
key string,
|
|
body io.ReadSeeker,
|
|
_ int64,
|
|
contentType string,
|
|
metadata map[string]string,
|
|
) error {
|
|
data, err := io.ReadAll(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
f.objects[key] = storedObject{
|
|
data: data,
|
|
contentType: contentType,
|
|
metadata: metadata,
|
|
lastModified: time.Now().UTC(),
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
|
|
object, ok := f.objects[key]
|
|
if !ok {
|
|
return nil, objectstore.Object{}, domain.ErrNotFound
|
|
}
|
|
|
|
return io.NopCloser(bytes.NewReader(object.data)), f.object(key, object), nil
|
|
}
|
|
|
|
func (f *fakeStore) Ping(context.Context) error { return nil }
|
|
|
|
func (f *fakeStore) Head(_ context.Context, key string) (objectstore.Object, error) {
|
|
object, ok := f.objects[key]
|
|
if !ok {
|
|
return objectstore.Object{}, domain.ErrNotFound
|
|
}
|
|
|
|
return f.object(key, object), nil
|
|
}
|
|
|
|
func (f *fakeStore) Copy(_ context.Context, src, dst, contentType string, metadata map[string]string) error {
|
|
object, ok := f.objects[src]
|
|
if !ok {
|
|
return domain.ErrNotFound
|
|
}
|
|
|
|
f.objects[dst] = storedObject{
|
|
data: append([]byte(nil), object.data...),
|
|
contentType: contentType,
|
|
metadata: metadata,
|
|
lastModified: time.Now().UTC(),
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeStore) Delete(_ context.Context, key string) error {
|
|
delete(f.objects, key)
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object, error) {
|
|
objects := make([]objectstore.Object, 0, len(f.objects))
|
|
for key, object := range f.objects {
|
|
if strings.HasPrefix(key, prefix) {
|
|
objects = append(objects, f.object(key, object))
|
|
}
|
|
}
|
|
|
|
return objects, nil
|
|
}
|
|
|
|
func (f *fakeStore) PresignPut(_ context.Context, key string, _ int64, ttl time.Duration) (string, time.Time, error) {
|
|
return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil
|
|
}
|
|
|
|
func (f *fakeStore) object(key string, object storedObject) objectstore.Object {
|
|
return objectstore.Object{
|
|
Key: key,
|
|
Size: int64(len(object.data)),
|
|
ContentType: object.contentType,
|
|
LastModified: object.lastModified,
|
|
Metadata: object.metadata,
|
|
}
|
|
}
|
|
|
|
func pngBytes(t *testing.T, width, height int) []byte {
|
|
t.Helper()
|
|
|
|
source := image.NewRGBA(image.Rect(0, 0, width, height))
|
|
for x := range width {
|
|
for y := range height {
|
|
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 200, A: 255})
|
|
}
|
|
}
|
|
|
|
var buffer bytes.Buffer
|
|
require.NoError(t, png.Encode(&buffer, source))
|
|
|
|
return buffer.Bytes()
|
|
}
|
|
|
|
func serviceConfig() attachment.Config {
|
|
return attachment.Config{
|
|
MaxUploadBytes: 1 << 20,
|
|
MaxImagePixels: 1_000_000,
|
|
PresignTTL: 5 * time.Minute,
|
|
PipelineVersion: 1,
|
|
MaxAttempts: 5,
|
|
}
|
|
}
|
|
|
|
func TestValidateFilename(t *testing.T) {
|
|
valid := []string{"photo.png", "фото.png", "a b.jpeg", strings.Repeat("я", 255)}
|
|
for _, name := range valid {
|
|
require.NoError(t, attachment.ValidateFilename(name), name)
|
|
}
|
|
|
|
invalid := []string{"", " ", "\t\n", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"}
|
|
for _, name := range invalid {
|
|
require.ErrorIs(t, attachment.ValidateFilename(name), domain.ErrValidation, name)
|
|
}
|
|
}
|
|
|
|
func TestUploadStagesAndQueues(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
store := newFakeStore()
|
|
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
|
|
|
chatID := uuid.New()
|
|
ownerID := uuid.New()
|
|
content := pngBytes(t, 16, 16)
|
|
sum := sha256.Sum256(content)
|
|
digest := hex.EncodeToString(sum[:])
|
|
|
|
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
|
|
repo.EXPECT().Admission(mock.Anything, ownerID).Return(0, 0, int64(0), nil).Once()
|
|
repo.EXPECT().CreateQueued(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
|
|
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
|
|
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
|
|
draft.SHA256 == digest && draft.Status == domain.AttachmentQueued &&
|
|
draft.PipelineVersion == 1 &&
|
|
strings.HasPrefix(draft.ObjectKey, "attachments/") &&
|
|
strings.HasPrefix(draft.StagingKey, "staging/uploads/")
|
|
}), mock.MatchedBy(func(job domain.Job) bool {
|
|
return job.PipelineVersion == 1 && job.Attempt == 1 &&
|
|
job.MaxAttempts == 5 && job.SourceKey != ""
|
|
})).Return(domain.Attachment{
|
|
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
|
|
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
|
Status: domain.AttachmentQueued, PipelineVersion: 1,
|
|
}, nil).Once()
|
|
|
|
result, err := service.Upload(t.Context(), attachment.UploadInput{
|
|
ChatID: chatID,
|
|
OwnerID: ownerID,
|
|
Filename: "photo.png",
|
|
DeclaredContentType: "image/png",
|
|
Body: bytes.NewReader(content),
|
|
})
|
|
require.NoError(t, err)
|
|
require.Equal(t, domain.AttachmentQueued, result.Status)
|
|
require.Len(t, store.objects, 1)
|
|
for key := range store.objects {
|
|
require.Contains(t, key, "staging/uploads/")
|
|
}
|
|
}
|
|
|
|
func TestUploadRejectsTooLargeBody(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
|
|
MaxUploadBytes: 8, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
|
|
PipelineVersion: 1, MaxAttempts: 5,
|
|
}, slog.Default())
|
|
|
|
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
|
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
|
|
|
|
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
|
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
|
|
DeclaredContentType: "image/png",
|
|
Body: bytes.NewReader(bytes.Repeat([]byte("x"), 9)),
|
|
})
|
|
require.ErrorIs(t, err, domain.ErrTooLarge)
|
|
}
|
|
|
|
func TestUploadRejectsMIMEMismatch(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
|
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
|
|
|
|
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
|
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.jpg",
|
|
DeclaredContentType: "image/jpeg",
|
|
Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
|
})
|
|
require.ErrorIs(t, err, domain.ErrUnsupportedMedia)
|
|
}
|
|
|
|
func TestUploadAdmissionRejectsFlood(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
|
|
MaxUploadBytes: 1 << 20, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
|
|
PipelineVersion: 1, MaxAttempts: 5, MaxPendingPerUser: 1,
|
|
}, slog.Default())
|
|
|
|
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
|
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(1, 1, int64(0), nil).Once()
|
|
|
|
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
|
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
|
|
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
|
})
|
|
require.ErrorIs(t, err, domain.ErrRateLimited)
|
|
}
|
|
|
|
func TestGetReturnsQueuedSnapshotWithoutVariants(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
|
|
Return(domain.Attachment{Status: domain.AttachmentQueued, PipelineVersion: 1}, nil).Once()
|
|
|
|
got, err := service.Get(t.Context(), uuid.New(), uuid.New())
|
|
require.NoError(t, err)
|
|
require.Equal(t, domain.AttachmentQueued, got.Status)
|
|
require.Empty(t, got.Variants)
|
|
}
|
|
|
|
func TestGetReadyLoadsCurrentVariants(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
attachmentID := uuid.New()
|
|
variant := domain.Variant{Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 10, Width: 256, Height: 160, SHA256: strings.Repeat("a", 64)}
|
|
|
|
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, attachmentID).
|
|
Return(domain.Attachment{ID: attachmentID, Status: domain.AttachmentReady, PipelineVersion: 2}, nil).Once()
|
|
repo.EXPECT().ListVariants(mock.Anything, attachmentID, 2).Return([]domain.Variant{variant}, nil).Once()
|
|
|
|
got, err := service.Get(t.Context(), uuid.New(), attachmentID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, []domain.Variant{variant}, got.Variants)
|
|
}
|
|
|
|
func TestGetRejectsInternalPending(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
|
|
Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
|
|
|
_, err := service.Get(t.Context(), uuid.New(), uuid.New())
|
|
require.ErrorIs(t, err, domain.ErrConflict)
|
|
}
|
|
|
|
func TestOpenVariantRejectsQueued(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
|
|
Return(domain.Attachment{Status: domain.AttachmentQueued}, nil).Once()
|
|
|
|
_, _, _, err := service.OpenVariant(t.Context(), uuid.New(), uuid.New(), domain.VariantOriginal)
|
|
require.ErrorIs(t, err, domain.ErrConflict)
|
|
}
|
|
|
|
func TestCompleteQueuesPresignedObject(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
store := newFakeStore()
|
|
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
|
|
|
id := uuid.New()
|
|
chatID := uuid.New()
|
|
ownerID := uuid.New()
|
|
content := pngBytes(t, 10, 10)
|
|
sum := sha256.Sum256(content)
|
|
digest := hex.EncodeToString(sum[:])
|
|
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
|
|
|
store.objects[stagingKey] = storedObject{
|
|
data: content, contentType: "image/png",
|
|
metadata: map[string]string{"sha256": digest}, lastModified: time.Now().UTC(),
|
|
}
|
|
|
|
pending := domain.Attachment{
|
|
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
|
StagingKey: stagingKey, ContentType: "image/png",
|
|
SizeBytes: int64(len(content)), SHA256: digest,
|
|
Status: domain.AttachmentPending, PipelineVersion: 1,
|
|
}
|
|
|
|
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
|
repo.EXPECT().CompletePresign(
|
|
mock.Anything, ownerID, id,
|
|
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "staging/verified/") }),
|
|
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "attachments/") }),
|
|
1, 5, mock.Anything,
|
|
).Return(domain.Attachment{
|
|
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
|
|
SizeBytes: int64(len(content)), SHA256: digest,
|
|
Status: domain.AttachmentQueued, PipelineVersion: 1,
|
|
}, nil).Once()
|
|
|
|
completed, err := service.Complete(t.Context(), ownerID, id, digest)
|
|
require.NoError(t, err)
|
|
require.Equal(t, domain.AttachmentQueued, completed.Status)
|
|
require.NotContains(t, store.objects, stagingKey)
|
|
require.Len(t, store.objects, 1)
|
|
}
|
|
|
|
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
store := newFakeStore()
|
|
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
|
|
|
id := uuid.New()
|
|
chatID := uuid.New()
|
|
ownerID := uuid.New()
|
|
content := pngBytes(t, 10, 10)
|
|
sum := sha256.Sum256(content)
|
|
digest := hex.EncodeToString(sum[:])
|
|
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
|
|
|
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
|
|
|
|
pending := domain.Attachment{
|
|
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
|
StagingKey: stagingKey, ContentType: "image/png",
|
|
SizeBytes: int64(len(content)) + 1, SHA256: digest,
|
|
Status: domain.AttachmentPending, PipelineVersion: 1,
|
|
}
|
|
|
|
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
|
repo.EXPECT().DeletePending(mock.Anything, id).Return(nil).Once()
|
|
|
|
_, err := service.Complete(t.Context(), ownerID, id, digest)
|
|
require.ErrorIs(t, err, domain.ErrValidation)
|
|
require.NotContains(t, store.objects, stagingKey)
|
|
}
|
|
|
|
func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
store := newFakeStore()
|
|
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
|
|
|
id := uuid.New()
|
|
chatID := uuid.New()
|
|
ownerID := uuid.New()
|
|
content := pngBytes(t, 10, 10)
|
|
sum := sha256.Sum256(content)
|
|
digest := hex.EncodeToString(sum[:])
|
|
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
|
|
|
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
|
|
pending := domain.Attachment{
|
|
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
|
StagingKey: stagingKey, ContentType: "image/png",
|
|
SizeBytes: int64(len(content)), SHA256: digest,
|
|
Status: domain.AttachmentPending, PipelineVersion: 1,
|
|
}
|
|
|
|
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
|
|
|
_, err := service.Complete(t.Context(), ownerID, id, strings.Repeat("0", 64))
|
|
require.ErrorIs(t, err, domain.ErrConflict)
|
|
require.Contains(t, store.objects, stagingKey)
|
|
}
|
|
|
|
func TestPresignRejectsNonPositiveSize(t *testing.T) {
|
|
repo := mocks.NewMockRepository(t)
|
|
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
|
|
|
_, err := service.Presign(t.Context(), domain.PresignRequest{
|
|
ChatID: uuid.New(), OwnerID: uuid.New(),
|
|
Filename: "photo.png", ContentType: "image/png",
|
|
SizeBytes: 0, SHA256: strings.Repeat("a", 64),
|
|
})
|
|
require.ErrorIs(t, err, domain.ErrValidation)
|
|
}
|