lab4: исправления по ревью
This commit is contained in:
@@ -207,7 +207,11 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType)
|
||||
}
|
||||
|
||||
if request.SizeBytes < 1 || request.SizeBytes > s.config.MaxUploadBytes {
|
||||
if request.SizeBytes < 1 {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes)
|
||||
}
|
||||
|
||||
if request.SizeBytes > s.config.MaxUploadBytes {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes)
|
||||
}
|
||||
|
||||
@@ -244,7 +248,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
|
||||
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, s.config.PresignTTL)
|
||||
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL)
|
||||
if err != nil {
|
||||
s.cleanupPending(ctx, id, "")
|
||||
|
||||
@@ -346,8 +350,8 @@ func (s *Service) Complete(
|
||||
}
|
||||
|
||||
if requestSHA != attachment.SHA256 {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
// The object is valid; only the completion request is inconsistent.
|
||||
// Keep the pending row and staging object so a retry can succeed.
|
||||
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
|
||||
}
|
||||
|
||||
@@ -454,6 +458,10 @@ func ValidateFilename(name string) error {
|
||||
return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if strings.ContainsAny(name, "/\\\x00") {
|
||||
return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation)
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PresignPut(_ context.Context, key string, ttl time.Duration) (string, time.Time, error) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func TestValidateFilename(t *testing.T) {
|
||||
require.NoError(t, attachment.ValidateFilename(name), name)
|
||||
}
|
||||
|
||||
invalid := []string{"", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"}
|
||||
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)
|
||||
}
|
||||
@@ -316,3 +316,46 @@ func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
||||
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,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -151,10 +151,18 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
}
|
||||
|
||||
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err == nil {
|
||||
stats.Recovered++
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil {
|
||||
// A transient database failure must not destroy a valid object.
|
||||
// Leave both the row and the object for the next sweep.
|
||||
s.log.WarnContext(ctx, "sweep recovery failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
stats.Recovered++
|
||||
continue
|
||||
}
|
||||
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package attachment_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -88,3 +89,38 @@ func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats)
|
||||
}
|
||||
|
||||
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-time.Hour)
|
||||
row := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
|
||||
store.objects[row.ObjectKey] = storedObject{
|
||||
data: []byte("abc"),
|
||||
lastModified: stale,
|
||||
metadata: map[string]string{"sha256": row.SHA256},
|
||||
}
|
||||
|
||||
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
|
||||
Return([]domain.Attachment{row}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey).
|
||||
Return(domain.Attachment{}, context.DeadlineExceeded).Once()
|
||||
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
|
||||
Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats.Recovered)
|
||||
require.Zero(t, stats.RowsDeleted)
|
||||
require.Contains(t, store.objects, row.ObjectKey)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user