lab5: асинхронная очередь, worker и идемпотентный pipeline
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.
This commit is contained in:
@@ -7,7 +7,6 @@ package mocks
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
@@ -49,12 +48,192 @@ func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
|
||||
// Admission provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Admission(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error) {
|
||||
ret := _mock.Called(ctx, ownerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Admission")
|
||||
}
|
||||
|
||||
var r0 int
|
||||
var r1 int
|
||||
var r2 int64
|
||||
var r3 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int, int, int64, error)); ok {
|
||||
return returnFunc(ctx, ownerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int); ok {
|
||||
r0 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(int)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) int); ok {
|
||||
r1 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r1 = ret.Get(1).(int)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID) int64); ok {
|
||||
r2 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r2 = ret.Get(2).(int64)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(3).(func(context.Context, uuid.UUID) error); ok {
|
||||
r3 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r3 = ret.Error(3)
|
||||
}
|
||||
return r0, r1, r2, r3
|
||||
}
|
||||
|
||||
// MockRepository_Admission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Admission'
|
||||
type MockRepository_Admission_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Admission is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) Admission(ctx any, ownerID any) *MockRepository_Admission_Call {
|
||||
return &MockRepository_Admission_Call{Call: _e.mock.On("Admission", ctx, ownerID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Admission_Call) Run(run func(ctx context.Context, ownerID uuid.UUID)) *MockRepository_Admission_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Admission_Call) Return(userPending int, totalPending int, stagedBytes int64, err error) *MockRepository_Admission_Call {
|
||||
_c.Call.Return(userPending, totalPending, stagedBytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Admission_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error)) *MockRepository_Admission_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// CompletePresign provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) CompletePresign(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CompletePresign")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_CompletePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompletePresign'
|
||||
type MockRepository_CompletePresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CompletePresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
// - attachmentID uuid.UUID
|
||||
// - verifiedKey string
|
||||
// - finalKey string
|
||||
// - pipelineVersion int
|
||||
// - maxAttempts int
|
||||
// - jobID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) CompletePresign(ctx any, ownerID any, attachmentID any, verifiedKey any, finalKey any, pipelineVersion any, maxAttempts any, jobID any) *MockRepository_CompletePresign_Call {
|
||||
return &MockRepository_CompletePresign_Call{Call: _e.mock.On("CompletePresign", ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID)) *MockRepository_CompletePresign_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
var arg4 string
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(string)
|
||||
}
|
||||
var arg5 int
|
||||
if args[5] != nil {
|
||||
arg5 = args[5].(int)
|
||||
}
|
||||
var arg6 int
|
||||
if args[6] != nil {
|
||||
arg6 = args[6].(int)
|
||||
}
|
||||
var arg7 uuid.UUID
|
||||
if args[7] != nil {
|
||||
arg7 = args[7].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
arg5,
|
||||
arg6,
|
||||
arg7,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CompletePresign_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error)) *MockRepository_CompletePresign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
panic("no return value specified for CreatePresign")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
@@ -75,19 +254,19 @@ func (_mock *MockRepository) Create(ctx context.Context, draft domain.Attachment
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
// MockRepository_CreatePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePresign'
|
||||
type MockRepository_CreatePresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// CreatePresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.AttachmentDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any) *MockRepository_CreatePresign_Call {
|
||||
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_Create_Call {
|
||||
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_CreatePresign_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
@@ -105,12 +284,84 @@ func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft do
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(attachment domain.Attachment, err error) *MockRepository_Create_Call {
|
||||
func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreatePresign_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_Create_Call {
|
||||
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (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)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CreateQueued")
|
||||
}
|
||||
|
||||
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.Attachment); ok {
|
||||
r0 = returnFunc(ctx, draft, job)
|
||||
} 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)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_CreateQueued_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateQueued'
|
||||
type MockRepository_CreateQueued_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CreateQueued is a helper method to define mock.On call
|
||||
// - 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)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job)) *MockRepository_CreateQueued_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.AttachmentDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.AttachmentDraft)
|
||||
}
|
||||
var arg2 domain.Job
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(domain.Job)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreateQueued_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
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 {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -316,6 +567,84 @@ func (_c *MockRepository_GetForOwner_Call) RunAndReturn(run func(ctx context.Con
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVariant provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetVariant(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error) {
|
||||
ret := _mock.Called(ctx, attachmentID, pipelineVersion, name)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVariant")
|
||||
}
|
||||
|
||||
var r0 domain.Variant
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) (domain.Variant, error)); ok {
|
||||
return returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) domain.Variant); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Variant)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int, domain.VariantName) error); ok {
|
||||
r1 = returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetVariant_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVariant'
|
||||
type MockRepository_GetVariant_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVariant is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - attachmentID uuid.UUID
|
||||
// - pipelineVersion int
|
||||
// - name domain.VariantName
|
||||
func (_e *MockRepository_Expecter) GetVariant(ctx any, attachmentID any, pipelineVersion any, name any) *MockRepository_GetVariant_Call {
|
||||
return &MockRepository_GetVariant_Call{Call: _e.mock.On("GetVariant", ctx, attachmentID, pipelineVersion, name)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName)) *MockRepository_GetVariant_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
var arg3 domain.VariantName
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(domain.VariantName)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) Return(variant domain.Variant, err error) *MockRepository_GetVariant_Call {
|
||||
_c.Call.Return(variant, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error)) *MockRepository_GetVariant_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// IsChatMember provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) IsChatMember(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error) {
|
||||
ret := _mock.Called(ctx, chatID, userID)
|
||||
@@ -388,196 +717,48 @@ func (_c *MockRepository_IsChatMember_Call) RunAndReturn(run func(ctx context.Co
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListKeys provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListKeys(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error) {
|
||||
ret := _mock.Called(ctx, limit, offset)
|
||||
// ListVariants provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error) {
|
||||
ret := _mock.Called(ctx, attachmentID, pipelineVersion)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListKeys")
|
||||
panic("no return value specified for ListVariants")
|
||||
}
|
||||
|
||||
var r0 []domain.AttachmentKey
|
||||
var r0 []domain.Variant
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) ([]domain.AttachmentKey, error)); ok {
|
||||
return returnFunc(ctx, limit, offset)
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) ([]domain.Variant, error)); ok {
|
||||
return returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) []domain.AttachmentKey); ok {
|
||||
r0 = returnFunc(ctx, limit, offset)
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) []domain.Variant); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.AttachmentKey)
|
||||
r0 = ret.Get(0).([]domain.Variant)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, int32, int32) error); ok {
|
||||
r1 = returnFunc(ctx, limit, offset)
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int) error); ok {
|
||||
r1 = returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListKeys'
|
||||
type MockRepository_ListKeys_Call struct {
|
||||
// MockRepository_ListVariants_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVariants'
|
||||
type MockRepository_ListVariants_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListKeys is a helper method to define mock.On call
|
||||
// ListVariants is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - limit int32
|
||||
// - offset int32
|
||||
func (_e *MockRepository_Expecter) ListKeys(ctx any, limit any, offset any) *MockRepository_ListKeys_Call {
|
||||
return &MockRepository_ListKeys_Call{Call: _e.mock.On("ListKeys", ctx, limit, offset)}
|
||||
// - attachmentID uuid.UUID
|
||||
// - pipelineVersion int
|
||||
func (_e *MockRepository_Expecter) ListVariants(ctx any, attachmentID any, pipelineVersion any) *MockRepository_ListVariants_Call {
|
||||
return &MockRepository_ListVariants_Call{Call: _e.mock.On("ListVariants", ctx, attachmentID, pipelineVersion)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) Run(run func(ctx context.Context, limit int32, offset int32)) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 int32
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(int32)
|
||||
}
|
||||
var arg2 int32
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int32)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) Return(attachmentKeys []domain.AttachmentKey, err error) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Return(attachmentKeys, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) RunAndReturn(run func(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error)) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStalePending provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, createdBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStalePending")
|
||||
}
|
||||
|
||||
var r0 []domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) ([]domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, createdBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) []domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.Attachment)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int32) error); ok {
|
||||
r1 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListStalePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStalePending'
|
||||
type MockRepository_ListStalePending_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStalePending is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - createdBefore time.Time
|
||||
// - limit int32
|
||||
func (_e *MockRepository_Expecter) ListStalePending(ctx any, createdBefore any, limit any) *MockRepository_ListStalePending_Call {
|
||||
return &MockRepository_ListStalePending_Call{Call: _e.mock.On("ListStalePending", ctx, createdBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int32)) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 time.Time
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(time.Time)
|
||||
}
|
||||
var arg2 int32
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int32)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) Return(attachments []domain.Attachment, err error) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Return(attachments, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStates provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error) {
|
||||
ret := _mock.Called(ctx, chatID, ids)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStates")
|
||||
}
|
||||
|
||||
var r0 []domain.AttachmentState
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) ([]domain.AttachmentState, error)); ok {
|
||||
return returnFunc(ctx, chatID, ids)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) []domain.AttachmentState); ok {
|
||||
r0 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.AttachmentState)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, []uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
|
||||
type MockRepository_ListStates_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStates is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - ids []uuid.UUID
|
||||
func (_e *MockRepository_Expecter) ListStates(ctx any, chatID any, ids any) *MockRepository_ListStates_Call {
|
||||
return &MockRepository_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockRepository_ListStates_Call {
|
||||
func (_c *MockRepository_ListVariants_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int)) *MockRepository_ListVariants_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
@@ -587,9 +768,9 @@ func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chat
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []uuid.UUID
|
||||
var arg2 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]uuid.UUID)
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
@@ -600,84 +781,12 @@ func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chat
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockRepository_ListStates_Call {
|
||||
_c.Call.Return(attachmentStates, err)
|
||||
func (_c *MockRepository_ListVariants_Call) Return(variants []domain.Variant, err error) *MockRepository_ListVariants_Call {
|
||||
_c.Call.Return(variants, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockRepository_ListStates_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// MarkReady provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, id, objectKey)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for MarkReady")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, id, objectKey)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, id, objectKey)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r1 = returnFunc(ctx, id, objectKey)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_MarkReady_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkReady'
|
||||
type MockRepository_MarkReady_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// MarkReady is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
// - objectKey string
|
||||
func (_e *MockRepository_Expecter) MarkReady(ctx any, id any, objectKey any) *MockRepository_MarkReady_Call {
|
||||
return &MockRepository_MarkReady_Call{Call: _e.mock.On("MarkReady", ctx, id, objectKey)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) Run(run func(ctx context.Context, id uuid.UUID, objectKey string)) *MockRepository_MarkReady_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) Return(attachment domain.Attachment, err error) *MockRepository_MarkReady_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)) *MockRepository_MarkReady_Call {
|
||||
func (_c *MockRepository_ListVariants_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)) *MockRepository_ListVariants_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSweepRepository creates a new instance of MockSweepRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSweepRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSweepRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSweepRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSweepRepository is an autogenerated mock type for the SweepRepository type
|
||||
type MockSweepRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSweepRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSweepRepository) EXPECT() *MockSweepRepository_Expecter {
|
||||
return &MockSweepRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// DeletePending provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for DeletePending")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) error); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSweepRepository_DeletePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePending'
|
||||
type MockSweepRepository_DeletePending_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// DeletePending is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockSweepRepository_Expecter) DeletePending(ctx any, id any) *MockSweepRepository_DeletePending_Call {
|
||||
return &MockSweepRepository_DeletePending_Call{Call: _e.mock.On("DeletePending", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_DeletePending_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockSweepRepository_DeletePending_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_DeletePending_Call) Return(err error) *MockSweepRepository_DeletePending_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_DeletePending_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) error) *MockSweepRepository_DeletePending_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListPendingPresign provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, createdBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListPendingPresign")
|
||||
}
|
||||
|
||||
var r0 []domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) ([]domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, createdBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) []domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.Attachment)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int) error); ok {
|
||||
r1 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListPendingPresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPendingPresign'
|
||||
type MockSweepRepository_ListPendingPresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListPendingPresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - createdBefore time.Time
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListPendingPresign(ctx any, createdBefore any, limit any) *MockSweepRepository_ListPendingPresign_Call {
|
||||
return &MockSweepRepository_ListPendingPresign_Call{Call: _e.mock.On("ListPendingPresign", ctx, createdBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int)) *MockSweepRepository_ListPendingPresign_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 time.Time
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(time.Time)
|
||||
}
|
||||
var arg2 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) Return(attachments []domain.Attachment, err error) *MockSweepRepository_ListPendingPresign_Call {
|
||||
_c.Call.Return(attachments, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)) *MockSweepRepository_ListPendingPresign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListReferencedKeys provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error) {
|
||||
ret := _mock.Called(ctx, afterKey, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListReferencedKeys")
|
||||
}
|
||||
|
||||
var r0 []string
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) ([]string, error)); ok {
|
||||
return returnFunc(ctx, afterKey, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) []string); ok {
|
||||
r0 = returnFunc(ctx, afterKey, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, int) error); ok {
|
||||
r1 = returnFunc(ctx, afterKey, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListReferencedKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListReferencedKeys'
|
||||
type MockSweepRepository_ListReferencedKeys_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListReferencedKeys is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - afterKey string
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListReferencedKeys(ctx any, afterKey any, limit any) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
return &MockSweepRepository_ListReferencedKeys_Call{Call: _e.mock.On("ListReferencedKeys", ctx, afterKey, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) Run(run func(ctx context.Context, afterKey string, limit int)) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) Return(strings []string, err error) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
_c.Call.Return(strings, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) RunAndReturn(run func(ctx context.Context, afterKey string, limit int) ([]string, error)) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStaleStaging provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListStaleStaging(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error) {
|
||||
ret := _mock.Called(ctx, readyBefore, failedBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStaleStaging")
|
||||
}
|
||||
|
||||
var r0 []domain.StaleStaging
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) ([]domain.StaleStaging, error)); ok {
|
||||
return returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) []domain.StaleStaging); ok {
|
||||
r0 = returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.StaleStaging)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, time.Time, int) error); ok {
|
||||
r1 = returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListStaleStaging_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStaleStaging'
|
||||
type MockSweepRepository_ListStaleStaging_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStaleStaging is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - readyBefore time.Time
|
||||
// - failedBefore time.Time
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListStaleStaging(ctx any, readyBefore any, failedBefore any, limit any) *MockSweepRepository_ListStaleStaging_Call {
|
||||
return &MockSweepRepository_ListStaleStaging_Call{Call: _e.mock.On("ListStaleStaging", ctx, readyBefore, failedBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) Run(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int)) *MockSweepRepository_ListStaleStaging_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 time.Time
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(time.Time)
|
||||
}
|
||||
var arg2 time.Time
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(time.Time)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) Return(staleStagings []domain.StaleStaging, err error) *MockSweepRepository_ListStaleStaging_Call {
|
||||
_c.Call.Return(staleStagings, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) RunAndReturn(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)) *MockSweepRepository_ListStaleStaging_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// MarkStagingDeleted provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error {
|
||||
ret := _mock.Called(ctx, attachmentID, stagingKey)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for MarkStagingDeleted")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, stagingKey)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSweepRepository_MarkStagingDeleted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkStagingDeleted'
|
||||
type MockSweepRepository_MarkStagingDeleted_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// MarkStagingDeleted is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - attachmentID uuid.UUID
|
||||
// - stagingKey string
|
||||
func (_e *MockSweepRepository_Expecter) MarkStagingDeleted(ctx any, attachmentID any, stagingKey any) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
return &MockSweepRepository_MarkStagingDeleted_Call{Call: _e.mock.On("MarkStagingDeleted", ctx, attachmentID, stagingKey)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_MarkStagingDeleted_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string)) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_MarkStagingDeleted_Call) Return(err error) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_MarkStagingDeleted_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -27,32 +27,55 @@ const (
|
||||
contentTypePNG = "image/png"
|
||||
contentTypeJPEG = "image/jpeg"
|
||||
|
||||
objectPrefixAttachments = "attachments/"
|
||||
objectPrefixStaging = "staging/"
|
||||
objectPrefixPresign = "staging/presign/"
|
||||
objectPrefixAttachments = domain.AttachmentsPrefix
|
||||
objectPrefixStaging = domain.StagingUploadPrefix
|
||||
objectPrefixPresign = domain.StagingPresignPrefix
|
||||
)
|
||||
|
||||
var sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
|
||||
// Repository is the persistence port. It is consumer-side so the service can be
|
||||
// tested without PostgreSQL.
|
||||
// tested without PostgreSQL. Job/outbox writes are atomic with the attachment
|
||||
// row inside CreateQueued/CompletePresign.
|
||||
type Repository interface {
|
||||
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
|
||||
MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
|
||||
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
|
||||
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
|
||||
ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)
|
||||
ListKeys(ctx context.Context, limit, offset int32) ([]domain.AttachmentKey, error)
|
||||
ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)
|
||||
GetVariant(
|
||||
ctx context.Context,
|
||||
attachmentID uuid.UUID,
|
||||
pipelineVersion int,
|
||||
name domain.VariantName,
|
||||
) (domain.Variant, error)
|
||||
CreateQueued(
|
||||
ctx context.Context,
|
||||
draft domain.AttachmentDraft,
|
||||
job domain.Job,
|
||||
) (domain.Attachment, error)
|
||||
CreatePresign(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
|
||||
CompletePresign(
|
||||
ctx context.Context,
|
||||
ownerID, attachmentID uuid.UUID,
|
||||
verifiedKey, finalKey string,
|
||||
pipelineVersion, maxAttempts int,
|
||||
jobID uuid.UUID,
|
||||
) (domain.Attachment, error)
|
||||
Admission(ctx context.Context, ownerID uuid.UUID) (userPending, totalPending int, stagedBytes int64, err error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
}
|
||||
|
||||
// Config carries the attachment limits. They are validated by config.Load.
|
||||
// Config carries attachment limits and the shared job contract knobs.
|
||||
type Config struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
PresignTTL time.Duration
|
||||
|
||||
PipelineVersion int
|
||||
MaxAttempts int
|
||||
MaxPendingPerUser int
|
||||
MaxPending int
|
||||
MaxStagedBytes int64
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
@@ -80,6 +103,8 @@ type UploadInput struct {
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
// Upload durably stages the original, records the job intent and returns the
|
||||
// queued snapshot. It never waits for the broker or the worker.
|
||||
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
|
||||
if err := ValidateFilename(input.Filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
@@ -94,6 +119,17 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
|
||||
return domain.Attachment{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
userPending, totalPending, stagedBytes, err := s.repo.Admission(ctx, input.OwnerID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, unavailable("check admission", err)
|
||||
}
|
||||
|
||||
if (s.config.MaxPendingPerUser > 0 && userPending >= s.config.MaxPendingPerUser) ||
|
||||
(s.config.MaxPending > 0 && totalPending >= s.config.MaxPending) ||
|
||||
(s.config.MaxStagedBytes > 0 && stagedBytes >= s.config.MaxStagedBytes) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: too many unfinished uploads", domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
file, size, sum, err := s.spool(input.Body)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
@@ -123,79 +159,153 @@ func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachm
|
||||
return domain.Attachment{}, fmt.Errorf("generate attachment id: %w", err)
|
||||
}
|
||||
|
||||
objectKey := objectPrefixAttachments + input.ChatID.String() + "/" + id.String()
|
||||
|
||||
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
OwnerID: input.OwnerID,
|
||||
ObjectKey: objectKey,
|
||||
Filename: input.Filename,
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
}); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
|
||||
}
|
||||
|
||||
stagingKey := domain.StagingUploadKey(input.ChatID, id)
|
||||
finalKey := domain.OriginalObjectKey(input.ChatID, id)
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
|
||||
}
|
||||
|
||||
if err := s.store.Put(ctx, objectKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
s.cleanupPending(ctx, id, "")
|
||||
|
||||
return domain.Attachment{}, unavailable("store attachment", err)
|
||||
if err := s.store.Put(ctx, stagingKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("store staging object", err)
|
||||
}
|
||||
|
||||
ready, err := s.repo.MarkReady(ctx, id, objectKey)
|
||||
if err := s.verifyStaging(ctx, stagingKey, size, sum); err != nil {
|
||||
s.deleteObject(ctx, id, stagingKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("verify staging object", err)
|
||||
}
|
||||
|
||||
job := domain.Job{
|
||||
ID: jobID,
|
||||
AttachmentID: id,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
SourceKey: stagingKey,
|
||||
Attempt: 1,
|
||||
MaxAttempts: s.config.MaxAttempts,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
OwnerID: input.OwnerID,
|
||||
ObjectKey: finalKey,
|
||||
StagingKey: stagingKey,
|
||||
Filename: input.Filename,
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
Status: domain.AttachmentQueued,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
}, job)
|
||||
if err != nil {
|
||||
// The object and the pending row remain; the sweeper either finalises
|
||||
// the row or removes both after the grace period. The client must not
|
||||
// receive 201 until metadata is committed.
|
||||
return domain.Attachment{}, unavailable("commit attachment", err)
|
||||
s.deleteObject(ctx, id, stagingKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("commit attachment intent", err)
|
||||
}
|
||||
|
||||
return ready, nil
|
||||
created.Variants = []domain.Variant{}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// Get returns metadata for any public status. Variants are exposed only for the
|
||||
// currently published pipeline version and only when ready.
|
||||
func (s *Service) Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error) {
|
||||
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
// Contract 1.4.0 declares Attachment.status as the single value "ready".
|
||||
// Pending/failed rows therefore cannot be represented in a 200 response;
|
||||
// they are reported as 409 until lab5 extends the enum.
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
if !attachment.Status.Public() {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
return s.withVariants(ctx, attachment)
|
||||
}
|
||||
|
||||
// Open returns metadata and the original stream. Only ready attachments have
|
||||
// bytes; pending/failed return 409 on the content endpoint.
|
||||
func (s *Service) Open(
|
||||
// OpenVariant returns metadata plus the selected content stream. Only a ready
|
||||
// attachment has bytes.
|
||||
func (s *Service) OpenVariant(
|
||||
ctx context.Context,
|
||||
callerID, id uuid.UUID,
|
||||
) (domain.Attachment, io.ReadCloser, error) {
|
||||
name domain.VariantName,
|
||||
) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
|
||||
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
if !attachment.Status.Public() || attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
|
||||
"%w: attachment is %s", domain.ErrConflict, attachment.Status,
|
||||
)
|
||||
}
|
||||
|
||||
if name == "" || name == domain.VariantOriginal {
|
||||
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
return attachment, domain.Variant{
|
||||
Name: domain.VariantOriginal,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
ObjectKey: attachment.ObjectKey,
|
||||
}, body, nil
|
||||
}
|
||||
|
||||
if !name.Valid() {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
|
||||
"%w: variant %q", domain.ErrValidation, name,
|
||||
)
|
||||
}
|
||||
|
||||
variant, err := s.repo.GetVariant(ctx, attachment.ID, attachment.PipelineVersion, name)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
body, _, err := s.store.Open(ctx, variant.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
return attachment, variant, body, nil
|
||||
}
|
||||
|
||||
// Open is kept for the legacy service port used by tests.
|
||||
func (s *Service) Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
|
||||
attachment, _, body, err := s.OpenVariant(ctx, callerID, id, domain.VariantOriginal)
|
||||
|
||||
return attachment, body, err
|
||||
}
|
||||
|
||||
func (s *Service) withVariants(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error) {
|
||||
attachment.Variants = []domain.Variant{}
|
||||
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
||||
variants, err := s.repo.ListVariants(ctx, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
return attachment, body, nil
|
||||
if variants != nil {
|
||||
attachment.Variants = variants
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
|
||||
@@ -235,15 +345,18 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
|
||||
stagingKey := objectPrefixPresign + request.ChatID.String() + "/" + id.String()
|
||||
|
||||
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: request.ChatID,
|
||||
OwnerID: request.OwnerID,
|
||||
ObjectKey: stagingKey,
|
||||
Filename: request.Filename,
|
||||
ContentType: request.ContentType,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
if _, err := s.repo.CreatePresign(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: request.ChatID,
|
||||
OwnerID: request.OwnerID,
|
||||
ObjectKey: stagingKey,
|
||||
StagingKey: stagingKey,
|
||||
Filename: request.Filename,
|
||||
ContentType: request.ContentType,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
Status: domain.AttachmentPending,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
}); err != nil {
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
@@ -264,6 +377,10 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Complete verifies the presigned object, copies the verified bytes to a
|
||||
// server-owned staging key, and enqueues the same async pipeline as the proxy
|
||||
// upload. The client's staging key remains writable until the verified copy is
|
||||
// durable.
|
||||
func (s *Service) Complete(
|
||||
ctx context.Context,
|
||||
ownerID, id uuid.UUID,
|
||||
@@ -279,12 +396,12 @@ func (s *Service) Complete(
|
||||
}
|
||||
|
||||
switch attachment.Status {
|
||||
case domain.AttachmentReady:
|
||||
case domain.AttachmentReady, domain.AttachmentQueued, domain.AttachmentProcessing:
|
||||
if attachment.SHA256 != requestSHA {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
return s.withVariants(ctx, attachment)
|
||||
case domain.AttachmentFailed:
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is failed", domain.ErrConflict)
|
||||
case domain.AttachmentPending:
|
||||
@@ -319,18 +436,31 @@ func (s *Service) Complete(
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
hasher := sha256.New()
|
||||
info, validateErr := imagecheck.Validate(io.TeeReader(body, hasher), s.config.MaxImagePixels)
|
||||
closeErr := body.Close()
|
||||
file, size, sum, err := s.spool(body)
|
||||
_ = body.Close()
|
||||
|
||||
if validateErr != nil {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, mapImageError(validateErr)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return domain.Attachment{}, unavailable("read uploaded object", closeErr)
|
||||
defer func() { _ = file.Close() }()
|
||||
defer func() { _ = os.Remove(file.Name()) }()
|
||||
|
||||
if size != attachment.SizeBytes {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf("%w: uploaded object size changed", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind uploaded object: %w", err)
|
||||
}
|
||||
|
||||
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
|
||||
if err != nil {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, mapImageError(err)
|
||||
}
|
||||
|
||||
if info.ContentType != attachment.ContentType {
|
||||
@@ -342,7 +472,6 @@ func (s *Service) Complete(
|
||||
)
|
||||
}
|
||||
|
||||
sum := hex.EncodeToString(hasher.Sum(nil))
|
||||
if sum != attachment.SHA256 {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
@@ -350,43 +479,76 @@ func (s *Service) Complete(
|
||||
}
|
||||
|
||||
if requestSHA != attachment.SHA256 {
|
||||
// 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)
|
||||
}
|
||||
|
||||
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
|
||||
verifiedKey := domain.StagingVerifiedKey(attachment.ChatID, attachment.ID)
|
||||
finalKey := domain.OriginalObjectKey(attachment.ChatID, attachment.ID)
|
||||
|
||||
if err := s.store.Copy(ctx, attachment.ObjectKey, finalKey, attachment.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("publish attachment", err)
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind verified object: %w", err)
|
||||
}
|
||||
|
||||
ready, err := s.repo.MarkReady(ctx, id, finalKey)
|
||||
if err := s.store.Put(ctx, verifiedKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("store verified object", err)
|
||||
}
|
||||
|
||||
if err := s.verifyStaging(ctx, verifiedKey, size, sum); err != nil {
|
||||
s.deleteObject(ctx, id, verifiedKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("verify staging object", err)
|
||||
}
|
||||
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
// A concurrent completion may have won. Re-read instead of reporting a
|
||||
// spurious failure.
|
||||
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
|
||||
if getErr == nil && current.Status == domain.AttachmentReady && current.SHA256 == requestSHA {
|
||||
return current, nil
|
||||
}
|
||||
s.deleteObject(ctx, id, verifiedKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("commit attachment", err)
|
||||
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil {
|
||||
// The final object is already committed; a stale staging object is an
|
||||
// orphan and the sweeper removes it after the grace period.
|
||||
s.log.WarnContext(ctx, "staging object cleanup failed",
|
||||
queued, err := s.repo.CompletePresign(
|
||||
ctx, ownerID, id, verifiedKey, finalKey,
|
||||
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
|
||||
)
|
||||
if err != nil {
|
||||
s.deleteObject(ctx, id, verifiedKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("commit presigned attachment", err)
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "presign staging cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
return ready, nil
|
||||
queued.Variants = []domain.Variant{}
|
||||
|
||||
return queued, nil
|
||||
}
|
||||
|
||||
// verifyStaging checks the freshly written object; a mismatch is a broken
|
||||
// staging handoff and must never become a 202.
|
||||
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
|
||||
head, err := s.store.Head(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("head staging object: %w", err)
|
||||
}
|
||||
|
||||
if head.Size != size {
|
||||
return fmt.Errorf("staging size %d, want %d", head.Size, size)
|
||||
}
|
||||
|
||||
if sha := head.Metadata["sha256"]; sha != "" && sha != sum {
|
||||
return errors.New("staging checksum metadata does not match")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "lab4-upload-*")
|
||||
file, err := os.CreateTemp("", "lab5-upload-*")
|
||||
if err != nil {
|
||||
return nil, 0, "", fmt.Errorf("create upload spool: %w", err)
|
||||
}
|
||||
@@ -427,16 +589,22 @@ func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
|
||||
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
|
||||
if objectKey != "" {
|
||||
if err := s.store.Delete(ctx, objectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "object cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
func (s *Service) deleteObject(ctx context.Context, id uuid.UUID, key string) {
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, key); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "object cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
|
||||
s.deleteObject(ctx, id, objectKey)
|
||||
|
||||
if err := s.repo.DeletePending(ctx, id); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "pending attachment cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
|
||||
@@ -71,6 +71,8 @@ func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectst
|
||||
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 {
|
||||
@@ -144,9 +146,11 @@ func pngBytes(t *testing.T, width, height int) []byte {
|
||||
|
||||
func serviceConfig() attachment.Config {
|
||||
return attachment.Config{
|
||||
MaxUploadBytes: 1 << 20,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: 5 * time.Minute,
|
||||
MaxUploadBytes: 1 << 20,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: 5 * time.Minute,
|
||||
PipelineVersion: 1,
|
||||
MaxAttempts: 5,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +166,7 @@ func TestValidateFilename(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadStoresOriginal(t *testing.T) {
|
||||
func TestUploadStagesAndQueues(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
@@ -171,16 +175,25 @@ func TestUploadStoresOriginal(t *testing.T) {
|
||||
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().Create(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
|
||||
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 == hex.EncodeToString(sum[:]) && strings.HasPrefix(draft.ObjectKey, "attachments/")
|
||||
})).Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{Status: domain.AttachmentReady, ContentType: "image/png", SizeBytes: int64(len(content))}, nil).
|
||||
Once()
|
||||
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,
|
||||
@@ -190,28 +203,28 @@ func TestUploadStoresOriginal(t *testing.T) {
|
||||
Body: bytes.NewReader(content),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentReady, result.Status)
|
||||
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,
|
||||
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",
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -220,19 +233,63 @@ func TestUploadRejectsMIMEMismatch(t *testing.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",
|
||||
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 TestGetRejectsNonReadyAttachment(t *testing.T) {
|
||||
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())
|
||||
|
||||
@@ -243,7 +300,18 @@ func TestGetRejectsNonReadyAttachment(t *testing.T) {
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func TestCompletePublishesPresignedObject(t *testing.T) {
|
||||
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())
|
||||
@@ -257,29 +325,32 @@ func TestCompletePublishesPresignedObject(t *testing.T) {
|
||||
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(),
|
||||
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,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
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().MarkReady(mock.Anything, id, mock.MatchedBy(func(key string) bool {
|
||||
return strings.HasPrefix(key, "attachments/")
|
||||
})).Return(domain.Attachment{
|
||||
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.AttachmentReady,
|
||||
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.AttachmentReady, completed.Status)
|
||||
require.Equal(t, domain.AttachmentQueued, completed.Status)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
@@ -297,16 +368,13 @@ func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
||||
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},
|
||||
}
|
||||
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)) + 1, SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
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()
|
||||
@@ -330,15 +398,12 @@ func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) {
|
||||
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},
|
||||
}
|
||||
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,
|
||||
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()
|
||||
|
||||
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
@@ -16,26 +17,38 @@ type LockStore interface {
|
||||
AcquireSweepLock(ctx context.Context) (release func(), acquired bool, err error)
|
||||
}
|
||||
|
||||
// SweepRepository is the storage port used by cleanup. It exposes only
|
||||
// read/delete projections; object bytes still live in S3.
|
||||
type SweepRepository interface {
|
||||
ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
ListStaleStaging(ctx context.Context, readyBefore, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)
|
||||
MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error
|
||||
ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
type SweepStats struct {
|
||||
Recovered int
|
||||
RowsDeleted int
|
||||
ObjectsDeleted int
|
||||
StagingCleared int
|
||||
}
|
||||
|
||||
type Sweeper struct {
|
||||
repo Repository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
repo SweepRepository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
orphanGrace time.Duration
|
||||
failedRetain time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSweeper(
|
||||
repo Repository,
|
||||
repo SweepRepository,
|
||||
store objectstore.Store,
|
||||
locker LockStore,
|
||||
grace, interval time.Duration,
|
||||
grace, orphanGrace, failedRetain, interval time.Duration,
|
||||
log *slog.Logger,
|
||||
) *Sweeper {
|
||||
if log == nil {
|
||||
@@ -43,12 +56,14 @@ func NewSweeper(
|
||||
}
|
||||
|
||||
return &Sweeper{
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
interval: interval,
|
||||
log: log,
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
orphanGrace: orphanGrace,
|
||||
failedRetain: failedRetain,
|
||||
interval: interval,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,18 +92,18 @@ func (s *Sweeper) sweep(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if stats.Recovered+stats.RowsDeleted+stats.ObjectsDeleted > 0 {
|
||||
if stats.RowsDeleted+stats.ObjectsDeleted+stats.StagingCleared > 0 {
|
||||
s.log.InfoContext(ctx, "attachment sweep finished",
|
||||
slog.Int("recovered", stats.Recovered),
|
||||
slog.Int("rows_deleted", stats.RowsDeleted),
|
||||
slog.Int("objects_deleted", stats.ObjectsDeleted),
|
||||
slog.Int("staging_cleared", stats.StagingCleared),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// SweepOnce reconciles PostgreSQL metadata with S3 objects. It never deletes a
|
||||
// ready row or an object referenced by any row. Only objects older than the
|
||||
// grace period are candidates, so an in-flight upload cannot be collected.
|
||||
// SweepOnce applies explicit, status-aware retention rules. It never deletes
|
||||
// staging of a queued/processing attachment and aborts object collection if any
|
||||
// database page or S3 listing fails.
|
||||
func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
release, acquired, err := s.locker.AcquireSweepLock(ctx)
|
||||
if err != nil {
|
||||
@@ -101,72 +116,20 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
|
||||
defer release()
|
||||
|
||||
before := time.Now().UTC().Add(-s.grace)
|
||||
|
||||
now := time.Now().UTC()
|
||||
var stats SweepStats
|
||||
|
||||
stale, err := s.repo.ListStalePending(ctx, before, 100)
|
||||
// Abandoned presign rows: no completion ever arrived.
|
||||
pending, err := s.repo.ListPendingPresign(ctx, now.Add(-s.grace), 100)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if row.Status != domain.AttachmentPending {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(row.ObjectKey, objectPrefixPresign) {
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
for _, row := range pending {
|
||||
if row.StagingKey != "" {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
// A proxy upload writes directly to its final key. If the process died
|
||||
// between PutObject and MarkReady, the object is complete and can be
|
||||
// recovered instead of discarded.
|
||||
head, err := s.store.Head(ctx, row.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
s.log.WarnContext(ctx, "sweep head failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
|
||||
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) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
@@ -176,12 +139,40 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
stats.RowsDeleted++
|
||||
}
|
||||
|
||||
// Ready/failed rows keep their staging key until the object is safely
|
||||
// removed. Active queued/processing staging is never in this list.
|
||||
stale, err := s.repo.ListStaleStaging(
|
||||
ctx, now.Add(-s.orphanGrace), now.Add(-s.failedRetain), 100,
|
||||
)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.MarkStagingDeleted(ctx, row.AttachmentID, row.StagingKey); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.StagingCleared++
|
||||
}
|
||||
|
||||
referenced, err := s.referencedKeys(ctx)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, prefix := range []string{objectPrefixAttachments, objectPrefixStaging} {
|
||||
// Orphans: objects no row references. Final objects and variants use the
|
||||
// normal grace; staging uses the longer orphan grace.
|
||||
for _, prefix := range []string{domain.AttachmentsPrefix, "staging/"} {
|
||||
before := now.Add(-s.grace)
|
||||
if prefix == "staging/" {
|
||||
before = now.Add(-s.orphanGrace)
|
||||
}
|
||||
|
||||
objects, err := s.store.List(ctx, prefix)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
@@ -209,20 +200,23 @@ func (s *Sweeper) referencedKeys(ctx context.Context) (map[string]struct{}, erro
|
||||
const pageSize = 1000
|
||||
|
||||
keys := make(map[string]struct{})
|
||||
after := ""
|
||||
|
||||
for offset := int32(0); ; offset += pageSize {
|
||||
rows, err := s.repo.ListKeys(ctx, pageSize, offset)
|
||||
for {
|
||||
rows, err := s.repo.ListReferencedKeys(ctx, after, pageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
keys[row.ObjectKey] = struct{}{}
|
||||
for _, key := range rows {
|
||||
keys[key] = struct{}{}
|
||||
}
|
||||
|
||||
if len(rows) < pageSize {
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
after = rows[len(rows)-1]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,73 +15,71 @@ import (
|
||||
"mtusi-messenger/internal/service/attachment/mocks"
|
||||
)
|
||||
|
||||
func TestSweepReconcilesPendingAndOrphanObjects(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
func TestSweepAppliesStatusAwareRetention(t *testing.T) {
|
||||
repo := mocks.NewMockSweepRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-time.Hour)
|
||||
stale := time.Now().UTC().Add(-2 * time.Hour)
|
||||
|
||||
presign := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "staging/presign/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
ID: uuid.New(), StagingKey: "staging/presign/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
proxyRecoverable := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
staleStaging := domain.StaleStaging{
|
||||
AttachmentID: uuid.New(), StagingKey: "staging/uploads/chat/ready", Status: domain.AttachmentReady,
|
||||
}
|
||||
proxyMissing := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
readyKey := "attachments/chat/ready"
|
||||
activeStaging := "staging/uploads/chat/active"
|
||||
readyKey := "attachments/chat/ready/original"
|
||||
variantKey := "attachments/chat/ready/variants/v1/thumbnail.jpg"
|
||||
|
||||
store.objects[presign.ObjectKey] = storedObject{data: []byte("x"), lastModified: stale}
|
||||
store.objects[proxyRecoverable.ObjectKey] = storedObject{
|
||||
data: []byte("abc"),
|
||||
lastModified: stale,
|
||||
metadata: map[string]string{"sha256": proxyRecoverable.SHA256},
|
||||
for _, key := range []string{
|
||||
presign.StagingKey, staleStaging.StagingKey, activeStaging, readyKey, variantKey,
|
||||
"attachments/chat/orphan", "staging/orphan",
|
||||
} {
|
||||
store.objects[key] = storedObject{data: []byte("x"), lastModified: stale}
|
||||
}
|
||||
store.objects[readyKey] = storedObject{data: []byte("ready"), lastModified: stale}
|
||||
store.objects["attachments/chat/orphan"] = storedObject{data: []byte("orphan"), lastModified: stale}
|
||||
store.objects["staging/abandoned"] = storedObject{data: []byte("stale"), lastModified: stale}
|
||||
store.objects["staging/fresh"] = storedObject{data: []byte("fresh"), lastModified: time.Now().UTC()}
|
||||
store.objects["staging/fresh"] = storedObject{data: []byte("x"), lastModified: time.Now().UTC()}
|
||||
|
||||
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
|
||||
Return([]domain.Attachment{presign, proxyRecoverable, proxyMissing}, nil).Once()
|
||||
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).
|
||||
Return([]domain.Attachment{presign}, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, presign.ID).Return(nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, proxyRecoverable.ID, proxyRecoverable.ObjectKey).
|
||||
Return(domain.Attachment{ID: proxyRecoverable.ID, Status: domain.AttachmentReady}, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, proxyMissing.ID).Return(nil).Once()
|
||||
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
|
||||
Return([]domain.AttachmentKey{
|
||||
{ID: proxyRecoverable.ID, ObjectKey: proxyRecoverable.ObjectKey, Status: domain.AttachmentReady},
|
||||
{ID: uuid.New(), ObjectKey: readyKey, Status: domain.AttachmentReady},
|
||||
}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).
|
||||
Return(func() {}, true, nil).Once()
|
||||
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).
|
||||
Return([]domain.StaleStaging{staleStaging}, nil).Once()
|
||||
repo.EXPECT().MarkStagingDeleted(mock.Anything, staleStaging.AttachmentID, staleStaging.StagingKey).
|
||||
Return(nil).Once()
|
||||
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
|
||||
Return([]string{activeStaging, readyKey, variantKey}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, store, locker,
|
||||
10*time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
|
||||
)
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, stats.Recovered)
|
||||
require.Equal(t, 2, stats.RowsDeleted)
|
||||
require.Equal(t, 3, stats.ObjectsDeleted)
|
||||
require.Equal(t, 1, stats.RowsDeleted)
|
||||
require.Equal(t, 1, stats.StagingCleared)
|
||||
require.Equal(t, 4, stats.ObjectsDeleted)
|
||||
|
||||
require.NotContains(t, store.objects, presign.ObjectKey)
|
||||
require.NotContains(t, store.objects, presign.StagingKey)
|
||||
require.NotContains(t, store.objects, staleStaging.StagingKey)
|
||||
require.NotContains(t, store.objects, "attachments/chat/orphan")
|
||||
require.NotContains(t, store.objects, "staging/abandoned")
|
||||
require.Contains(t, store.objects, proxyRecoverable.ObjectKey)
|
||||
require.NotContains(t, store.objects, "staging/orphan")
|
||||
require.Contains(t, store.objects, activeStaging)
|
||||
require.Contains(t, store.objects, readyKey)
|
||||
require.Contains(t, store.objects, variantKey)
|
||||
require.Contains(t, store.objects, "staging/fresh")
|
||||
}
|
||||
|
||||
func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
repo := mocks.NewMockSweepRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
sweeper := attachment.NewSweeper(repo, newFakeStore(), locker, time.Minute, time.Hour, slog.Default())
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, newFakeStore(), locker,
|
||||
time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
|
||||
)
|
||||
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(nil, false, nil).Once()
|
||||
|
||||
@@ -90,37 +88,26 @@ func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
require.Zero(t, stats)
|
||||
}
|
||||
|
||||
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
func TestSweepAbortsObjectCollectionWhenKeysCannotBeRead(t *testing.T) {
|
||||
repo := mocks.NewMockSweepRepository(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,
|
||||
}
|
||||
orphan := "attachments/chat/orphan"
|
||||
store.objects[orphan] = storedObject{data: []byte("x"), lastModified: time.Now().UTC().Add(-2 * time.Hour)}
|
||||
|
||||
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()
|
||||
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
|
||||
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
|
||||
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
|
||||
Return(nil, context.DeadlineExceeded).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, store, locker,
|
||||
time.Minute, time.Hour, 24*time.Hour, time.Minute, 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)
|
||||
_, err := sweeper.SweepOnce(t.Context())
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
require.Contains(t, store.objects, orphan, "fail-closed: no deletion when the key set is unknown")
|
||||
}
|
||||
|
||||
@@ -269,3 +269,75 @@ func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Con
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Replay provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Replay")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 bool
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, bool, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) domain.Message); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Message)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.MessageDraft) bool); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Get(1).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, domain.MessageDraft) error); ok {
|
||||
r2 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockRepository_Replay_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Replay'
|
||||
type MockRepository_Replay_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Replay is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockRepository_Expecter) Replay(ctx any, draft any) *MockRepository_Replay_Call {
|
||||
return &MockRepository_Replay_Call{Call: _e.mock.On("Replay", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Replay_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Replay_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.MessageDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.MessageDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Replay_Call) Return(message domain.Message, b bool, err error) *MockRepository_Replay_Call {
|
||||
_c.Call.Return(message, b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Replay_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error)) *MockRepository_Replay_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
@@ -11,6 +11,11 @@ import (
|
||||
|
||||
type Repository interface {
|
||||
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
// Replay returns the stored message for a live Idempotency-Key. It must be
|
||||
// checked before attachment-state validation: a message that was accepted
|
||||
// while the attachment was queued keeps replaying as 201 even after the
|
||||
// attachment later fails.
|
||||
Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error)
|
||||
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
@@ -50,6 +55,15 @@ func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.M
|
||||
return domain.Message{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
replayed, found, err := s.messages.Replay(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("replay message: %w", err)
|
||||
}
|
||||
|
||||
if found {
|
||||
return replayed, nil
|
||||
}
|
||||
|
||||
if len(draft.AttachmentIDs) > 0 {
|
||||
if s.attachments == nil {
|
||||
return domain.Message{}, fmt.Errorf("attachment checker is not configured: %w", domain.ErrUnavailable)
|
||||
@@ -65,7 +79,10 @@ func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.M
|
||||
}
|
||||
|
||||
for _, state := range states {
|
||||
if state.Status != domain.AttachmentReady {
|
||||
switch state.Status {
|
||||
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentReady:
|
||||
// Accepted work is linkable by contract.
|
||||
default:
|
||||
return domain.Message{}, fmt.Errorf(
|
||||
"%w: attachment %s is %s",
|
||||
domain.ErrConflict, state.ID, state.Status,
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
@@ -38,6 +39,8 @@ func (s *ServiceSuite) SetupTest() {
|
||||
s.caller = uuid.New()
|
||||
s.chatID = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
s.messages.EXPECT().Replay(mock.Anything, mock.Anything).
|
||||
Return(domain.Message{}, false, nil).Maybe()
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.MessageDraft {
|
||||
@@ -167,6 +170,40 @@ func (s *ServiceSuite) TestSendAcceptsReadyAttachment() {
|
||||
s.Equal([]uuid.UUID{attachmentID}, got.AttachmentIDs)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendReplaysBeforeAttachmentValidation() {
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{uuid.New()}
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(), ChatID: draft.ChatID, SenderID: draft.SenderID,
|
||||
Text: draft.Text, AttachmentIDs: draft.AttachmentIDs, CreatedAt: s.now,
|
||||
}
|
||||
|
||||
// The stored key is authoritative even if the attachment has since failed;
|
||||
// ListStates must not be consulted on a replay.
|
||||
s.messages.ExpectedCalls = nil
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.messages.EXPECT().Replay(s.T().Context(), draft).Return(stored, true, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsFailedAttachment() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.attachments.EXPECT().
|
||||
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
|
||||
Return([]domain.AttachmentState{{ID: attachmentID, Status: domain.AttachmentFailed}}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendAllowsAttachmentOnlyMessage() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
|
||||
Reference in New Issue
Block a user