лаба 4 на оценку 5

This commit is contained in:
2026-10-30 12:27:49 +03:00
parent 7860d81fa1
commit f9444a3965
59 changed files with 4696 additions and 90 deletions
@@ -0,0 +1,65 @@
package application
import (
"context"
"fmt"
"io"
"mtusi2026lab4/internal/domain"
)
type AttachmentDownload struct {
Body io.ReadCloser
ContentType string
Filename string
SizeBytes int64
}
func (s *Service) GetAttachment(
ctx context.Context,
attachmentID string,
actorID string,
) (domain.Attachment, error) {
return s.repository.GetAttachment(ctx, attachmentID, actorID)
}
func (s *Service) DownloadAttachment(
ctx context.Context,
attachmentID string,
actorID string,
variant string,
) (AttachmentDownload, error) {
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
if err != nil {
return AttachmentDownload{}, err
}
if attachment.Status != domain.AttachmentStatusReady {
return AttachmentDownload{}, ErrAttachmentNotReady
}
if variant == "" {
variant = "original"
}
if variant != "original" {
return AttachmentDownload{}, domain.ErrNotFound
}
if s.objectStore == nil {
return AttachmentDownload{}, ErrStorageUnavailable
}
object, err := s.objectStore.Get(ctx, attachment.ObjectKey)
if err != nil {
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
}
if object.Body == nil || object.SizeBytes != attachment.SizeBytes {
if object.Body != nil {
_ = object.Body.Close()
}
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
}
return AttachmentDownload{
Body: object.Body,
ContentType: attachment.ContentType,
Filename: attachment.Filename,
SizeBytes: attachment.SizeBytes,
}, nil
}
+246
View File
@@ -0,0 +1,246 @@
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)
}
+524
View File
@@ -0,0 +1,524 @@
package application_test
import (
"bytes"
"context"
"encoding/binary"
"errors"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"strings"
"sync"
"testing"
"time"
"mtusi2026lab4/internal/adapter/memory"
. "mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
type fakeObjectStore struct {
mu sync.Mutex
objects map[string][]byte
putError error
blockDelete bool
putCalls int
deleteCalls int
lastPutKey string
}
type alwaysFailReader struct{}
func (alwaysFailReader) Read([]byte) (int, error) {
return 0, errors.New("injected interrupted upload")
}
type finalizeFailureRepository struct {
Repository
}
func (repository *finalizeFailureRepository) MarkAttachmentReady(
context.Context,
string,
time.Time,
) (domain.Attachment, error) {
return domain.Attachment{}, errors.New("injected metadata finalize failure")
}
type commitThenDisconnectRepository struct {
Repository
hideReadback bool
}
func (repository *commitThenDisconnectRepository) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
if _, err := repository.Repository.MarkAttachmentReady(ctx, attachmentID, updatedAt); err != nil {
return domain.Attachment{}, err
}
return domain.Attachment{}, errors.New("injected connection loss after commit")
}
func (repository *commitThenDisconnectRepository) GetAttachment(
ctx context.Context,
attachmentID string,
actorID string,
) (domain.Attachment, error) {
if repository.hideReadback {
return domain.Attachment{}, errors.New("injected database outage during readback")
}
return repository.Repository.GetAttachment(ctx, attachmentID, actorID)
}
func newFakeObjectStore() *fakeObjectStore {
return &fakeObjectStore{objects: make(map[string][]byte)}
}
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
store.mu.Lock()
defer store.mu.Unlock()
store.putCalls++
store.lastPutKey = object.Key
if store.putError != nil {
return store.putError
}
payload, err := io.ReadAll(object.Body)
if err != nil {
return err
}
if int64(len(payload)) != object.SizeBytes {
return errors.New("declared object size differs")
}
store.objects[object.Key] = payload
return nil
}
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
store.mu.Lock()
defer store.mu.Unlock()
payload, exists := store.objects[key]
if !exists {
return ObjectContent{}, errors.New("object not found")
}
copyOfPayload := append([]byte(nil), payload...)
return ObjectContent{
Body: io.NopCloser(bytes.NewReader(copyOfPayload)),
SizeBytes: int64(len(copyOfPayload)),
}, nil
}
func (store *fakeObjectStore) Delete(ctx context.Context, key string) error {
store.mu.Lock()
store.deleteCalls++
blockDelete := store.blockDelete
store.mu.Unlock()
if blockDelete {
<-ctx.Done()
return ctx.Err()
}
store.mu.Lock()
defer store.mu.Unlock()
delete(store.objects, key)
return nil
}
func newAttachmentService(
t *testing.T,
objectStore ObjectStore,
) (*Service, *memory.MemoryStore, string, string) {
t.Helper()
legacyStore := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacyStore)
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
return service, legacyStore, user.ID, chat.ID
}
func encodeTestImage(t *testing.T, contentType string) []byte {
t.Helper()
var payload bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
img.Set(0, 0, color.RGBA{R: 255, A: 255})
var err error
if contentType == "image/png" {
err = png.Encode(&payload, img)
} else {
err = jpeg.Encode(&payload, img, nil)
}
if err != nil {
t.Fatal(err)
}
return payload.Bytes()
}
func corruptPNGAfterPrefix(t *testing.T) []byte {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, 512, 512))
state := uint32(0x12345678)
for index := range img.Pix {
state ^= state << 13
state ^= state >> 17
state ^= state << 5
img.Pix[index] = byte(state)
}
var payload bytes.Buffer
if err := png.Encode(&payload, img); err != nil {
t.Fatal(err)
}
corrupted := payload.Bytes()
if len(corrupted) <= 70_000 {
t.Fatalf("test PNG is unexpectedly small: %d", len(corrupted))
}
corrupted[70_000] ^= 0xff
return corrupted
}
func jpegWithoutScanData(t *testing.T) []byte {
t.Helper()
payload := encodeTestImage(t, "image/jpeg")
sos := bytes.Index(payload, []byte{0xff, 0xda})
if sos < 0 || sos+4 > len(payload) {
t.Fatal("encoded JPEG has no SOS marker")
}
segmentLength := int(binary.BigEndian.Uint16(payload[sos+2 : sos+4]))
endOfHeader := sos + 2 + segmentLength
if endOfHeader > len(payload) {
t.Fatal("invalid SOS segment length in test JPEG")
}
return append([]byte(nil), payload[:endOfHeader]...)
}
func TestUploadAttachmentStoresValidatedImage(t *testing.T) {
objectStore := newFakeObjectStore()
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
payload := encodeTestImage(t, "image/png")
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "кот.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(payload),
})
if err != nil {
t.Fatal(err)
}
if attachment.Status != domain.AttachmentStatusReady {
t.Fatalf("status = %q, want ready", attachment.Status)
}
if attachment.ObjectKey == "" || strings.Contains(attachment.ObjectKey, attachment.Filename) {
t.Fatalf("object key must be server-generated: %q", attachment.ObjectKey)
}
if attachment.Width != 2 || attachment.Height != 2 || len(attachment.SHA256) != 64 {
t.Fatalf("unexpected image metadata: %+v", attachment)
}
if !bytes.Equal(objectStore.objects[attachment.ObjectKey], payload) {
t.Fatal("stored object differs from uploaded bytes")
}
stored, err := metadataStore.GetAttachmentByID(attachment.ID)
if err != nil || stored.Status != domain.AttachmentStatusReady {
t.Fatalf("ready metadata was not persisted: %+v, %v", stored, err)
}
}
func TestUploadAttachmentRejectsInvalidInputBeforeStorage(t *testing.T) {
testCases := []struct {
name string
filename string
declaredType string
payload []byte
wantError error
}{
{name: "unsafe filename", filename: "../image.png", declaredType: "image/png", payload: encodeTestImage(t, "image/png"), wantError: ErrInvalidInput},
{name: "unsupported declared type", filename: "image.gif", declaredType: "image/gif", payload: []byte("GIF89a"), wantError: ErrUnsupportedMediaType},
{name: "MIME substitution", filename: "image.jpg", declaredType: "image/jpeg", payload: encodeTestImage(t, "image/png"), wantError: ErrUnsupportedMediaType},
{name: "corrupt image", filename: "image.png", declaredType: "image/png", payload: []byte("not a png"), wantError: ErrInvalidImage},
{name: "PNG header without image data", filename: "truncated.png", declaredType: "image/png", payload: pngConfigurationOnly(1, 1), wantError: ErrInvalidImage},
{name: "PNG corruption after 64 KiB", filename: "corrupted.png", declaredType: "image/png", payload: corruptPNGAfterPrefix(t), wantError: ErrInvalidImage},
{name: "JPEG without scan data", filename: "truncated.jpg", declaredType: "image/jpeg", payload: jpegWithoutScanData(t), wantError: ErrInvalidImage},
{name: "too large", filename: "image.png", declaredType: "image/png", payload: bytes.Repeat([]byte{0}, domain.MaxAttachmentSizeBytes+1), wantError: ErrPayloadTooLarge},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
objectStore := newFakeObjectStore()
service, _, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: testCase.filename,
DeclaredContentType: testCase.declaredType,
Body: bytes.NewReader(testCase.payload),
})
if !errors.Is(err, testCase.wantError) {
t.Fatalf("error = %v, want %v", err, testCase.wantError)
}
if objectStore.putCalls != 0 {
t.Fatalf("invalid upload reached object storage %d times", objectStore.putCalls)
}
})
}
}
func TestUploadAttachmentCompensatesObjectStoreFailure(t *testing.T) {
objectStore := newFakeObjectStore()
objectStore.putError = errors.New("injected put failure")
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "image.jpg",
DeclaredContentType: "image/jpeg",
Body: bytes.NewReader(encodeTestImage(t, "image/jpeg")),
})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error = %v, want ErrStorageUnavailable", err)
}
if objectStore.deleteCalls != 1 {
t.Fatalf("compensating deletes = %d, want 1", objectStore.deleteCalls)
}
objectStore.mu.Lock()
keyParts := strings.Split(objectStore.lastPutKey, "/")
objectStore.mu.Unlock()
if len(keyParts) != 4 {
t.Fatalf("unexpected generated object key: %q", objectStore.lastPutKey)
}
failedAttachment, lookupErr := metadataStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if failedAttachment.Status != domain.AttachmentStatusFailed || failedAttachment.ErrorCode == nil {
t.Fatalf("failed upload metadata was not finalized: %+v", failedAttachment)
}
}
func TestUploadAttachmentMarksFailedBeforeBlockedObjectCleanup(t *testing.T) {
objectStore := newFakeObjectStore()
objectStore.putError = errors.New("injected put failure")
objectStore.blockDelete = true
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
startedAt := time.Now()
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID, ChatID: chatID, Filename: "blocked-cleanup.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error = %v, want ErrStorageUnavailable", err)
}
if elapsed := time.Since(startedAt); elapsed > 2*time.Second {
t.Fatalf("bounded cleanup took %s", elapsed)
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
failed, lookupErr := metadataStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if failed.Status != domain.AttachmentStatusFailed || failed.ErrorCode == nil {
t.Fatalf("blocked object cleanup consumed DB cleanup context: %+v", failed)
}
}
func TestUploadAttachmentRejectsInterruptedBodyBeforeMetadata(t *testing.T) {
objectStore := newFakeObjectStore()
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
payload := encodeTestImage(t, "image/png")
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "interrupted.png",
DeclaredContentType: "image/png",
Body: io.MultiReader(bytes.NewReader(payload[:8]), alwaysFailReader{}),
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
if objectStore.putCalls != 0 {
t.Fatal("interrupted upload reached object storage")
}
if _, lookupErr := metadataStore.GetAttachmentByID("missing"); !errors.Is(lookupErr, domain.ErrNotFound) {
t.Fatalf("unexpected metadata lookup result: %v", lookupErr)
}
}
func TestUploadAttachmentPreservesObjectOnMetadataFinalizeFailure(t *testing.T) {
legacyStore := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacyStore)
user, err := repository.CreateUser(context.Background(), "finalize", "Finalize", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Finalize", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("finalize-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
service, err := NewService(
&finalizeFailureRepository{Repository: repository},
codec,
time.Hour,
WithObjectStore(objectStore),
)
if err != nil {
t.Fatal(err)
}
_, err = service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID,
ChatID: chat.ID,
Filename: "finalize.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err == nil {
t.Fatal("metadata finalize failure was hidden")
}
if objectStore.deleteCalls != 0 || len(objectStore.objects) != 1 {
t.Fatalf("ambiguous object must be preserved: deletes=%d objects=%d", objectStore.deleteCalls, len(objectStore.objects))
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
pending, lookupErr := legacyStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if pending.Status != domain.AttachmentStatusPending || pending.ErrorCode != nil {
t.Fatalf("ambiguous metadata must remain reconcilable: %+v", pending)
}
}
func TestUploadAttachmentRecoversWhenCommitResponseIsLost(t *testing.T) {
legacyStore := memory.NewMemoryStore()
baseRepository := memory.NewMemoryRepository(legacyStore)
user, err := baseRepository.CreateUser(context.Background(), "commit-lost", "Commit Lost", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := baseRepository.CreateChat(context.Background(), "Commit Lost", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("commit-lost-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
repository := &commitThenDisconnectRepository{Repository: baseRepository}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID, ChatID: chat.ID, Filename: "commit.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err != nil {
t.Fatalf("committed ready attachment was not recovered: %v", err)
}
if attachment.Status != domain.AttachmentStatusReady || len(objectStore.objects) != 1 || objectStore.deleteCalls != 0 {
t.Fatalf("lost commit response damaged attachment: attachment=%+v deletes=%d objects=%d",
attachment, objectStore.deleteCalls, len(objectStore.objects))
}
}
func TestUploadAttachmentNeverDeletesObjectAfterAmbiguousCommit(t *testing.T) {
legacyStore := memory.NewMemoryStore()
baseRepository := memory.NewMemoryRepository(legacyStore)
user, err := baseRepository.CreateUser(context.Background(), "commit-outage", "Commit Outage", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := baseRepository.CreateChat(context.Background(), "Commit Outage", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("commit-outage-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
repository := &commitThenDisconnectRepository{Repository: baseRepository, hideReadback: true}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
_, err = service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID, ChatID: chat.ID, Filename: "commit.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err == nil {
t.Fatal("database outage after commit was hidden")
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
stored, lookupErr := legacyStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if stored.Status != domain.AttachmentStatusReady || len(objectStore.objects) != 1 || objectStore.deleteCalls != 0 {
t.Fatalf("committed ready metadata lost its original: metadata=%+v deletes=%d objects=%d",
stored, objectStore.deleteCalls, len(objectStore.objects))
}
}
func TestUploadAttachmentRejectsPixelLimitBeforeFullDecode(t *testing.T) {
objectStore := newFakeObjectStore()
service, _, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "huge.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(pngConfigurationOnly(10_000, 4_001)),
})
if !errors.Is(err, ErrPayloadTooLarge) {
t.Fatalf("error = %v, want ErrPayloadTooLarge", err)
}
if objectStore.putCalls != 0 {
t.Fatalf("oversized decoded image reached object storage %d times", objectStore.putCalls)
}
}
func pngConfigurationOnly(width uint32, height uint32) []byte {
payload := make([]byte, 33)
copy(payload[0:8], []byte{137, 80, 78, 71, 13, 10, 26, 10})
binary.BigEndian.PutUint32(payload[8:12], 13)
copy(payload[12:16], "IHDR")
binary.BigEndian.PutUint32(payload[16:20], width)
binary.BigEndian.PutUint32(payload[20:24], height)
payload[24] = 8
payload[25] = 6
payload[26] = 0
payload[27] = 0
payload[28] = 0
binary.BigEndian.PutUint32(payload[29:33], crc32.ChecksumIEEE(payload[12:29]))
return payload
}
+11
View File
@@ -1,5 +1,7 @@
package application
import "io"
type CreateUserCommand struct {
Username string
DisplayName string
@@ -21,7 +23,16 @@ type SendMessageCommand struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
IdempotencyKey string
}
type UploadAttachmentCommand struct {
ActorID string
ChatID string
Filename string
DeclaredContentType string
Body io.Reader
}
+30 -4
View File
@@ -1,7 +1,9 @@
package application
import (
"encoding/base64"
"errors"
"strings"
"testing"
"time"
@@ -47,11 +49,13 @@ func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
t.Fatal(err)
}
replacement := "A"
if token[len(token)-1:] == replacement {
replacement = "B"
parts := strings.Split(token, ".")
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
t.Fatal(err)
}
tampered := token[:len(token)-1] + replacement
signature[0] ^= 1
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature)
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
}
@@ -68,3 +72,25 @@ func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
t.Fatal("expected short cursor signing key to be rejected")
}
}
func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf"
validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf"
testCases := []cursorPayload{
{Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID},
{Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID},
}
for _, payload := range testCases {
token, encodeErr := codec.encode(payload)
if encodeErr != nil {
t.Fatal(encodeErr)
}
if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) {
t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr)
}
}
}
+10 -5
View File
@@ -3,9 +3,14 @@ package application
import "errors"
var (
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrAttachmentNotReady = errors.New("attachment is not ready")
ErrPayloadTooLarge = errors.New("payload too large")
ErrUnsupportedMediaType = errors.New("unsupported media type")
ErrInvalidImage = errors.New("invalid image")
ErrStorageUnavailable = errors.New("object storage unavailable")
)
+13 -2
View File
@@ -7,6 +7,8 @@ import (
"fmt"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
)
type canonicalMessageRequest struct {
@@ -15,13 +17,21 @@ type canonicalMessageRequest struct {
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
if err := domain.ValidateMessageText(command.Text); err != nil {
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
if attachmentIDs == nil {
attachmentIDs = make([]string, 0)
}
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
for index, attachmentID := range attachmentIDs {
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: make([]string, 0),
AttachmentIDs: attachmentIDs,
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
@@ -31,6 +41,7 @@ func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
AttachmentIDs: attachmentIDs,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
+28
View File
@@ -2,6 +2,7 @@ package application
import (
"context"
"io"
"time"
"mtusi2026lab4/internal/domain"
@@ -28,6 +29,7 @@ type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
Key string
@@ -40,9 +42,35 @@ type MessageRepository interface {
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
}
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error)
MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error)
MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error
GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error)
}
type Repository interface {
UserRepository
SessionRepository
ChatRepository
MessageRepository
AttachmentRepository
}
type ObjectPut struct {
Key string
ContentType string
SizeBytes int64
Body io.Reader
}
type ObjectContent struct {
Body io.ReadCloser
SizeBytes int64
}
type ObjectStore interface {
Put(ctx context.Context, object ObjectPut) error
Get(ctx context.Context, key string) (ObjectContent, error)
Delete(ctx context.Context, key string) error
}
+30 -10
View File
@@ -6,15 +6,22 @@ import (
)
const MinimumIdempotencyTTL = 24 * time.Hour
const defaultAttachmentCleanupTimeout = time.Second
const defaultAttachmentUploadConcurrency = 4
const defaultAttachmentDecodeConcurrency = 1
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
objectStore ObjectStore
attachmentCleanupTimeout time.Duration
attachmentUploadSlots chan struct{}
attachmentDecodeSlots chan struct{}
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
@@ -28,11 +35,14 @@ func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Dur
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
}
for _, option := range options {
if err := option(service); err != nil {
@@ -51,3 +61,13 @@ func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return nil
}
}
func WithObjectStore(objectStore ObjectStore) ServiceOption {
return func(service *Service) error {
if objectStore == nil {
return fmt.Errorf("object store is required")
}
service.objectStore = objectStore
return nil
}
}