This commit is contained in:
Vladislav Kunetskiy
2026-10-29 23:36:12 +03:00
parent 276dbdad8a
commit 6344754111
383 changed files with 68663 additions and 194 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
}
+495
View File
@@ -0,0 +1,495 @@
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 {
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.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, 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
}
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 {
// The object is valid; only the completion request is inconsistent.
// Keep the pending row and staging object so a retry can succeed.
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
}
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
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.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)
}
+361
View File
@@ -0,0 +1,361 @@
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, _ 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,
}
}
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 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)
}
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,
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
Status: domain.AttachmentPending,
}
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)
}
+243
View File
@@ -0,0 +1,243 @@
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 {
// A transient database failure must not destroy a valid object.
// Leave both the row and the object for the next sweep.
s.log.WarnContext(ctx, "sweep recovery failed",
slog.String("attachment_id", row.ID.String()),
slog.Any("error", err),
)
continue
}
stats.Recovered++
continue
}
if s.deleteObject(ctx, row.ObjectKey) {
stats.ObjectsDeleted++
}
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
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
}
+126
View File
@@ -0,0 +1,126 @@
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 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)
}
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
repo := mocks.NewMockRepository(t)
locker := mocks.NewMockLockStore(t)
store := newFakeStore()
stale := time.Now().UTC().Add(-time.Hour)
row := domain.Attachment{
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Status: domain.AttachmentPending, CreatedAt: stale,
}
store.objects[row.ObjectKey] = storedObject{
data: []byte("abc"),
lastModified: stale,
metadata: map[string]string{"sha256": row.SHA256},
}
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
Return([]domain.Attachment{row}, nil).Once()
repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey).
Return(domain.Attachment{}, context.DeadlineExceeded).Once()
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once()
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.Zero(t, stats.Recovered)
require.Zero(t, stats.RowsDeleted)
require.Contains(t, store.objects, row.ObjectKey)
}
+265
View File
@@ -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
}
+69
View File
@@ -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
}
+140
View File
@@ -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,271 @@
// 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
}
+101
View File
@@ -0,0 +1,101 @@
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)
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)
}
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)
}
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
}
+224
View File
@@ -0,0 +1,224 @@
package message_test
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"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)
}
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) 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,310 @@
// 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
}
+168
View File
@@ -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
}
+95
View File
@@ -0,0 +1,95 @@
package session
import (
"context"
"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)
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 {
return domain.User{}, fmt.Errorf("authenticate: %w", err)
}
if !password.Verify(plain, credentials.PasswordHash) {
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
}
return credentials.User, nil
}
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
}
+146
View File
@@ -0,0 +1,146 @@
package session_test
import (
"bytes"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"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)
}
+181
View File
@@ -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
}
+55
View File
@@ -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
}
+104
View File
@@ -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)
}