Перейти к содержанию

КАРТА КОНСОЛИДАЦИИ USER API РОУТЕРОВ

Дата анализа: 2025-10-02 Цель: Подготовка к консолидации 11 файлов роутеров в 1 unified файл


SUMMARY

Текущее состояние:

  • 11 файлов роутеров
  • 35 endpoints (14 auth + 21 user data)
  • 5608 строк кода

Целевое состояние:

  • 1 файл user_api_router.go
  • 35 endpoints (сохраняем все)
  • ~2000 строк кода (экономия 64%)

ENDPOINTS → HANDLERS КАРТА

1. AUTH ENDPOINTS (14 endpoints) - user_auth_router.go

Endpoint Handler Тип Middleware
/api/auth/check handleAuthCheck() GET Публичный
/api/auth/cookie/verify handleCookieVerify() GET Публичный
/api/auth/cookie/logout handleCookieLogout() POST Публичный
/api/auth/cookie/profile handleCookieProfile() GET Публичный
/api/auth/status handleAuthStatus() GET Публичный (НИКОГДА не 401)
/api/auth/wallet/register handleWalletRegister() POST Публичный
/api/auth/wallet/login handleWalletLogin() POST Публичный
/api/auth/wallet/check handleWalletCheck() POST Публичный
/api/auth/refresh handleRefreshToken() POST Публичный
/api/auth/test-refresh handleTestRefreshToken() POST Публичный (тестовый)
/api/auth/profile handleAuthProfile() GET JWT Protected
/api/auth/logout handleLogout() POST JWT Protected
/api/auth/wallet/connect handleWalletConnect() POST JWT Protected
/api/user/ping handleUserPing() GET JWT Protected

2. BALANCE ENDPOINTS (5 endpoints) - user_balance_router.go

Endpoint Handler Тип Middleware
/api/user/balance handleGetBalance() GET JWT Protected
/api/user/balance/history handleGetBalanceHistory() GET JWT Protected
/api/user/deposits handleGetDeposits() GET JWT Protected
/api/user/deposits/address handleGetDepositAddress() GET JWT Protected
/api/user/dashboard handleDashboard() GET JWT Protected

3. INVESTMENT ENDPOINTS (8 endpoints) - user_investment_router.go

Endpoint Handler Тип Middleware
/api/user/investments handleGetInvestments() GET JWT Protected
/api/user/investments handleCreateInvestment() POST JWT Protected
/api/user/investments/{id} handleGetInvestment() GET JWT Protected
/api/user/investments/{id} handleDeleteInvestment() DELETE JWT Protected
/api/user/investments/{id}/cancel handleCancelInvestment() POST JWT Protected
/api/user/investments/performance handleGetPortfolioPerformance() GET JWT Protected
/api/user/strategies handleGetStrategies() GET JWT Protected
/api/user/strategies/{id} handleGetStrategy() GET JWT Protected
/api/user/strategies/{id}/performance handleGetStrategyPerformance() GET JWT Protected

4. PROFILE ENDPOINTS (3 endpoints) - user_profile_router.go

Endpoint Handler Тип Middleware
/api/user/profile handleGetProfile() GET JWT Protected
/api/user/profile handleUpdateProfile() PUT JWT Protected
/api/user/dashboard/stats handleGetDashboardStats() GET JWT Protected

⚠️ CONFLICT: /api/user/dashboard дублируется в user_investment_router.go и user_profile_router.go!

5. TRANSACTION ENDPOINTS (2 endpoints) - user_transaction_router.go

Endpoint Handler Тип Middleware
/api/user/transactions handleGetTransactions() GET JWT Protected
/api/user/transactions/{id} handleGetTransaction() GET JWT Protected

6. WITHDRAWAL ENDPOINTS (1 endpoint) - user_withdrawal_router.go

Endpoint Handler Тип Middleware
/api/user/withdrawals handleGetWithdrawals() GET JWT Protected

7. NOTIFICATION ENDPOINTS (4 endpoints) - user_notification_router.go

Endpoint Handler Тип Middleware
/api/user/notifications handleGetNotifications() GET JWT Protected
/api/user/notifications/{id}/read handleMarkNotificationRead() PUT JWT Protected
/api/user/notifications/mark-all-read handleMarkAllRead() PUT JWT Protected
/api/user/notifications/unread/count handleGetUnreadCount() GET JWT Protected

DEPENDENCIES АНАЛИЗ

UserAuthRouter Dependencies:

*BaseHandler
authService          sharedInterfaces.AuthServiceInterface
authMiddleware       *middleware.AuthMiddleware
canonicalUserService canonical.ComprehensiveUserService

UserBalanceRouter Dependencies:

*BaseHandler
logger               logging.CanonicalLogger
traceLogger          middlewareInterfaces.TraceLoggerInterface
balanceService       canonical.BalanceService
transactionService   canonical.CanonicalTransactionService
currencyService      interfaces.CurrencyService
depositProvider      interfaces.DepositAddressProvider
blockchainService    interfaces.BlockchainServiceInterface
validationService    validationUnified.UnifiedValidationInterface
confirmationService  blockchainValidation.ConfirmationService
corsMiddleware       middlewareInterfaces.CORSMiddlewareInterface
authMiddleware       middlewareInterfaces.AuthMiddlewareInterface
config               config.ConfigInterface
errorHandler         middlewareInterfaces.HTTPErrorHandlerInterface

UserInvestmentRouter Dependencies:

*BaseHandler
canonicalInvestmentService canonical.CanonicalInvestmentService
authService                sharedInterfaces.AuthServiceInterface
userService                storageInterfaces.UserService
strategyService            sharedInterfaces.StrategyService
investmentService          sharedServices.UserInvestmentServiceInterface
valueService               *sharedServices.InvestmentValueService
authMiddleware             *middleware.AuthMiddleware

UserProfileRouter Dependencies:

*BaseHandler
authService          sharedInterfaces.AuthServiceInterface
userService          storageInterfaces.UserService
authMiddleware       *middleware.AuthMiddleware
canonicalUserService canonical.ComprehensiveUserService

UserTransactionRouter Dependencies:

*BaseHandler
transactionService canonical.CanonicalTransactionService
authMiddleware     *middleware.AuthMiddleware

UserWithdrawalRouter Dependencies:

*BaseHandler
withdrawalService  sharedInterfaces.WithdrawalServiceInterface
authMiddleware     *middleware.AuthMiddleware

UserNotificationRouter Dependencies:

*BaseHandler
notificationService *notificationService.NotificationServiceImpl
authMiddleware      *middleware.AuthMiddleware

ОБНАРУЖЕННЫЕ ПРОБЛЕМЫ

1. ДУБЛИКАТ ENDPOINT: /api/user/dashboard

  • user_investment_router.go: handleDashboard()
  • user_profile_router.go: handleGetDashboard()

Решение: Определить какой правильный, удалить дубликат

2. ДУБЛИРОВАНИЕ DEPENDENCIES

Каждый роутер создает свои: - authMiddleware (7 раз!) - *BaseHandler (7 раз!) - authService (3 раза)

Решение: Единая структура с общими dependencies

3. КОМПОЗИТНЫЙ ОРКЕСТРАТОР

clean_user_router.go делегирует во все остальные роутеры - лишний слой абстракции

Решение: Удалить после консолидации


UNIFIED DEPENDENCIES (для UserAPIRouter)

type UserAPIRouter struct {
    *BaseHandler

    // Middleware
    authMiddleware       *middleware.AuthMiddleware
    corsMiddleware       middlewareInterfaces.CORSMiddlewareInterface

    // Auth & User
    authService          sharedInterfaces.AuthServiceInterface
    canonicalUserService canonical.ComprehensiveUserService
    userService          storageInterfaces.UserService

    // Financial Services
    balanceService       canonical.BalanceService
    transactionService   canonical.CanonicalTransactionService
    currencyService      interfaces.CurrencyService

    // Investment Services
    canonicalInvestmentService canonical.CanonicalInvestmentService
    investmentService          sharedServices.UserInvestmentServiceInterface
    valueService               *sharedServices.InvestmentValueService
    strategyService            sharedInterfaces.StrategyService

    // Other Services
    withdrawalService    sharedInterfaces.WithdrawalServiceInterface
    notificationService  *notificationService.NotificationServiceImpl
    depositProvider      interfaces.DepositAddressProvider
    blockchainService    interfaces.BlockchainServiceInterface
    confirmationService  blockchainValidation.ConfirmationService
    validationService    validationUnified.UnifiedValidationInterface

    // Infrastructure
    logger               logging.CanonicalLogger
    traceLogger          middlewareInterfaces.TraceLoggerInterface
    errorHandler         middlewareInterfaces.HTTPErrorHandlerInterface
    config               config.ConfigInterface
}

МЕСТА ИСПОЛЬЗОВАНИЯ РОУТЕРОВ

1. RouterFactory (backend/shared/routing/router_factory.go)

Метод: CreateCompositeRouter()createCleanUserRouter() (строка 178)

// RouterFactory создает CleanUserRouter
cleanUserRouter, err := rf.createCleanUserRouter()
if err != nil {
    return nil, fmt.Errorf("failed to create clean user router: %w", err)
}

// Регистрирует все user endpoints
cleanUserRouter.RegisterRoutes(mainRouter)

ВАЖНО: RouterFactory - единственное место создания user роутеров!

2. CompositeRouter (backend/shared/routing/composite_router.go)

Строка 621-631: Использует RouterFactory для создания всех роутеров:

routerFactory := NewRouterFactory(routerDeps)
router, err := routerFactory.CreateCompositeRouter()  // ← создает все роутеры внутри

3. Tests (backend/tests/)

Файлы использующие routing пакет: - backend/tests/integration/test_helpers.go - создание тестовых роутеров - backend/tests/unit/routing_helper_functions_test.go - unit тесты routing - backend/tests/unit/routing_helper_functions_isolated_test.go - изолированные тесты

Импорты: Тесты импортируют "github.com/aiseeq/saga/backend/shared/routing" но НЕ используют конкретные роутеры напрямую

4. Main (backend/cmd/saga/main.go)

Строка 652-673: Использует CompositeRouter (который использует RouterFactory)

// CompositeRouter активирован
sagaServerLogger.InfoStructured("✅ CompositeRouter активирован", ...)

ВЫВОД: ИЗОЛИРОВАННОЕ ИСПОЛЬЗОВАНИЕ

Роутеры используются ТОЛЬКО через:

  1. RouterFactory.createCleanUserRouter() (строка 178-220)
  2. CleanUserRouter.RegisterRoutes() (композитный, делегирует)

Для миграции нужно изменить ТОЛЬКО: - router_factory.go - заменить createCleanUserRouter() на createUserAPIRouter() - Удалить все старые роутеры после миграции


КРИТИЧЕСКИЕ ТЕСТЫ ДЛЯ ВАЛИДАЦИИ

UNIT ТЕСТЫ (backend/tests/unit/)

  • routing_helper_functions_test.go - валидация routing helpers
  • routing_helper_functions_isolated_test.go - изолированные тесты роутинга

SMOKE ТЕСТЫ (backend/tests/smoke/)

  • routing_smoke_test.go - smoke тесты всех endpoints
  • routing_smoke_isolated_test.go - изолированные smoke тесты

INTEGRATION ТЕСТЫ (backend/tests/integration/)

  • routing_regression_test.go - регрессионные тесты роутинга
  • routing_regression_pilot_test.go - pilot регрессионные тесты

E2E ТЕСТЫ (frontend/e2e/tests/)

  • frontend/e2e/tests/user/user-ping.spec.ts - User API ping endpoint (4 теста)
  • frontend/e2e/tests/admin/ - админские endpoints
  • frontend/e2e/tests/critical-paths/ - критические пути

MIDDLEWARE И VALIDATORS

ОБЯЗАТЕЛЬНЫЕ MIDDLEWARE:

  • authMiddleware.WithJWTAuth() - JWT аутентификация (защита user endpoints)
  • corsMiddleware - CORS headers
  • errorHandler - обработка HTTP ошибок
  • traceLogger - логирование запросов

VALIDATORS:

  • validationService.UnifiedValidationInterface - unified валидация
  • balanceService.CanonicalBalanceService - валидация балансов
  • confirmationService.ConfirmationService - подтверждение транзакций

ПЛАН МИГРАЦИИ DEPENDENCIES

Этап 1: Собрать ВСЕ dependencies

  • Проанализированы все struct поля роутеров
  • Создан unified список dependencies
  • Определены обязательные vs опциональные

Этап 2: Определить constructor signature

func NewUserAPIRouter(
    db *sqlx.DB,
    repositories storageInterfaces.CompositeRepositories,
    logger logging.CanonicalLogger,
    config config.ConfigInterface,
    // ... все сервисы
) *UserAPIRouter

Этап 3: Создать factory метод

Обновить RouterFactory для создания UserAPIRouter вместо множественных роутеров


МЕТРИКИ

Метрика Текущее Целевое Изменение
Файлов 11 1 -91%
Строк кода 5608 ~2000 -64%
Endpoints 35 35 0%
Dependencies дубликатов Высокое Нет -100%
Время поиска endpoint 30-60 сек 5-10 сек -80%

СЛЕДУЮЩИЕ ШАГИ (ФАЗА 2)

  1. Создать backend/shared/routing/user_api_router.go
  2. Скопировать ВСЕ handler методы
  3. Объединить dependencies
  4. Создать unified RegisterRoutes()
  5. Создать приватные методы registerXXXRoutes()

Статус ФАЗЫ 1: ✅ ЗАВЕРШЕНО