lab4: S3-вложения, presigned upload и проверки

This commit is contained in:
Vladislav Kunetskiy
2026-10-21 22:42:48 +03:00
parent d342b2a227
commit 49c2fe3071
79 changed files with 12266 additions and 910 deletions
@@ -0,0 +1,115 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
mock "github.com/stretchr/testify/mock"
)
// NewMockLockStore creates a new instance of MockLockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockLockStore(t interface {
mock.TestingT
Cleanup(func())
}) *MockLockStore {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockLockStore{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockLockStore is an autogenerated mock type for the LockStore type
type MockLockStore struct {
mock.Mock
}
type MockLockStore_Expecter struct {
mock *mock.Mock
}
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
return &MockLockStore_Expecter{mock: &_m.Mock}
}
// AcquireSweepLock provides a mock function for the type MockLockStore
func (_mock *MockLockStore) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
ret := _mock.Called(ctx)
if len(ret) == 0 {
panic("no return value specified for AcquireSweepLock")
}
var r0 func()
var r1 bool
var r2 error
if returnFunc, ok := ret.Get(0).(func(context.Context) (func(), bool, error)); ok {
return returnFunc(ctx)
}
if returnFunc, ok := ret.Get(0).(func(context.Context) func()); ok {
r0 = returnFunc(ctx)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(func())
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context) bool); ok {
r1 = returnFunc(ctx)
} else {
r1 = ret.Get(1).(bool)
}
if returnFunc, ok := ret.Get(2).(func(context.Context) error); ok {
r2 = returnFunc(ctx)
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// MockLockStore_AcquireSweepLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireSweepLock'
type MockLockStore_AcquireSweepLock_Call struct {
*mock.Call
}
// AcquireSweepLock is a helper method to define mock.On call
// - ctx context.Context
func (_e *MockLockStore_Expecter) AcquireSweepLock(ctx any) *MockLockStore_AcquireSweepLock_Call {
return &MockLockStore_AcquireSweepLock_Call{Call: _e.mock.On("AcquireSweepLock", ctx)}
}
func (_c *MockLockStore_AcquireSweepLock_Call) Run(run func(ctx context.Context)) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
run(
arg0,
)
})
return _c
}
func (_c *MockLockStore_AcquireSweepLock_Call) Return(release func(), acquired bool, err error) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Return(release, acquired, err)
return _c
}
func (_c *MockLockStore_AcquireSweepLock_Call) RunAndReturn(run func(ctx context.Context) (func(), bool, error)) *MockLockStore_AcquireSweepLock_Call {
_c.Call.Return(run)
return _c
}
@@ -0,0 +1,683 @@
// 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"
)
// 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.AttachmentDraft) (domain.Attachment, error) {
ret := _mock.Called(ctx, draft)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) (domain.Attachment, error)); ok {
return returnFunc(ctx, draft)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) domain.Attachment); ok {
r0 = returnFunc(ctx, draft)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft) 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.AttachmentDraft
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
}
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *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.AttachmentDraft
if args[1] != nil {
arg1 = args[1].(domain.AttachmentDraft)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Create_Call) Return(attachment domain.Attachment, err error) *MockRepository_Create_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_Create_Call {
_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
}
// 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
}
// ListKeys provides a mock function for the type MockRepository
func (_mock *MockRepository) ListKeys(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error) {
ret := _mock.Called(ctx, limit, offset)
if len(ret) == 0 {
panic("no return value specified for ListKeys")
}
var r0 []domain.AttachmentKey
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) ([]domain.AttachmentKey, error)); ok {
return returnFunc(ctx, limit, offset)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) []domain.AttachmentKey); ok {
r0 = returnFunc(ctx, limit, offset)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.AttachmentKey)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, int32, int32) error); ok {
r1 = returnFunc(ctx, limit, offset)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListKeys'
type MockRepository_ListKeys_Call struct {
*mock.Call
}
// ListKeys is a helper method to define mock.On call
// - ctx context.Context
// - limit int32
// - offset int32
func (_e *MockRepository_Expecter) ListKeys(ctx any, limit any, offset any) *MockRepository_ListKeys_Call {
return &MockRepository_ListKeys_Call{Call: _e.mock.On("ListKeys", ctx, limit, offset)}
}
func (_c *MockRepository_ListKeys_Call) Run(run func(ctx context.Context, limit int32, offset int32)) *MockRepository_ListKeys_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 int32
if args[1] != nil {
arg1 = args[1].(int32)
}
var arg2 int32
if args[2] != nil {
arg2 = args[2].(int32)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_ListKeys_Call) Return(attachmentKeys []domain.AttachmentKey, err error) *MockRepository_ListKeys_Call {
_c.Call.Return(attachmentKeys, err)
return _c
}
func (_c *MockRepository_ListKeys_Call) RunAndReturn(run func(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error)) *MockRepository_ListKeys_Call {
_c.Call.Return(run)
return _c
}
// ListStalePending provides a mock function for the type MockRepository
func (_mock *MockRepository) ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error) {
ret := _mock.Called(ctx, createdBefore, limit)
if len(ret) == 0 {
panic("no return value specified for ListStalePending")
}
var r0 []domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) ([]domain.Attachment, error)); ok {
return returnFunc(ctx, createdBefore, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) []domain.Attachment); ok {
r0 = returnFunc(ctx, createdBefore, limit)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.Attachment)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int32) error); ok {
r1 = returnFunc(ctx, createdBefore, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListStalePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStalePending'
type MockRepository_ListStalePending_Call struct {
*mock.Call
}
// ListStalePending is a helper method to define mock.On call
// - ctx context.Context
// - createdBefore time.Time
// - limit int32
func (_e *MockRepository_Expecter) ListStalePending(ctx any, createdBefore any, limit any) *MockRepository_ListStalePending_Call {
return &MockRepository_ListStalePending_Call{Call: _e.mock.On("ListStalePending", ctx, createdBefore, limit)}
}
func (_c *MockRepository_ListStalePending_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int32)) *MockRepository_ListStalePending_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 time.Time
if args[1] != nil {
arg1 = args[1].(time.Time)
}
var arg2 int32
if args[2] != nil {
arg2 = args[2].(int32)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_ListStalePending_Call) Return(attachments []domain.Attachment, err error) *MockRepository_ListStalePending_Call {
_c.Call.Return(attachments, err)
return _c
}
func (_c *MockRepository_ListStalePending_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)) *MockRepository_ListStalePending_Call {
_c.Call.Return(run)
return _c
}
// ListStates provides a mock function for the type MockRepository
func (_mock *MockRepository) ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error) {
ret := _mock.Called(ctx, chatID, ids)
if len(ret) == 0 {
panic("no return value specified for ListStates")
}
var r0 []domain.AttachmentState
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) ([]domain.AttachmentState, error)); ok {
return returnFunc(ctx, chatID, ids)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) []domain.AttachmentState); ok {
r0 = returnFunc(ctx, chatID, ids)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]domain.AttachmentState)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, []uuid.UUID) error); ok {
r1 = returnFunc(ctx, chatID, ids)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
type MockRepository_ListStates_Call struct {
*mock.Call
}
// ListStates is a helper method to define mock.On call
// - ctx context.Context
// - chatID uuid.UUID
// - ids []uuid.UUID
func (_e *MockRepository_Expecter) ListStates(ctx any, chatID any, ids any) *MockRepository_ListStates_Call {
return &MockRepository_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
}
func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockRepository_ListStates_Call {
_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_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockRepository_ListStates_Call {
_c.Call.Return(attachmentStates, err)
return _c
}
func (_c *MockRepository_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockRepository_ListStates_Call {
_c.Call.Return(run)
return _c
}
// MarkReady provides a mock function for the type MockRepository
func (_mock *MockRepository) MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error) {
ret := _mock.Called(ctx, id, objectKey)
if len(ret) == 0 {
panic("no return value specified for MarkReady")
}
var r0 domain.Attachment
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) (domain.Attachment, error)); ok {
return returnFunc(ctx, id, objectKey)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) domain.Attachment); ok {
r0 = returnFunc(ctx, id, objectKey)
} else {
r0 = ret.Get(0).(domain.Attachment)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string) error); ok {
r1 = returnFunc(ctx, id, objectKey)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_MarkReady_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkReady'
type MockRepository_MarkReady_Call struct {
*mock.Call
}
// MarkReady is a helper method to define mock.On call
// - ctx context.Context
// - id uuid.UUID
// - objectKey string
func (_e *MockRepository_Expecter) MarkReady(ctx any, id any, objectKey any) *MockRepository_MarkReady_Call {
return &MockRepository_MarkReady_Call{Call: _e.mock.On("MarkReady", ctx, id, objectKey)}
}
func (_c *MockRepository_MarkReady_Call) Run(run func(ctx context.Context, id uuid.UUID, objectKey string)) *MockRepository_MarkReady_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 string
if args[2] != nil {
arg2 = args[2].(string)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_MarkReady_Call) Return(attachment domain.Attachment, err error) *MockRepository_MarkReady_Call {
_c.Call.Return(attachment, err)
return _c
}
func (_c *MockRepository_MarkReady_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)) *MockRepository_MarkReady_Call {
_c.Call.Return(run)
return _c
}
+487
View File
@@ -0,0 +1,487 @@
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"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/imagecheck"
"mtusi-messenger/internal/platform/objectstore"
)
const (
contentTypePNG = "image/png"
contentTypeJPEG = "image/jpeg"
objectPrefixAttachments = "attachments/"
objectPrefixStaging = "staging/"
objectPrefixPresign = "staging/presign/"
)
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.
type Repository interface {
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)
DeletePending(ctx context.Context, id uuid.UUID) error
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)
ListKeys(ctx context.Context, limit, offset int32) ([]domain.AttachmentKey, error)
}
// Config carries the attachment limits. They are validated by config.Load.
type Config struct {
MaxUploadBytes int64
MaxImagePixels int64
PresignTTL time.Duration
}
type Service struct {
repo Repository
store objectstore.Store
config Config
log *slog.Logger
}
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
if log == nil {
log = slog.Default()
}
return &Service{repo: repo, store: store, config: config, log: log}
}
// 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
}
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
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)
}
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)
}
objectKey := objectPrefixAttachments + input.ChatID.String() + "/" + id.String()
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
ID: id,
ChatID: input.ChatID,
OwnerID: input.OwnerID,
ObjectKey: objectKey,
Filename: input.Filename,
ContentType: info.ContentType,
SizeBytes: size,
SHA256: sum,
}); err != nil {
return domain.Attachment{}, err
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
}
if err := s.store.Put(ctx, objectKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
s.cleanupPending(ctx, id, "")
return domain.Attachment{}, unavailable("store attachment", err)
}
ready, err := s.repo.MarkReady(ctx, id, objectKey)
if err != nil {
// The object and the pending row remain; the sweeper either finalises
// the row or removes both after the grace period. The client must not
// receive 201 until metadata is committed.
return domain.Attachment{}, unavailable("commit attachment", err)
}
return ready, nil
}
func (s *Service) Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, err
}
// Contract 1.4.0 declares Attachment.status as the single value "ready".
// Pending/failed rows therefore cannot be represented in a 200 response;
// they are reported as 409 until lab5 extends the enum.
if attachment.Status != domain.AttachmentReady {
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
}
return attachment, nil
}
// Open returns metadata and the original stream. Only ready attachments have
// bytes; pending/failed return 409 on the content endpoint.
func (s *Service) Open(
ctx context.Context,
callerID, id uuid.UUID,
) (domain.Attachment, io.ReadCloser, error) {
attachment, err := s.repo.GetForMember(ctx, callerID, id)
if err != nil {
return domain.Attachment{}, nil, err
}
if attachment.Status != domain.AttachmentReady {
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
}
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
if err != nil {
return domain.Attachment{}, nil, err
}
return attachment, body, 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 || 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.Create(ctx, domain.AttachmentDraft{
ID: id,
ChatID: request.ChatID,
OwnerID: request.OwnerID,
ObjectKey: stagingKey,
Filename: request.Filename,
ContentType: request.ContentType,
SizeBytes: request.SizeBytes,
SHA256: request.SHA256,
}); err != nil {
return domain.PresignResult{}, err
}
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, 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
}
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:
if attachment.SHA256 != requestSHA {
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
}
return attachment, nil
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
}
hasher := sha256.New()
info, validateErr := imagecheck.Validate(io.TeeReader(body, hasher), s.config.MaxImagePixels)
closeErr := body.Close()
if validateErr != nil {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, mapImageError(validateErr)
}
if closeErr != nil {
return domain.Attachment{}, unavailable("read uploaded object", closeErr)
}
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,
)
}
sum := hex.EncodeToString(hasher.Sum(nil))
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 {
s.cleanupPending(ctx, id, attachment.ObjectKey)
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
}
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
if err := s.store.Copy(ctx, attachment.ObjectKey, finalKey, attachment.ContentType, map[string]string{"sha256": sum}); err != nil {
return domain.Attachment{}, unavailable("publish attachment", err)
}
ready, err := s.repo.MarkReady(ctx, id, finalKey)
if err != nil {
// A concurrent completion may have won. Re-read instead of reporting a
// spurious failure.
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
if getErr == nil && current.Status == domain.AttachmentReady && current.SHA256 == requestSHA {
return current, nil
}
return domain.Attachment{}, unavailable("commit attachment", err)
}
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil {
// The final object is already committed; a stale staging object is an
// orphan and the sweeper removes it after the grace period.
s.log.WarnContext(ctx, "staging object cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
return ready, nil
}
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
file, err := os.CreateTemp("", "lab4-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) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
if objectKey != "" {
if err := s.store.Delete(ctx, objectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
s.log.WarnContext(ctx, "object cleanup failed",
slog.String("attachment_id", id.String()),
slog.Any("error", err),
)
}
}
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.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)
}
+318
View File
@@ -0,0 +1,318 @@
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) 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, 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,
}
}
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{"", 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 TestUploadStoresOriginal(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)
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
repo.EXPECT().Create(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
draft.SHA256 == hex.EncodeToString(sum[:]) && strings.HasPrefix(draft.ObjectKey, "attachments/")
})).Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, mock.Anything, mock.Anything).
Return(domain.Attachment{Status: domain.AttachmentReady, ContentType: "image/png", SizeBytes: int64(len(content))}, nil).
Once()
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.AttachmentReady, result.Status)
require.Len(t, store.objects, 1)
}
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,
}, slog.Default())
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, 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()
_, 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 TestGetRejectsNonReadyAttachment(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 TestCompletePublishesPresignedObject(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,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending,
}
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, id, mock.MatchedBy(func(key string) bool {
return strings.HasPrefix(key, "attachments/")
})).Return(domain.Attachment{
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
SizeBytes: int64(len(content)), SHA256: digest, Status: domain.AttachmentReady,
}, nil).Once()
completed, err := service.Complete(t.Context(), ownerID, id, digest)
require.NoError(t, err)
require.Equal(t, domain.AttachmentReady, completed.Status)
require.NotContains(t, store.objects, stagingKey)
require.Len(t, store.objects, 1)
}
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,
ContentType: "image/png", SizeBytes: int64(len(content)) + 1, SHA256: digest,
Status: domain.AttachmentPending,
}
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)
}
+235
View File
@@ -0,0 +1,235 @@
package attachment
import (
"context"
"errors"
"log/slog"
"strings"
"time"
"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)
}
type SweepStats struct {
Recovered int
RowsDeleted int
ObjectsDeleted int
}
type Sweeper struct {
repo Repository
store objectstore.Store
locker LockStore
grace time.Duration
interval time.Duration
log *slog.Logger
}
func NewSweeper(
repo Repository,
store objectstore.Store,
locker LockStore,
grace, interval time.Duration,
log *slog.Logger,
) *Sweeper {
if log == nil {
log = slog.Default()
}
return &Sweeper{
repo: repo,
store: store,
locker: locker,
grace: grace,
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.Recovered+stats.RowsDeleted+stats.ObjectsDeleted > 0 {
s.log.InfoContext(ctx, "attachment sweep finished",
slog.Int("recovered", stats.Recovered),
slog.Int("rows_deleted", stats.RowsDeleted),
slog.Int("objects_deleted", stats.ObjectsDeleted),
)
}
}
// SweepOnce reconciles PostgreSQL metadata with S3 objects. It never deletes a
// ready row or an object referenced by any row. Only objects older than the
// grace period are candidates, so an in-flight upload cannot be collected.
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()
before := time.Now().UTC().Add(-s.grace)
var stats SweepStats
stale, err := s.repo.ListStalePending(ctx, before, 100)
if err != nil {
return stats, err
}
for _, row := range stale {
if row.Status != domain.AttachmentPending {
continue
}
if strings.HasPrefix(row.ObjectKey, objectPrefixPresign) {
if s.deleteObject(ctx, row.ObjectKey) {
stats.ObjectsDeleted++
}
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
return stats, err
}
stats.RowsDeleted++
continue
}
// A proxy upload writes directly to its final key. If the process died
// between PutObject and MarkReady, the object is complete and can be
// recovered instead of discarded.
head, err := s.store.Head(ctx, row.ObjectKey)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
return stats, err
}
stats.RowsDeleted++
continue
}
s.log.WarnContext(ctx, "sweep head failed",
slog.String("attachment_id", row.ID.String()),
slog.Any("error", err),
)
continue
}
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err == nil {
stats.Recovered++
continue
}
}
if s.deleteObject(ctx, row.ObjectKey) {
stats.ObjectsDeleted++
}
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
return stats, err
}
stats.RowsDeleted++
}
referenced, err := s.referencedKeys(ctx)
if err != nil {
return stats, err
}
for _, prefix := range []string{objectPrefixAttachments, objectPrefixStaging} {
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{})
for offset := int32(0); ; offset += pageSize {
rows, err := s.repo.ListKeys(ctx, pageSize, offset)
if err != nil {
return nil, err
}
for _, row := range rows {
keys[row.ObjectKey] = struct{}{}
}
if len(rows) < pageSize {
return keys, nil
}
}
}
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.String("object_key", key),
slog.Any("error", err),
)
}
return false
}
@@ -0,0 +1,90 @@
package attachment_test
import (
"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 TestSweepReconcilesPendingAndOrphanObjects(t *testing.T) {
repo := mocks.NewMockRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
stale := time.Now().UTC().Add(-time.Hour)
presign := domain.Attachment{
ID: uuid.New(), ObjectKey: "staging/presign/chat/" + uuid.NewString(),
Status: domain.AttachmentPending, CreatedAt: stale,
}
proxyRecoverable := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Status: domain.AttachmentPending, CreatedAt: stale,
}
proxyMissing := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
Status: domain.AttachmentPending, CreatedAt: stale,
}
readyKey := "attachments/chat/ready"
store.objects[presign.ObjectKey] = storedObject{data: []byte("x"), lastModified: stale}
store.objects[proxyRecoverable.ObjectKey] = storedObject{
data: []byte("abc"),
lastModified: stale,
metadata: map[string]string{"sha256": proxyRecoverable.SHA256},
}
store.objects[readyKey] = storedObject{data: []byte("ready"), lastModified: stale}
store.objects["attachments/chat/orphan"] = storedObject{data: []byte("orphan"), lastModified: stale}
store.objects["staging/abandoned"] = storedObject{data: []byte("stale"), lastModified: stale}
store.objects["staging/fresh"] = storedObject{data: []byte("fresh"), lastModified: time.Now().UTC()}
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
Return([]domain.Attachment{presign, proxyRecoverable, proxyMissing}, nil).Once()
repo.EXPECT().DeletePending(mock.Anything, presign.ID).Return(nil).Once()
repo.EXPECT().MarkReady(mock.Anything, proxyRecoverable.ID, proxyRecoverable.ObjectKey).
Return(domain.Attachment{ID: proxyRecoverable.ID, Status: domain.AttachmentReady}, nil).Once()
repo.EXPECT().DeletePending(mock.Anything, proxyMissing.ID).Return(nil).Once()
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
Return([]domain.AttachmentKey{
{ID: proxyRecoverable.ID, ObjectKey: proxyRecoverable.ObjectKey, Status: domain.AttachmentReady},
{ID: uuid.New(), ObjectKey: readyKey, Status: domain.AttachmentReady},
}, nil).Once()
locker.EXPECT().AcquireSweepLock(mock.Anything).
Return(func() {}, true, nil).Once()
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
stats, err := sweeper.SweepOnce(t.Context())
require.NoError(t, err)
require.Equal(t, 1, stats.Recovered)
require.Equal(t, 2, stats.RowsDeleted)
require.Equal(t, 3, stats.ObjectsDeleted)
require.NotContains(t, store.objects, presign.ObjectKey)
require.NotContains(t, store.objects, "attachments/chat/orphan")
require.NotContains(t, store.objects, "staging/abandoned")
require.Contains(t, store.objects, proxyRecoverable.ObjectKey)
require.Contains(t, store.objects, readyKey)
require.Contains(t, store.objects, "staging/fresh")
}
func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
repo := mocks.NewMockRepository(t)
locker := mocks.NewMockLockStore(t)
sweeper := attachment.NewSweeper(repo, newFakeStore(), locker, time.Minute, time.Hour, 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)
}
@@ -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
}
@@ -114,6 +114,78 @@ func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context,
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)
+46 -4
View File
@@ -10,6 +10,7 @@ import (
)
type Repository interface {
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
ListVisible(
ctx context.Context,
@@ -19,12 +20,20 @@ type Repository interface {
) (domain.Page[domain.Message], error)
}
type Service struct {
messages Repository
// 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)
}
func NewService(messages Repository) *Service {
return &Service{messages: messages}
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) {
@@ -32,6 +41,39 @@ func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.M
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)
}
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 {
if state.Status != domain.AttachmentReady {
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)
+88 -8
View File
@@ -18,11 +18,12 @@ var errRepository = errors.New("repository is unavailable")
type ServiceSuite struct {
suite.Suite
messages *mocks.MockRepository
service *message.Service
caller uuid.UUID
chatID uuid.UUID
now time.Time
messages *mocks.MockRepository
attachments *mocks.MockAttachmentChecker
service *message.Service
caller uuid.UUID
chatID uuid.UUID
now time.Time
}
func TestServiceSuite(t *testing.T) {
@@ -32,7 +33,8 @@ func TestServiceSuite(t *testing.T) {
func (s *ServiceSuite) SetupTest() {
s.messages = mocks.NewMockRepository(s.T())
s.service = message.NewService(s.messages)
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)
@@ -57,6 +59,7 @@ func (s *ServiceSuite) TestSendReturnsStoredMessage() {
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)
@@ -76,11 +79,11 @@ func (s *ServiceSuite) TestSendRejectsWhitespaceTextWithoutRepositoryCall() {
func (s *ServiceSuite) TestSendPropagatesNotFoundForOutsider() {
draft := s.draft()
s.messages.EXPECT().Create(s.T().Context(), draft).Return(domain.Message{}, domain.ErrNotFound).Once()
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() {
@@ -142,3 +145,80 @@ func (s *ServiceSuite) TestHistoryWrapsRepositoryFailure() {
_, 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) 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)
}