lab7: безопасность, mTLS, OpenBao и PKI lifecycle
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-11-10 14:39:57 +03:00
parent 20afc2c790
commit 1b6e96ccc0
570 changed files with 298308 additions and 137 deletions
@@ -0,0 +1,115 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
mock "github.com/stretchr/testify/mock"
)
// NewMockLockStore creates a new instance of MockLockStore. 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 NewMockLockStore(t interface {
mock.TestingT
Cleanup(func())
}) *MockLockStore {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockLockStore{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockLockStore is an autogenerated mock type for the LockStore type
type MockLockStore struct {
mock.Mock
}
type MockLockStore_Expecter struct {
mock *mock.Mock
}
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
return &MockLockStore_Expecter{mock: &_m.Mock}
}
// AcquireSweepLock provides a mock function for the type MockLockStore
func (_mock *MockLockStore) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
ret := _mock.Called(ctx)
if len(ret) == 0 {
panic("no return value specified for AcquireSweepLock")
}
var r0 func()
var r1 bool
var r2 error
if returnFunc, ok := ret.Get(0).(func(context.Context) (func(), bool, error)); ok {
return returnFunc(ctx)
}
if returnFunc, ok := ret.Get(0).(func(context.Context) func()); ok {
r0 = returnFunc(ctx)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(func())
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context) bool); ok {
r1 = returnFunc(ctx)
} else {
r1 = ret.Get(1).(bool)
}
if returnFunc, ok := ret.Get(2).(func(context.Context) error); ok {
r2 = returnFunc(ctx)
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// MockLockStore_AcquireSweepLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireSweepLock'
type MockLockStore_AcquireSweepLock_Call struct {
*mock.Call
}
// AcquireSweepLock is a helper method to define mock.On call
// - ctx context.Context
func (_e *MockLockStore_Expecter) AcquireSweepLock(ctx any) *MockLockStore_AcquireSweepLock_Call {
return &MockLockStore_AcquireSweepLock_Call{Call: _e.mock.On("AcquireSweepLock", ctx)}
}
func (_c *MockLockStore_AcquireSweepLock_Call) Run(run func(ctx context.Context)) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
run(
arg0,
)
})
return _c
}
func (_c *MockLockStore_AcquireSweepLock_Call) Return(release func(), acquired bool, err error) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Return(release, acquired, err)
return _c
}
func (_c *MockLockStore_AcquireSweepLock_Call) RunAndReturn(run func(ctx context.Context) (func(), bool, error)) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Return(run)
return _c
}
@@ -0,0 +1,804 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
)
// NewMockRepository creates a new instance of MockRepository. 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 NewMockRepository(t interface {
mock.TestingT
Cleanup(func())
}) *MockRepository {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockRepository{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockRepository is an autogenerated mock type for the Repository type
type MockRepository struct {
mock.Mock
}
type MockRepository_Expecter struct {
mock *mock.Mock
}
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
return &MockRepository_Expecter{mock: &_m.Mock}
}
// 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, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, limits)
if len(ret) == 0 {
panic("no return value specified for CreatePresign")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, limits)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// 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
}
// CreatePresign is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.AttachmentDraft
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any, limits any) *MockRepository_CreatePresign_Call {
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft, limits)}
}
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits)) *MockRepository_CreatePresign_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.AdmissionLimits
if args[2] != nil {
arg2 = args[2].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreatePresign_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
_c.Call.Return(run)
return _c
}
// CreateQueued provides a mock function for the type MockRepository
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft, job, limits)
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.AdmissionLimits) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft, job, limits)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) domain.Attachment); ok {
r0 = returnFunc(ctx, draft, job, limits)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) error); ok {
r1 = returnFunc(ctx, draft, job, limits)
} 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
// - limits domain.AdmissionLimits
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any, limits any) *MockRepository_CreateQueued_Call {
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job, limits)}
}
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits)) *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)
}
var arg3 domain.AdmissionLimits
if args[3] != nil {
arg3 = args[3].(domain.AdmissionLimits)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
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, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreateQueued_Call {
_c.Call.Return(run)
return _c
}
// DeletePending provides a mock function for the type MockRepository
func (_mock *MockRepository) 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
}
// MockRepository_DeletePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePending'
type MockRepository_DeletePending_Call struct {
*mock.Call
}
// DeletePending is a helper method to define mock.On call
// - ctx context.Context
// - id uuid.UUID
func (_e *MockRepository_Expecter) DeletePending(ctx any, id any) *MockRepository_DeletePending_Call {
return &MockRepository_DeletePending_Call{Call: _e.mock.On("DeletePending", ctx, id)}
}
func (_c *MockRepository_DeletePending_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockRepository_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 *MockRepository_DeletePending_Call) Return(err error) *MockRepository_DeletePending_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockRepository_DeletePending_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) error) *MockRepository_DeletePending_Call {
_c.Call.Return(run)
return _c
}
// GetForMember provides a mock function for the type MockRepository
func (_mock *MockRepository) GetForMember(ctx context.Context, userID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
ret := _mock.Called(ctx, userID, id)
if len(ret) == 0 {
panic("no return value specified for GetForMember")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
return returnFunc(ctx, userID, id)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
r0 = returnFunc(ctx, userID, id)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
r1 = returnFunc(ctx, userID, id)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_GetForMember_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForMember'
type MockRepository_GetForMember_Call struct {
*mock.Call
}
// GetForMember is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
// - id uuid.UUID
func (_e *MockRepository_Expecter) GetForMember(ctx any, userID any, id any) *MockRepository_GetForMember_Call {
return &MockRepository_GetForMember_Call{Call: _e.mock.On("GetForMember", ctx, userID, id)}
}
func (_c *MockRepository_GetForMember_Call) Run(run func(ctx context.Context, userID uuid.UUID, id uuid.UUID)) *MockRepository_GetForMember_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)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_GetForMember_Call) Return(attachment domain.Attachment, err error) *MockRepository_GetForMember_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_GetForMember_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockRepository_GetForMember_Call {
_c.Call.Return(run)
return _c
}
// GetForOwner provides a mock function for the type MockRepository
func (_mock *MockRepository) GetForOwner(ctx context.Context, ownerID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
ret := _mock.Called(ctx, ownerID, id)
if len(ret) == 0 {
panic("no return value specified for GetForOwner")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
return returnFunc(ctx, ownerID, id)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
r0 = returnFunc(ctx, ownerID, id)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
r1 = returnFunc(ctx, ownerID, id)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_GetForOwner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForOwner'
type MockRepository_GetForOwner_Call struct {
*mock.Call
}
// GetForOwner is a helper method to define mock.On call
// - ctx context.Context
// - ownerID uuid.UUID
// - id uuid.UUID
func (_e *MockRepository_Expecter) GetForOwner(ctx any, ownerID any, id any) *MockRepository_GetForOwner_Call {
return &MockRepository_GetForOwner_Call{Call: _e.mock.On("GetForOwner", ctx, ownerID, id)}
}
func (_c *MockRepository_GetForOwner_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID)) *MockRepository_GetForOwner_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)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_GetForOwner_Call) Return(attachment domain.Attachment, err error) *MockRepository_GetForOwner_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_GetForOwner_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockRepository_GetForOwner_Call {
_c.Call.Return(run)
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)
if len(ret) == 0 {
panic("no return value specified for IsChatMember")
}
var r0 bool
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (bool, error)); ok {
return returnFunc(ctx, chatID, userID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) bool); ok {
r0 = returnFunc(ctx, chatID, userID)
} else {
r0 = ret.Get(0).(bool)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
r1 = returnFunc(ctx, chatID, userID)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_IsChatMember_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsChatMember'
type MockRepository_IsChatMember_Call struct {
*mock.Call
}
// IsChatMember is a helper method to define mock.On call
// - ctx context.Context
// - chatID uuid.UUID
// - userID uuid.UUID
func (_e *MockRepository_Expecter) IsChatMember(ctx any, chatID any, userID any) *MockRepository_IsChatMember_Call {
return &MockRepository_IsChatMember_Call{Call: _e.mock.On("IsChatMember", ctx, chatID, userID)}
}
func (_c *MockRepository_IsChatMember_Call) Run(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID)) *MockRepository_IsChatMember_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)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_IsChatMember_Call) Return(b bool, err error) *MockRepository_IsChatMember_Call {
_c.Call.Return(b, err)
return _c
}
func (_c *MockRepository_IsChatMember_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error)) *MockRepository_IsChatMember_Call {
_c.Call.Return(run)
return _c
}
// 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 ListVariants")
}
var r0 []domain.Variant
var r1 error
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, uuid.UUID, int) []domain.Variant); ok {
r0 = returnFunc(ctx, attachmentID, pipelineVersion)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.Variant)
}
}
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_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
}
// ListVariants is a helper method to define mock.On call
// - ctx context.Context
// - 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_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 {
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)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_ListVariants_Call) Return(variants []domain.Variant, err error) *MockRepository_ListVariants_Call {
_c.Call.Return(variants, err)
return _c
}
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
}
+712
View File
@@ -0,0 +1,712 @@
package attachment
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"regexp"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"golang.org/x/sync/semaphore"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/imagecheck"
"mtusi-messenger/internal/platform/objectstore"
"mtusi-messenger/internal/telemetry"
)
const (
contentTypePNG = "image/png"
contentTypeJPEG = "image/jpeg"
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. 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)
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, 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,
limits domain.AdmissionLimits,
) (domain.Attachment, error)
CreatePresign(
ctx context.Context,
draft domain.AttachmentDraft,
limits domain.AdmissionLimits,
) (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 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
MaxConcurrent int
}
type Service struct {
repo Repository
store objectstore.Store
config Config
log *slog.Logger
upload *semaphore.Weighted
}
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
if log == nil {
log = slog.Default()
}
service := &Service{repo: repo, store: store, config: config, log: log}
if config.MaxConcurrent > 0 {
service.upload = semaphore.NewWeighted(int64(config.MaxConcurrent))
}
return service
}
// UploadInput is one raw-body upload. DeclaredContentType comes from the HTTP
// Content-Type header and is cross-checked against the detected format.
type UploadInput struct {
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
DeclaredContentType string
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 s.upload != nil {
if err := s.upload.Acquire(ctx, 1); err != nil {
return domain.Attachment{}, unavailable("acquire upload slot", err)
}
defer s.upload.Release(1)
}
if err := ValidateFilename(input.Filename); err != nil {
return domain.Attachment{}, err
}
member, err := s.repo.IsChatMember(ctx, input.ChatID, input.OwnerID)
if err != nil {
return domain.Attachment{}, err
}
if !member {
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
}
defer func() { _ = file.Close() }()
defer func() { _ = os.Remove(file.Name()) }()
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
}
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
if err != nil {
return domain.Attachment{}, mapImageError(err)
}
if info.ContentType != input.DeclaredContentType {
return domain.Attachment{}, fmt.Errorf(
"%w: declared %q, detected %q",
domain.ErrUnsupportedMedia, input.DeclaredContentType, info.ContentType,
)
}
id, err := uuid.NewV7()
if err != nil {
return domain.Attachment{}, fmt.Errorf("generate attachment id: %w", 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, stagingKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("store staging object", err)
}
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(),
}
limits := s.admissionLimits()
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, limits)
if err != nil {
if errors.Is(err, domain.ErrRateLimited) {
s.deleteObject(ctx, id, stagingKey)
return domain.Attachment{}, err
}
// An ambiguous COMMIT may have persisted the intent; leave the staging
// object for the sweeper instead of destroying a queued job's source.
return domain.Attachment{}, unavailable("commit attachment intent", err)
}
created.Variants = []domain.Variant{}
telemetry.RecordJobAccepted(ctx, created.PipelineVersion)
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
}
if !attachment.Status.Public() {
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
}
return s.withVariants(ctx, attachment)
}
// 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,
name domain.VariantName,
) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
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 attachment, nil
}
variants, err := s.repo.ListVariants(ctx, attachment.ID, attachment.PipelineVersion)
if err != nil {
return domain.Attachment{}, err
}
if variants != nil {
attachment.Variants = variants
}
return attachment, nil
}
func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
if err := ValidateFilename(request.Filename); err != nil {
return domain.PresignResult{}, err
}
if request.ContentType != contentTypePNG && request.ContentType != contentTypeJPEG {
return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType)
}
if request.SizeBytes < 1 {
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes)
}
if request.SizeBytes > s.config.MaxUploadBytes {
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes)
}
if !sha256Pattern.MatchString(request.SHA256) {
return domain.PresignResult{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
}
member, err := s.repo.IsChatMember(ctx, request.ChatID, request.OwnerID)
if err != nil {
return domain.PresignResult{}, err
}
if !member {
return domain.PresignResult{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
}
id, err := uuid.NewV7()
if err != nil {
return domain.PresignResult{}, fmt.Errorf("generate attachment id: %w", err)
}
stagingKey := objectPrefixPresign + request.ChatID.String() + "/" + id.String()
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,
}, s.admissionLimits()); err != nil {
return domain.PresignResult{}, err
}
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL)
if err != nil {
s.cleanupPending(ctx, id, "")
return domain.PresignResult{}, unavailable("presign attachment", err)
}
return domain.PresignResult{
AttachmentID: id,
UploadURL: url,
ExpiresAt: expiresAt,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
}, 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,
requestSHA string,
) (domain.Attachment, error) {
if !sha256Pattern.MatchString(requestSHA) {
return domain.Attachment{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
}
attachment, err := s.repo.GetForOwner(ctx, ownerID, id)
if err != nil {
return domain.Attachment{}, err
}
switch attachment.Status {
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 s.withVariants(ctx, attachment)
case domain.AttachmentFailed:
return domain.Attachment{}, fmt.Errorf("%w: attachment is failed", domain.ErrConflict)
case domain.AttachmentPending:
default:
return domain.Attachment{}, fmt.Errorf("%w: unknown attachment status", domain.ErrConflict)
}
if !strings.HasPrefix(attachment.ObjectKey, objectPrefixPresign) {
return domain.Attachment{}, fmt.Errorf("%w: attachment is not a presigned upload", domain.ErrConflict)
}
head, err := s.store.Head(ctx, attachment.ObjectKey)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return domain.Attachment{}, fmt.Errorf("%w: object was not uploaded", domain.ErrIncomplete)
}
return domain.Attachment{}, err
}
if head.Size != attachment.SizeBytes {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf(
"%w: uploaded %d bytes, declared %d",
domain.ErrValidation, head.Size, attachment.SizeBytes,
)
}
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
if err != nil {
return domain.Attachment{}, err
}
file, size, sum, err := s.spool(body)
_ = body.Close()
if err != nil {
return domain.Attachment{}, err
}
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 {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf(
"%w: declared %q, detected %q",
domain.ErrUnsupportedMedia, attachment.ContentType, info.ContentType,
)
}
if sum != attachment.SHA256 {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf("%w: uploaded object checksum mismatch", domain.ErrValidation)
}
if requestSHA != attachment.SHA256 {
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
}
verifiedKey := domain.StagingVerifiedKey(attachment.ChatID, attachment.ID)
finalKey := domain.OriginalObjectKey(attachment.ChatID, attachment.ID)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind verified object: %w", err)
}
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 {
s.deleteObject(ctx, id, verifiedKey)
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
}
queued, err := s.repo.CompletePresign(
ctx, ownerID, id, verifiedKey, finalKey,
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
)
if err != nil {
// The verified key is shared by concurrent completions of this
// attachment. Never delete it here: a winning request may already have
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
if errors.Is(err, domain.ErrConflict) {
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
return s.withVariants(ctx, current)
}
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
}
return domain.Attachment{}, unavailable("commit presigned attachment", err)
}
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),
)
}
queued.Variants = []domain.Variant{}
telemetry.RecordJobAccepted(ctx, queued.PipelineVersion)
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) admissionLimits() domain.AdmissionLimits {
return domain.AdmissionLimits{
PerUser: s.config.MaxPendingPerUser,
Total: s.config.MaxPending,
Bytes: s.config.MaxStagedBytes,
}
}
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
head, err := s.store.Head(ctx, key)
if err != nil {
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("", "lab5-upload-*")
if err != nil {
return nil, 0, "", fmt.Errorf("create upload spool: %w", err)
}
cleanup := func() {
_ = file.Close()
_ = os.Remove(file.Name())
}
hasher := sha256.New()
limited := io.LimitReader(body, s.config.MaxUploadBytes+1)
buffer := make([]byte, 32<<10)
size, err := io.CopyBuffer(io.MultiWriter(file, hasher), limited, buffer)
if err != nil {
cleanup()
var maxBytes *http.MaxBytesError
if errors.As(err, &maxBytes) {
return nil, 0, "", fmt.Errorf("%w: request body exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
}
return nil, 0, "", fmt.Errorf("%w: read upload: %w", domain.ErrValidation, err)
}
if size > s.config.MaxUploadBytes {
cleanup()
return nil, 0, "", fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
}
if size == 0 {
cleanup()
return nil, 0, "", fmt.Errorf("%w: empty image", domain.ErrUnsupportedMedia)
}
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
}
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()),
slog.Any("error", err),
)
}
}
// ValidateFilename implements the contract rule: 1-255 Unicode code points,
// no path separators, NUL or control characters. The name is display-only; the
// S3 key is always generated.
func ValidateFilename(name string) error {
if !utf8.ValidString(name) {
return fmt.Errorf("%w: filename is not valid UTF-8", domain.ErrValidation)
}
length := utf8.RuneCountInString(name)
if length < 1 || length > 255 {
return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length)
}
if strings.TrimSpace(name) == "" {
return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation)
}
if strings.ContainsAny(name, "/\\\x00") {
return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation)
}
for _, r := range name {
if unicode.IsControl(r) {
return fmt.Errorf("%w: filename contains a control character", domain.ErrValidation)
}
}
return nil
}
func mapImageError(err error) error {
switch {
case errors.Is(err, imagecheck.ErrTooLarge):
return fmt.Errorf("%w: %w", domain.ErrTooLarge, err)
case errors.Is(err, imagecheck.ErrUnsupported), errors.Is(err, imagecheck.ErrCorrupt):
return fmt.Errorf("%w: %w", domain.ErrUnsupportedMedia, err)
default:
return err
}
}
func unavailable(operation string, err error) error {
if errors.Is(err, domain.ErrUnavailable) || errors.Is(err, domain.ErrNotFound) {
return err
}
return fmt.Errorf("%w: %s: %w", domain.ErrUnavailable, operation, err)
}
+509
View File
@@ -0,0 +1,509 @@
package attachment_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"image"
"image/color"
"image/png"
"io"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/objectstore"
"mtusi-messenger/internal/service/attachment"
"mtusi-messenger/internal/service/attachment/mocks"
)
type storedObject struct {
data []byte
contentType string
metadata map[string]string
lastModified time.Time
}
type fakeStore struct {
objects map[string]storedObject
}
func newFakeStore() *fakeStore {
return &fakeStore{objects: make(map[string]storedObject)}
}
func (f *fakeStore) Put(
_ context.Context,
key string,
body io.ReadSeeker,
_ int64,
contentType string,
metadata map[string]string,
) error {
data, err := io.ReadAll(body)
if err != nil {
return err
}
f.objects[key] = storedObject{
data: data,
contentType: contentType,
metadata: metadata,
lastModified: time.Now().UTC(),
}
return nil
}
func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
object, ok := f.objects[key]
if !ok {
return nil, objectstore.Object{}, domain.ErrNotFound
}
return io.NopCloser(bytes.NewReader(object.data)), f.object(key, object), nil
}
func (f *fakeStore) Ping(context.Context) error { return nil }
func (f *fakeStore) Head(_ context.Context, key string) (objectstore.Object, error) {
object, ok := f.objects[key]
if !ok {
return objectstore.Object{}, domain.ErrNotFound
}
return f.object(key, object), nil
}
func (f *fakeStore) Copy(_ context.Context, src, dst, contentType string, metadata map[string]string) error {
object, ok := f.objects[src]
if !ok {
return domain.ErrNotFound
}
f.objects[dst] = storedObject{
data: append([]byte(nil), object.data...),
contentType: contentType,
metadata: metadata,
lastModified: time.Now().UTC(),
}
return nil
}
func (f *fakeStore) Delete(_ context.Context, key string) error {
delete(f.objects, key)
return nil
}
func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object, error) {
objects := make([]objectstore.Object, 0, len(f.objects))
for key, object := range f.objects {
if strings.HasPrefix(key, prefix) {
objects = append(objects, f.object(key, object))
}
}
return objects, nil
}
func (f *fakeStore) PresignPut(_ context.Context, key string, _ int64, ttl time.Duration) (string, time.Time, error) {
return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil
}
func (f *fakeStore) object(key string, object storedObject) objectstore.Object {
return objectstore.Object{
Key: key,
Size: int64(len(object.data)),
ContentType: object.contentType,
LastModified: object.lastModified,
Metadata: object.metadata,
}
}
func pngBytes(t *testing.T, width, height int) []byte {
t.Helper()
source := image.NewRGBA(image.Rect(0, 0, width, height))
for x := range width {
for y := range height {
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 200, A: 255})
}
}
var buffer bytes.Buffer
require.NoError(t, png.Encode(&buffer, source))
return buffer.Bytes()
}
func serviceConfig() attachment.Config {
return attachment.Config{
MaxUploadBytes: 1 << 20,
MaxImagePixels: 1_000_000,
PresignTTL: 5 * time.Minute,
PipelineVersion: 1,
MaxAttempts: 5,
}
}
func TestValidateFilename(t *testing.T) {
valid := []string{"photo.png", "фото.png", "a b.jpeg", strings.Repeat("я", 255)}
for _, name := range valid {
require.NoError(t, attachment.ValidateFilename(name), name)
}
invalid := []string{"", " ", "\t\n", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"}
for _, name := range invalid {
require.ErrorIs(t, attachment.ValidateFilename(name), domain.ErrValidation, name)
}
}
func TestUploadStagesAndQueues(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 16, 16)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, ownerID).Return(0, 0, int64(0), nil).Once()
repo.EXPECT().CreateQueued(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
draft.SHA256 == digest && draft.Status == domain.AttachmentQueued &&
draft.PipelineVersion == 1 &&
strings.HasPrefix(draft.ObjectKey, "attachments/") &&
strings.HasPrefix(draft.StagingKey, "staging/uploads/")
}), mock.MatchedBy(func(job domain.Job) bool {
return job.PipelineVersion == 1 && job.Attempt == 1 &&
job.MaxAttempts == 5 && job.SourceKey != ""
}), domain.AdmissionLimits{}).Return(domain.Attachment{
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}, nil).Once()
result, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: chatID,
OwnerID: ownerID,
Filename: "photo.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(content),
})
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, result.Status)
require.Len(t, store.objects, 1)
for key := range store.objects {
require.Contains(t, key, "staging/uploads/")
}
}
func TestUploadRejectsTooLargeBody(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
MaxUploadBytes: 8, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
PipelineVersion: 1, MaxAttempts: 5,
}, slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(bytes.Repeat([]byte("x"), 9)),
})
require.ErrorIs(t, err, domain.ErrTooLarge)
}
func TestUploadRejectsMIMEMismatch(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.jpg",
DeclaredContentType: "image/jpeg",
Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrUnsupportedMedia)
}
func TestUploadAdmissionRejectsFlood(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
MaxUploadBytes: 1 << 20, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
PipelineVersion: 1, MaxAttempts: 5, MaxPendingPerUser: 1,
}, slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(1, 1, int64(0), nil).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestGetReturnsQueuedSnapshotWithoutVariants(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentQueued, PipelineVersion: 1}, nil).Once()
got, err := service.Get(t.Context(), uuid.New(), uuid.New())
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
require.Empty(t, got.Variants)
}
func TestGetReadyLoadsCurrentVariants(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
attachmentID := uuid.New()
variant := domain.Variant{Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 10, Width: 256, Height: 160, SHA256: strings.Repeat("a", 64)}
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, attachmentID).
Return(domain.Attachment{ID: attachmentID, Status: domain.AttachmentReady, PipelineVersion: 2}, nil).Once()
repo.EXPECT().ListVariants(mock.Anything, attachmentID, 2).Return([]domain.Variant{variant}, nil).Once()
got, err := service.Get(t.Context(), uuid.New(), attachmentID)
require.NoError(t, err)
require.Equal(t, []domain.Variant{variant}, got.Variants)
}
func TestGetRejectsInternalPending(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
_, err := service.Get(t.Context(), uuid.New(), uuid.New())
require.ErrorIs(t, err, domain.ErrConflict)
}
func TestOpenVariantRejectsQueued(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentQueued}, nil).Once()
_, _, _, err := service.OpenVariant(t.Context(), uuid.New(), uuid.New(), domain.VariantOriginal)
require.ErrorIs(t, err, domain.ErrConflict)
}
func TestCompleteQueuesPresignedObject(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content, contentType: "image/png",
metadata: map[string]string{"sha256": digest}, lastModified: time.Now().UTC(),
}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id,
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "staging/verified/") }),
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "attachments/") }),
1, 5, mock.Anything,
).Return(domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}, nil).Once()
completed, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, completed.Status)
require.NotContains(t, store.objects, stagingKey)
require.Len(t, store.objects, 1)
}
func TestCompleteConcurrentConflictKeepsVerifiedSource(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{
data: content, contentType: "image/png",
metadata: map[string]string{"sha256": digest},
}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
queued := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: "attachments/" + chatID.String() + "/" + id.String(),
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentQueued, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().CompletePresign(
mock.Anything, ownerID, id, mock.Anything, mock.Anything,
1, 5, mock.Anything,
).Return(domain.Attachment{}, domain.ErrConflict).Once()
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(queued, nil).Once()
got, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentQueued, got.Status)
verified := 0
for key := range store.objects {
if strings.HasPrefix(key, "staging/verified/") {
verified++
}
}
require.Equal(t, 1, verified, "loser must not delete the winner's verified source")
}
func TestPresignHonoursAdmissionLimit(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().CreatePresign(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Presign(t.Context(), domain.PresignRequest{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("a", 64),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
}
func TestUploadRateLimitedByAtomicAdmissionRemovesStaging(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
repo.EXPECT().CreateQueued(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
_, err := service.Upload(t.Context(), attachment.UploadInput{
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
})
require.ErrorIs(t, err, domain.ErrRateLimited)
require.Empty(t, store.objects, "a rejected atomic admission must not leave staging")
}
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)) + 1, SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().DeletePending(mock.Anything, id).Return(nil).Once()
_, err := service.Complete(t.Context(), ownerID, id, digest)
require.ErrorIs(t, err, domain.ErrValidation)
require.NotContains(t, store.objects, stagingKey)
}
func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) {
repo := mocks.NewMockRepository(t)
store := newFakeStore()
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
id := uuid.New()
chatID := uuid.New()
ownerID := uuid.New()
content := pngBytes(t, 10, 10)
sum := sha256.Sum256(content)
digest := hex.EncodeToString(sum[:])
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
store.objects[stagingKey] = storedObject{data: content, contentType: "image/png", metadata: map[string]string{"sha256": digest}}
pending := domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
StagingKey: stagingKey, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending, PipelineVersion: 1,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
_, err := service.Complete(t.Context(), ownerID, id, strings.Repeat("0", 64))
require.ErrorIs(t, err, domain.ErrConflict)
require.Contains(t, store.objects, stagingKey)
}
func TestPresignRejectsNonPositiveSize(t *testing.T) {
repo := mocks.NewMockRepository(t)
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
_, err := service.Presign(t.Context(), domain.PresignRequest{
ChatID: uuid.New(), OwnerID: uuid.New(),
Filename: "photo.png", ContentType: "image/png",
SizeBytes: 0, SHA256: strings.Repeat("a", 64),
})
require.ErrorIs(t, err, domain.ErrValidation)
}
+236
View File
@@ -0,0 +1,236 @@
package attachment
import (
"context"
"errors"
"log/slog"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/objectstore"
)
// LockStore serialises sweepers across API replicas.
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 {
RowsDeleted int
ObjectsDeleted int
StagingCleared int
}
type Sweeper struct {
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 SweepRepository,
store objectstore.Store,
locker LockStore,
grace, orphanGrace, failedRetain, interval time.Duration,
log *slog.Logger,
) *Sweeper {
if log == nil {
log = slog.Default()
}
return &Sweeper{
repo: repo,
store: store,
locker: locker,
grace: grace,
orphanGrace: orphanGrace,
failedRetain: failedRetain,
interval: interval,
log: log,
}
}
// Run sweeps immediately, then on every interval until the context is done.
func (s *Sweeper) Run(ctx context.Context) {
s.sweep(ctx)
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.sweep(ctx)
}
}
}
func (s *Sweeper) sweep(ctx context.Context) {
stats, err := s.SweepOnce(ctx)
if err != nil {
s.log.WarnContext(ctx, "attachment sweep failed", slog.Any("error", err))
return
}
if stats.RowsDeleted+stats.ObjectsDeleted+stats.StagingCleared > 0 {
s.log.InfoContext(ctx, "attachment sweep finished",
slog.Int("rows_deleted", stats.RowsDeleted),
slog.Int("objects_deleted", stats.ObjectsDeleted),
slog.Int("staging_cleared", stats.StagingCleared),
)
}
}
// 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 {
return SweepStats{}, err
}
if !acquired {
return SweepStats{}, nil
}
defer release()
now := time.Now().UTC()
var stats SweepStats
// 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 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++
}
// 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
}
// 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
}
for _, object := range objects {
if object.LastModified.IsZero() || !object.LastModified.Before(before) {
continue
}
if _, ok := referenced[object.Key]; ok {
continue
}
if s.deleteObject(ctx, object.Key) {
stats.ObjectsDeleted++
}
}
}
return stats, nil
}
func (s *Sweeper) referencedKeys(ctx context.Context) (map[string]struct{}, error) {
const pageSize = 1000
keys := make(map[string]struct{})
after := ""
for {
rows, err := s.repo.ListReferencedKeys(ctx, after, pageSize)
if err != nil {
return nil, err
}
for _, key := range rows {
keys[key] = struct{}{}
}
if len(rows) < pageSize {
return keys, nil
}
after = rows[len(rows)-1]
}
}
func (s *Sweeper) deleteObject(ctx context.Context, key string) bool {
err := s.store.Delete(ctx, key)
if err == nil {
return true
}
if !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "sweep delete failed",
slog.Any("error", err),
)
}
return false
}
+113
View File
@@ -0,0 +1,113 @@
package attachment_test
import (
"context"
"log/slog"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/service/attachment"
"mtusi-messenger/internal/service/attachment/mocks"
)
func TestSweepAppliesStatusAwareRetention(t *testing.T) {
repo := mocks.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
stale := time.Now().UTC().Add(-2 * time.Hour)
presign := domain.Attachment{
ID: uuid.New(), StagingKey: "staging/presign/chat/" + uuid.NewString(),
Status: domain.AttachmentPending,
}
staleStaging := domain.StaleStaging{
AttachmentID: uuid.New(), StagingKey: "staging/uploads/chat/ready", Status: domain.AttachmentReady,
}
activeStaging := "staging/uploads/chat/active"
readyKey := "attachments/chat/ready/original"
variantKey := "attachments/chat/ready/variants/v1/thumbnail.jpg"
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["staging/fresh"] = storedObject{data: []byte("x"), lastModified: time.Now().UTC()}
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().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,
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.RowsDeleted)
require.Equal(t, 1, stats.StagingCleared)
require.Equal(t, 4, stats.ObjectsDeleted)
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/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.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
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()
stats, err := sweeper.SweepOnce(t.Context())
require.NoError(t, err)
require.Zero(t, stats)
}
func TestSweepAbortsObjectCollectionWhenKeysCannotBeRead(t *testing.T) {
repo := mocks.NewMockSweepRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
orphan := "attachments/chat/orphan"
store.objects[orphan] = storedObject{data: []byte("x"), lastModified: time.Now().UTC().Add(-2 * time.Hour)}
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, 24*time.Hour, time.Minute, slog.Default(),
)
_, 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")
}