lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// 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}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
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 {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(chat domain.Chat, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
|
||||
type MockRepository_GetVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockRepository_GetVisible_Call {
|
||||
return &MockRepository_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockRepository_GetVisible_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_GetVisible_Call) Return(chat domain.Chat, err error) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_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 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
chats Repository
|
||||
}
|
||||
|
||||
func NewService(chats Repository) *Service {
|
||||
return &Service{chats: chats}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
created, err := s.chats.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("create chat: %w", err)
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, callerID, chatID uuid.UUID) (domain.Chat, error) {
|
||||
found, err := s.chats.GetVisible(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil && !after.BelongsTo(callerID) {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("cursor is bound to another list: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.chats.ListVisible(ctx, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/chat/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
chats *mocks.MockRepository
|
||||
service *chat.Service
|
||||
caller uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.chats = mocks.NewMockRepository(s.T())
|
||||
s.service = chat.NewService(s.chats)
|
||||
s.caller = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.ChatDraft {
|
||||
return domain.ChatDraft{
|
||||
Title: "Проект по ВНП",
|
||||
MemberIDs: []uuid.UUID{s.caller},
|
||||
CallerID: s.caller,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateReturnsStoredChat() {
|
||||
draft := s.draft()
|
||||
stored := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: draft.MemberIDs,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsDraftWithoutCallerWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.MemberIDs = []uuid.UUID{uuid.New()}
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsBlankTitleWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Title = " "
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesUnknownMember() {
|
||||
draft := s.draft()
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(domain.Chat{}, domain.ErrUnknownMember).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember,
|
||||
"целостность участников проверяет хранилище, сервис только пробрасывает исход")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetPropagatesNotFoundForForeignChat() {
|
||||
chatID := uuid.New()
|
||||
|
||||
s.chats.EXPECT().GetVisible(s.T().Context(), chatID, s.caller).Return(domain.Chat{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.Get(s.T().Context(), s.caller, chatID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Chat{ID: uuid.New(), Title: "Проект", MemberIDs: []uuid.UUID{s.caller}, CreatedAt: s.now}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{Items: []domain.Chat{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Chat{stored}, page.Items)
|
||||
s.Nil(page.Next, "на последней странице курсора нет")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListRejectsCursorFromAnotherCaller() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"курсор чужого списка не должен открывать чужие чаты")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListAcceptsOwnCursor() {
|
||||
own := &domain.Cursor{Scope: s.caller, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, own, 10).
|
||||
Return(domain.Page[domain.Chat]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, own, 10)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListWrapsRepositoryFailure() {
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
// NewMockAttachmentChecker creates a new instance of MockAttachmentChecker. 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 NewMockAttachmentChecker(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockAttachmentChecker {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockAttachmentChecker{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockAttachmentChecker is an autogenerated mock type for the AttachmentChecker type
|
||||
type MockAttachmentChecker struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockAttachmentChecker_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockAttachmentChecker) EXPECT() *MockAttachmentChecker_Expecter {
|
||||
return &MockAttachmentChecker_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// ListStates provides a mock function for the type MockAttachmentChecker
|
||||
func (_mock *MockAttachmentChecker) 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
|
||||
}
|
||||
|
||||
// MockAttachmentChecker_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
|
||||
type MockAttachmentChecker_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 *MockAttachmentChecker_Expecter) ListStates(ctx any, chatID any, ids any) *MockAttachmentChecker_ListStates_Call {
|
||||
return &MockAttachmentChecker_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentChecker_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockAttachmentChecker_ListStates_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 *MockAttachmentChecker_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockAttachmentChecker_ListStates_Call {
|
||||
_c.Call.Return(attachmentStates, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentChecker_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockAttachmentChecker_ListStates_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// 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}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, 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) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
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 {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Create_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_Create_Call) Return(message domain.Message, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(message, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)) *MockRepository_Create_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
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Message]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Message], error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Message]); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Message])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, chatID any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, chatID, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_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 *domain.Cursor
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(*domain.Cursor)
|
||||
}
|
||||
var arg4 int
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Message], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error)) *MockRepository_ListVisible_Call {
|
||||
_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
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
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,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// AttachmentChecker validates that requested attachments exist in the chat and
|
||||
// are ready. The contract returns 404 for unknown/foreign IDs and 409 for
|
||||
// attachments that cannot be linked.
|
||||
type AttachmentChecker interface {
|
||||
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
messages Repository
|
||||
attachments AttachmentChecker
|
||||
}
|
||||
|
||||
func NewService(messages Repository, attachments AttachmentChecker) *Service {
|
||||
return &Service{messages: messages, attachments: attachments}
|
||||
}
|
||||
|
||||
func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
member, err := s.messages.IsChatMember(ctx, draft.ChatID, draft.SenderID)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
|
||||
}
|
||||
|
||||
if !member {
|
||||
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)
|
||||
}
|
||||
|
||||
states, err := s.attachments.ListStates(ctx, draft.ChatID, draft.AttachmentIDs)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check attachments: %w", err)
|
||||
}
|
||||
|
||||
if len(states) != len(draft.AttachmentIDs) {
|
||||
return domain.Message{}, fmt.Errorf("%w: attachment is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
for _, state := range states {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sent, err := s.messages.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (s *Service) History(
|
||||
ctx context.Context,
|
||||
callerID, chatID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
if after != nil && !after.BelongsTo(chatID) {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("cursor is bound to another chat: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.messages.ListVisible(ctx, chatID, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package message_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/message/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
messages *mocks.MockRepository
|
||||
attachments *mocks.MockAttachmentChecker
|
||||
service *message.Service
|
||||
caller uuid.UUID
|
||||
chatID uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.messages = mocks.NewMockRepository(s.T())
|
||||
s.attachments = mocks.NewMockAttachmentChecker(s.T())
|
||||
s.service = message.NewService(s.messages, s.attachments)
|
||||
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 {
|
||||
return domain.MessageDraft{
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "Привет, Боб!",
|
||||
Idempotency: domain.MessageIdempotency{Key: "service-suite-key"},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendReturnsStoredMessage() {
|
||||
draft := s.draft()
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsWhitespaceTextWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Text = " \t\n "
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation,
|
||||
"пробельный текст не проходит схему контракта, но проходит minLength")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendPropagatesNotFoundForOutsider() {
|
||||
draft := s.draft()
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(false, nil).Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound,
|
||||
"посторонний не должен узнать о существовании чата")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "первое",
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{Items: []domain.Message{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Message{stored}, page.Items)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryRejectsCursorFromAnotherChat() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"контракт требует 400 на курсор от другого чата")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryAcceptsCursorOfSameChat() {
|
||||
own := &domain.Cursor{Scope: s.chatID, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, own, 7).
|
||||
Return(domain.Page[domain.Message]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, own, 7)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPropagatesNotFoundForOutsider() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, domain.ErrNotFound).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryWrapsRepositoryFailure() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendAcceptsReadyAttachment() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(), ChatID: draft.ChatID, SenderID: draft.SenderID,
|
||||
AttachmentIDs: []uuid.UUID{attachmentID}, CreatedAt: s.now,
|
||||
}
|
||||
|
||||
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.AttachmentReady}}, nil).
|
||||
Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
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()
|
||||
draft.Text = ""
|
||||
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.AttachmentReady}}, nil).
|
||||
Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(domain.Message{AttachmentIDs: draft.AttachmentIDs}, nil).Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsForeignAttachment() {
|
||||
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{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsPendingAttachment() {
|
||||
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.AttachmentPending}}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsDuplicateAttachments() {
|
||||
id := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{id, id}
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
// 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}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, session)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
|
||||
r1 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
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 {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - session domain.NewSession
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, session any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, session)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewSession
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewSession)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(session1 domain.Session, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(session1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Credentials provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ret := _mock.Called(ctx, username)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Credentials")
|
||||
}
|
||||
|
||||
var r0 domain.UserCredentials
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
|
||||
return returnFunc(ctx, username)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
|
||||
r0 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.UserCredentials)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
|
||||
type MockRepository_Credentials_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Credentials is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
func (_e *MockRepository_Expecter) Credentials(ctx any, username any) *MockRepository_Credentials_Call {
|
||||
return &MockRepository_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockRepository_Credentials_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)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(userCredentials, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, tokenHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
|
||||
r1 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockRepository_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Resolve(ctx any, tokenHash any) *MockRepository_Resolve_Call {
|
||||
return &MockRepository_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []byte
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Return(session domain.Session, err error) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ret := _mock.Called(ctx, userID, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
|
||||
r0 = returnFunc(ctx, userID, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockRepository_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockRepository_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockRepository_Revoke_Call {
|
||||
return &MockRepository_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockRepository_Revoke_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 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Return(err error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// UpdatePasswordHash provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) UpdatePasswordHash(ctx context.Context, userID uuid.UUID, oldHash string, newHash string) (bool, error) {
|
||||
ret := _mock.Called(ctx, userID, oldHash, newHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for UpdatePasswordHash")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, userID, oldHash, newHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string, string) bool); ok {
|
||||
r0 = returnFunc(ctx, userID, oldHash, newHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, userID, oldHash, newHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_UpdatePasswordHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePasswordHash'
|
||||
type MockRepository_UpdatePasswordHash_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// UpdatePasswordHash is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - oldHash string
|
||||
// - newHash string
|
||||
func (_e *MockRepository_Expecter) UpdatePasswordHash(ctx any, userID any, oldHash any, newHash any) *MockRepository_UpdatePasswordHash_Call {
|
||||
return &MockRepository_UpdatePasswordHash_Call{Call: _e.mock.On("UpdatePasswordHash", ctx, userID, oldHash, newHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) Run(run func(ctx context.Context, userID uuid.UUID, oldHash string, newHash string)) *MockRepository_UpdatePasswordHash_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)
|
||||
}
|
||||
var arg3 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) Return(b bool, err error) *MockRepository_UpdatePasswordHash_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, oldHash string, newHash string) (bool, error)) *MockRepository_UpdatePasswordHash_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockTokens creates a new instance of MockTokens. 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 NewMockTokens(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockTokens {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockTokens{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockTokens is an autogenerated mock type for the Tokens type
|
||||
type MockTokens struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockTokens_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockTokens) EXPECT() *MockTokens_Expecter {
|
||||
return &MockTokens_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Generate provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Generate() (string, []byte, error) {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Generate")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
var r1 []byte
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func() (string, []byte, error)); ok {
|
||||
return returnFunc()
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func() string); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func() []byte); ok {
|
||||
r1 = returnFunc()
|
||||
} else {
|
||||
if ret.Get(1) != nil {
|
||||
r1 = ret.Get(1).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func() error); ok {
|
||||
r2 = returnFunc()
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockTokens_Generate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Generate'
|
||||
type MockTokens_Generate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Generate is a helper method to define mock.On call
|
||||
func (_e *MockTokens_Expecter) Generate() *MockTokens_Generate_Call {
|
||||
return &MockTokens_Generate_Call{Call: _e.mock.On("Generate")}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Run(run func()) *MockTokens_Generate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Return(s string, bytes []byte, err error) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(s, bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) RunAndReturn(run func() (string, []byte, error)) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Hash provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Hash(raw string) ([]byte, error) {
|
||||
ret := _mock.Called(raw)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Hash")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(string) ([]byte, error)); ok {
|
||||
return returnFunc(raw)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(string) []byte); ok {
|
||||
r0 = returnFunc(raw)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = returnFunc(raw)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockTokens_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash'
|
||||
type MockTokens_Hash_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Hash is a helper method to define mock.On call
|
||||
// - raw string
|
||||
func (_e *MockTokens_Expecter) Hash(raw any) *MockTokens_Hash_Call {
|
||||
return &MockTokens_Hash_Call{Call: _e.mock.On("Hash", raw)}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Run(run func(raw string)) *MockTokens_Hash_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 string
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Return(bytes []byte, err error) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) RunAndReturn(run func(raw string) ([]byte, error)) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
|
||||
UpdatePasswordHash(ctx context.Context, userID uuid.UUID, oldHash, newHash string) (bool, error)
|
||||
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
|
||||
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type Tokens interface {
|
||||
Generate() (string, []byte, error)
|
||||
Hash(raw string) ([]byte, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
sessions Repository
|
||||
tokens Tokens
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service {
|
||||
return &Service{sessions: sessions, tokens: tokens, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
|
||||
credentials, err := s.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthenticated) {
|
||||
// Spend the same derivation budget as a real credential check so
|
||||
// an unknown username does not answer measurably faster.
|
||||
if dummyErr := password.DummyVerify(plain); dummyErr != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", dummyErr)
|
||||
}
|
||||
}
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
|
||||
verified, err := password.Verify(plain, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
if !verified.Match {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
if verified.NeedsRehash {
|
||||
// Optional upgrade: a busy derivation or transient write error must not
|
||||
// turn an already verified login into a failure.
|
||||
s.rehash(ctx, credentials.User.ID, credentials.PasswordHash, plain)
|
||||
}
|
||||
|
||||
return credentials.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) rehash(ctx context.Context, userID uuid.UUID, oldHash, plain string) {
|
||||
hash, err := password.Hash(plain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// A concurrent upgrade wins the CAS; both outcomes are acceptable.
|
||||
_, _ = s.sessions.UpdatePasswordHash(ctx, userID, oldHash, hash)
|
||||
}
|
||||
|
||||
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Resolve(ctx, hash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", err)
|
||||
}
|
||||
|
||||
return session.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, user domain.User) (domain.Session, error) {
|
||||
raw, hash, err := s.tokens.Generate()
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Create(ctx, domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: user.ID,
|
||||
ExpiresAt: time.Now().UTC().Add(s.ttl),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
|
||||
session.Token = raw
|
||||
session.User = user
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *Service) Revoke(ctx context.Context, userID uuid.UUID, raw string) error {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
if err := s.sessions.Revoke(ctx, userID, hash); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
"mtusi-messenger/internal/service/session/mocks"
|
||||
)
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sessions *mocks.MockRepository
|
||||
tokens *mocks.MockTokens
|
||||
service *session.Service
|
||||
ttl time.Duration
|
||||
user domain.User
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.sessions = mocks.NewMockRepository(s.T())
|
||||
s.tokens = mocks.NewMockTokens(s.T())
|
||||
s.ttl = time.Hour
|
||||
s.service = session.NewService(s.sessions, s.tokens, s.ttl)
|
||||
s.user = domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
stored := domain.Session{ExpiresAt: time.Now().Add(time.Hour), User: s.user}
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Resolve(mock.Anything, hash).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Resolve(s.T().Context(), "raw-token")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveRejectsMalformedTokenWithoutStorage() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
_, err := s.service.Resolve(s.T().Context(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateGeneratesTokenAndReturnsIt() {
|
||||
hash := []byte("hashed-token")
|
||||
expiresAt := time.Now().Add(s.ttl)
|
||||
|
||||
s.tokens.EXPECT().Generate().Return("raw-token", hash, nil).Once()
|
||||
s.sessions.EXPECT().
|
||||
Create(mock.Anything, mock.MatchedBy(func(candidate domain.NewSession) bool {
|
||||
return bytes.Equal(candidate.TokenHash, hash) &&
|
||||
candidate.UserID == s.user.ID &&
|
||||
candidate.ExpiresAt.After(time.Now())
|
||||
})).
|
||||
Return(domain.Session{ExpiresAt: expiresAt}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("raw-token", got.Token)
|
||||
s.Equal(s.user, got.User)
|
||||
s.Equal(expiresAt, got.ExpiresAt)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesTokenGenerationError() {
|
||||
s.tokens.EXPECT().Generate().Return("", nil, errors.New("no entropy")).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
userID := uuid.New()
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Revoke(mock.Anything, userID, hash).Return(nil).Once()
|
||||
|
||||
s.Require().NoError(s.service.Revoke(s.T().Context(), userID, "raw-token"))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeRejectsMalformedToken() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
err := s.service.Revoke(s.T().Context(), uuid.New(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateVerifiesPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateRejectsWrongPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
_, err = s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticatePropagatesUnknownUser() {
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "nobody").
|
||||
Return(domain.UserCredentials{}, domain.ErrUnauthenticated).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Authenticate(s.T().Context(), "nobody", "secret-password-123")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateUpgradesHashesWithCAS() {
|
||||
plain := "secret-password-123"
|
||||
for _, legacy := range []bool{false, true} {
|
||||
oldHash := obsoleteHash(plain, legacy)
|
||||
for _, updated := range []bool{true, false} {
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
s.sessions.On("UpdatePasswordHash", mock.Anything, s.user.ID, oldHash,
|
||||
mock.MatchedBy(func(hash string) bool {
|
||||
verified, err := password.Verify(plain, hash)
|
||||
return err == nil && verified.Match && !verified.NeedsRehash
|
||||
})).Return(updated, nil).Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", plain)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestWrongLegacyPasswordDoesNotUpgrade() {
|
||||
oldHash := obsoleteHash("secret-password-123", true)
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
|
||||
_, err := s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
s.sessions.AssertNotCalled(s.T(), "UpdatePasswordHash", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestPasswordUpgradeFailureDoesNotBlockLogin() {
|
||||
oldHash := obsoleteHash("secret-password-123", false)
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
s.sessions.On("UpdatePasswordHash", mock.Anything, s.user.ID, oldHash, mock.Anything).
|
||||
Return(false, domain.ErrUnavailable).Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func obsoleteHash(plain string, legacy bool) string {
|
||||
var salt [16]byte
|
||||
memory, threads := uint32(32), uint8(1)
|
||||
prefix := "$argon2id$v=19$m=32,t=1,p=1$"
|
||||
if legacy {
|
||||
memory, threads = 64*1024, 4
|
||||
prefix = "argon2id$"
|
||||
}
|
||||
hash := argon2.IDKey([]byte(plain), salt[:], 1, memory, threads, 32)
|
||||
return prefix + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// 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}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) domain.User); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewUser) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
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 {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.NewUser
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.NewUser)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewUser
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewUser)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(user domain.User, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.NewUser) (domain.User, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetByID provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetByID")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) domain.User); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByID'
|
||||
type MockRepository_GetByID_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetByID is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetByID(ctx any, id any) *MockRepository_GetByID_Call {
|
||||
return &MockRepository_GetByID_Call{Call: _e.mock.On("GetByID", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockRepository_GetByID_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_GetByID_Call) Return(user domain.User, err error) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) (domain.User, error)) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.NewUser) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users Repository
|
||||
}
|
||||
|
||||
func NewService(users Repository) *Service {
|
||||
return &Service{users: users}
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
hash, err := password.Hash(draft.Password)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
user, err := s.users.Create(ctx, domain.NewUser{
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package user_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/service/user/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
users *mocks.MockRepository
|
||||
service *user.Service
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.users = mocks.NewMockRepository(s.T())
|
||||
s.service = user.NewService(s.users)
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterHashesPasswordAndReturnsStoredUser() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
stored := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.MatchedBy(func(candidate domain.NewUser) bool {
|
||||
return candidate.Username == draft.Username &&
|
||||
candidate.DisplayName == draft.DisplayName &&
|
||||
candidate.PasswordHash != "" &&
|
||||
candidate.PasswordHash != draft.Password
|
||||
})).
|
||||
Return(stored, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got, "сервис отдаёт то, что присвоило хранилище")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsBlankDisplayNameWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: " ", Password: "very-secret-password"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsShortPasswordWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.Anything).
|
||||
Return(domain.User{}, domain.ErrUsernameTaken).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDPropagatesNotFound() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDWrapsRepositoryFailure() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, errRepository).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
Reference in New Issue
Block a user