health_check_test.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env tsx
  2. /**
  3. * 健康检查系统测试
  4. * 测试生产环境模块的健康检查功能
  5. */
  6. import { HealthChecker, HealthAPI } from '../src/infrastructure/health/index.js'
  7. import { ProductionLogger } from '../src/utils/ProductionLogger.js'
  8. class MockAdapter {
  9. name = 'mock-exchange'
  10. async ping() {
  11. return { status: 'ok', timestamp: Date.now() }
  12. }
  13. async time() {
  14. return Date.now()
  15. }
  16. async balances() {
  17. return { USDT: 1000, BTC: 0.5 }
  18. }
  19. }
  20. class MockAccountManager {
  21. getRegisteredAccounts() {
  22. return [
  23. { exchange: 'mock-exchange', accountId: 'account1' },
  24. { exchange: 'mock-exchange', accountId: 'account2' },
  25. ]
  26. }
  27. async getBalances(exchange: string, accountId: string) {
  28. return { USDT: 500, BTC: 0.25 }
  29. }
  30. }
  31. async function testHealthCheck() {
  32. console.log('🏥 测试健康检查系统')
  33. console.log('='.repeat(50))
  34. // 初始化日志器
  35. const logger = new ProductionLogger({
  36. level: 'info',
  37. enableConsole: true,
  38. enableFile: false,
  39. })
  40. // 初始化健康检查器
  41. const healthChecker = new HealthChecker()
  42. // 注册模拟适配器和账户管理器
  43. const mockAdapter = new MockAdapter()
  44. const mockAccountManager = new MockAccountManager()
  45. healthChecker.registerExchange('mock-exchange', mockAdapter as any)
  46. healthChecker.registerAccountManager('mock-manager', mockAccountManager)
  47. // 监听健康检查事件
  48. healthChecker.on('health_check', health => {
  49. logger.info('健康检查完成', {
  50. status: health.status,
  51. exchangeCount: Object.keys(health.exchanges).length,
  52. accountCount: Object.keys(health.accounts).length,
  53. })
  54. })
  55. // 执行健康检查
  56. console.log('📊 执行健康检查...')
  57. const health = await healthChecker.performHealthCheck()
  58. console.log('\n✅ 健康检查结果:')
  59. console.log(`整体状态: ${health.status}`)
  60. console.log(`运行时间: ${Math.round(health.uptime / 1000)}秒`)
  61. console.log(
  62. `交易所状态:`,
  63. Object.entries(health.exchanges)
  64. .map(([name, status]) => `${name}: ${status.status} (连接: ${status.connected ? '✅' : '❌'})`)
  65. .join(', '),
  66. )
  67. console.log(
  68. `账户状态:`,
  69. Object.entries(health.accounts)
  70. .map(([key, status]) => `${key}: ${status.status} (余额可访问: ${status.balanceAccessible ? '✅' : '❌'})`)
  71. .join(', '),
  72. )
  73. console.log(`内存使用: ${Math.round((health.memory.used / health.memory.total) * 100)}%`)
  74. // 获取健康检查摘要
  75. const summary = healthChecker.getHealthSummary()
  76. console.log('\n📋 系统摘要:')
  77. console.log(JSON.stringify(summary, null, 2))
  78. return health
  79. }
  80. async function testHealthAPI() {
  81. console.log('\n🌐 测试健康检查 API')
  82. console.log('='.repeat(50))
  83. const healthChecker = new HealthChecker()
  84. const mockAdapter = new MockAdapter()
  85. healthChecker.registerExchange('mock-exchange', mockAdapter as any)
  86. const healthAPI = new HealthAPI(healthChecker, {
  87. port: 3002, // 使用不同端口避免冲突
  88. host: 'localhost',
  89. })
  90. try {
  91. // 启动健康检查 API
  92. await healthAPI.start()
  93. console.log('✅ 健康检查 API 已启动')
  94. // 等待一段时间让系统稳定
  95. await new Promise(resolve => setTimeout(resolve, 1000))
  96. // 测试健康检查端点
  97. const endpoints = [
  98. 'http://localhost:3002/health',
  99. 'http://localhost:3002/health/summary',
  100. 'http://localhost:3002/health/live',
  101. 'http://localhost:3002/health/ready',
  102. ]
  103. for (const endpoint of endpoints) {
  104. try {
  105. const response = await fetch(endpoint)
  106. const data = await response.json()
  107. console.log(`\n📡 ${endpoint}:`)
  108. console.log(`状态码: ${response.status}`)
  109. console.log('响应:', JSON.stringify(data, null, 2))
  110. } catch (error) {
  111. console.error(`❌ ${endpoint} 请求失败:`, error)
  112. }
  113. }
  114. } finally {
  115. // 关闭 API
  116. await healthAPI.stop()
  117. console.log('✅ 健康检查 API 已关闭')
  118. }
  119. }
  120. async function main() {
  121. try {
  122. console.log('🚀 开始生产模块健康检查测试\n')
  123. // 测试健康检查核心功能
  124. await testHealthCheck()
  125. // 测试健康检查 API
  126. await testHealthAPI()
  127. console.log('\n🎉 所有健康检查测试完成!')
  128. } catch (error) {
  129. console.error('❌ 测试失败:', error)
  130. process.exit(1)
  131. }
  132. }
  133. // 运行测试
  134. if (import.meta.url === `file://${process.argv[1]}`) {
  135. main()
  136. }