lab5: исправления по ревью

Concurrent complete no longer deletes the shared verified source; admission is atomic and covers pending presign rows; relay reconciles queued jobs lost to dead-lettering; failed staging is protected until failed_retention; timestamps normalized to UTC; reprocess prefers the durable original and keeps job->attachment lock order; heartbeat errors no longer burn attempts; confirm timeout enforced; pinned images and sanitized health responses.
This commit is contained in:
Vladislav Kunetskiy
2026-10-30 23:13:44 +03:00
parent 4bdcac3dfa
commit 9d7a0acb5a
40 changed files with 592 additions and 521 deletions
+36 -24
View File
@@ -229,8 +229,8 @@ func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context
}
// CreatePresign provides a mock function for the type MockRepository
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft)
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, limits)
if len(ret) == 0 {
panic("no return value specified for CreatePresign")
@@ -238,16 +238,16 @@ func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.Att
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) domain.Attachment); ok {
r0 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft) error); ok {
r1 = returnFunc(ctx, draft)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, limits)
} else {
r1 = ret.Error(1)
}
@@ -262,11 +262,12 @@ type MockRepository_CreatePresign_Call struct {
// CreatePresign is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any, limits any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft, limits)}
}
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits)) *MockRepository_CreatePresign_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -276,9 +277,14 @@ func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, d
if args[1] != nil {
arg1 = args[1].(domain.AttachmentDraft)
}
var arg2 domain.AdmissionLimits
if args[2] != nil {
arg2 = args[2].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
@@ -289,14 +295,14 @@ func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment
return _c
}
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
_c.Call.Return(run)
return _c
}
// CreateQueued provides a mock function for the type MockRepository
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job)
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job, limits)
if len(ret) == 0 {
panic("no return value specified for CreateQueued")
@@ -304,16 +310,16 @@ func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.Atta
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job) error); ok {
r1 = returnFunc(ctx, draft, job)
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, job, limits)
} else {
r1 = ret.Error(1)
}
@@ -329,11 +335,12 @@ type MockRepository_CreateQueued_Call struct {
// - ctx context.Context
// - draft domain.AttachmentDraft
// - job domain.Job
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job)}
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any, limits any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job, limits)}
}
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits)) *MockRepository_CreateQueued_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
@@ -347,10 +354,15 @@ func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, dr
if args[2] != nil {
arg2 = args[2].(domain.Job)
}
var arg3 domain.AdmissionLimits
if args[3] != nil {
arg3 = args[3].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
@@ -361,7 +373,7 @@ func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment,
return _c
}
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
_c.Call.Return(run)
return _c
}
+36 -5
View File
@@ -52,8 +52,13 @@ type Repository interface {
ctx context.Context,
draft domain.AttachmentDraft,
job domain.Job,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
CompletePresign(
ctx context.Context,
ownerID, attachmentID uuid.UUID,
@@ -191,6 +196,8 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
CreatedAt: time.Now().UTC(),
}
limits := s.admissionLimits()
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
@@ -203,10 +210,16 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
SHA256: sum,
Status: domain.AttachmentQueued,
PipelineVersion: s.config.PipelineVersion,
}, job)
}, job, limits)
if err != nil {
s.deleteObject(ctx, id, stagingKey)
if errors.Is(err, domain.ErrRateLimited) {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, err
}
// An ambiguous COMMIT may have persisted the intent; leave the staging
// object for the sweeper instead of destroying a queued job's source.
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
@@ -357,7 +370,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
SHA256: request.SHA256,
Status: domain.AttachmentPending,
PipelineVersion: s.config.PipelineVersion,
}); err != nil {
}, s.admissionLimits()); err != nil {
return domain.PresignResult{}, err
}
@@ -511,7 +524,17 @@ func (s *Service) Complete(
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
s.deleteObject(ctx, id, verifiedKey)
// The verified key is shared by concurrent completions of this
// attachment. Never delete it here: a winning request may already have
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
if errors.Is(err, domain.ErrConflict) {
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
return s.withVariants(ctx, current)
}
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
}
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
@@ -530,6 +553,14 @@ func (s *Service) Complete(
// verifyStaging checks the freshly written object; a mismatch is a broken
// staging handoff and must never become a 202.
func (s *Service) admissionLimits() domain.AdmissionLimits {
return domain.AdmissionLimits{
PerUser: s.config.MaxPendingPerUser,
Total: s.config.MaxPending,
Bytes: s.config.MaxStagedBytes,
}
}
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
+84 -1
View File
@@ -189,7 +189,7 @@ func TestUploadStagesAndQueues(t *testing.T) {
}), mock.MatchedBy(func(job domain.Job) bool {
return job.PipelineVersion == 1 && job.Attempt == 1 &&
job.MaxAttempts == 5 && job.SourceKey != ""
})).Return(domain.Attachment{
}), domain.AdmissionLimits{}).Return(domain.Attachment{
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
@@ -355,6 +355,89 @@ func TestCompleteQueuesPresignedObject(t *testing.T) {
require.Len(t, store.objects, 1)
}
func TestCompleteConcurrentConflictKeepsVerifiedSource(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,
}
queued := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: "attachments/" + chatID.String() + "/" + id.String(),
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id, mock.Anything, mock.Anything,
1, 5, mock.Anything,
).Return(domain.Attachment{}, domain.ErrConflict).Once()
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(queued, nil).Once()
got, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
verified := 0
for key := range store.objects {
if strings.HasPrefix(key, "staging/verified/") {
verified++
}
}
require.Equal(t, 1, verified, "loser must not delete the winner's verified source")
}
func TestPresignHonoursAdmissionLimit(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().CreatePresign(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Presign(t.Context(), domain.PresignRequest{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("a", 64),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestUploadRateLimitedByAtomicAdmissionRemovesStaging(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, 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()
repo.EXPECT().CreateQueued(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).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)
require.Empty(t, store.objects, "a rejected atomic admission must not leave staging")
}
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()