File size: 9,331 Bytes
75031b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env node

/**
 * 计费事件测试脚本
 *
 * 用于测试计费事件的发布和消费功能
 *
 * 使用方法:
 * node scripts/test-billing-events.js [command]
 *
 * 命令:
 *   publish      - 发布测试事件
 *   consume      - 消费事件(测试模式)
 *   info         - 查看队列状态
 *   clear        - 清空队列(危险操作)
 */

const path = require('path')
const Redis = require('ioredis')

// 加载配置
require('dotenv').config({ path: path.join(__dirname, '../.env') })

const config = {
  host: process.env.REDIS_HOST || 'localhost',
  port: parseInt(process.env.REDIS_PORT) || 6379,
  password: process.env.REDIS_PASSWORD || '',
  db: parseInt(process.env.REDIS_DB) || 0
}

const redis = new Redis(config)
const STREAM_KEY = 'billing:events'

// ========================================
// 命令实现
// ========================================

/**
 * 发布测试事件
 */
async function publishTestEvent() {
  console.log('📤 Publishing test billing event...')

  const testEvent = {
    eventId: `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    eventType: 'usage.recorded',
    timestamp: new Date().toISOString(),
    version: '1.0',
    apiKey: {
      id: 'test-key-123',
      name: 'Test API Key',
      userId: 'test-user-456'
    },
    usage: {
      model: 'claude-sonnet-4-20250514',
      inputTokens: 1500,
      outputTokens: 800,
      cacheCreateTokens: 200,
      cacheReadTokens: 100,
      ephemeral5mTokens: 150,
      ephemeral1hTokens: 50,
      totalTokens: 2600
    },
    cost: {
      total: 0.0156,
      currency: 'USD',
      breakdown: {
        input: 0.0045,
        output: 0.012,
        cacheCreate: 0.00075,
        cacheRead: 0.00003,
        ephemeral5m: 0.0005625,
        ephemeral1h: 0.0001875
      }
    },
    account: {
      id: 'test-account-789',
      type: 'claude-official'
    },
    context: {
      isLongContext: false,
      requestTimestamp: new Date().toISOString()
    }
  }

  try {
    const messageId = await redis.xadd(
      STREAM_KEY,
      'MAXLEN',
      '~',
      100000,
      '*',
      'data',
      JSON.stringify(testEvent)
    )

    console.log('✅ Event published successfully!')
    console.log(`   Message ID: ${messageId}`)
    console.log(`   Event ID: ${testEvent.eventId}`)
    console.log(`   Cost: $${testEvent.cost.total}`)
  } catch (error) {
    console.error('❌ Failed to publish event:', error.message)
    process.exit(1)
  }
}

/**
 * 消费事件(测试模式,不创建消费者组)
 */
async function consumeTestEvents() {
  console.log('📬 Consuming test events...')
  console.log('   Press Ctrl+C to stop\n')

  let isRunning = true

  process.on('SIGINT', () => {
    console.log('\n⏹️  Stopping consumer...')
    isRunning = false
  })

  let lastId = '0' // 从头开始

  while (isRunning) {
    try {
      // 使用 XREAD 而不是 XREADGROUP(测试模式)
      const messages = await redis.xread('BLOCK', 5000, 'COUNT', 10, 'STREAMS', STREAM_KEY, lastId)

      if (!messages || messages.length === 0) {
        continue
      }

      const [streamKey, entries] = messages[0]
      console.log(`📬 Received ${entries.length} messages from ${streamKey}\n`)

      for (const [messageId, fields] of entries) {
        try {
          const data = {}
          for (let i = 0; i < fields.length; i += 2) {
            data[fields[i]] = fields[i + 1]
          }

          const event = JSON.parse(data.data)

          console.log(`📊 Event: ${event.eventId}`)
          console.log(`   API Key: ${event.apiKey.name} (${event.apiKey.id})`)
          console.log(`   Model: ${event.usage.model}`)
          console.log(`   Tokens: ${event.usage.totalTokens}`)
          console.log(`   Cost: $${event.cost.total.toFixed(6)}`)
          console.log(`   Timestamp: ${event.timestamp}`)
          console.log('')

          lastId = messageId // 更新位置
        } catch (parseError) {
          console.error(`❌ Failed to parse message ${messageId}:`, parseError.message)
        }
      }
    } catch (error) {
      if (isRunning) {
        console.error('❌ Error consuming messages:', error.message)
        await new Promise((resolve) => setTimeout(resolve, 5000))
      }
    }
  }

  console.log('👋 Consumer stopped')
}

/**
 * 查看队列状态
 */
async function showQueueInfo() {
  console.log('📊 Queue Information\n')

  try {
    // Stream 长度
    const length = await redis.xlen(STREAM_KEY)
    console.log(`Stream: ${STREAM_KEY}`)
    console.log(`Length: ${length} messages\n`)

    if (length === 0) {
      console.log('ℹ️  Queue is empty')
      return
    }

    // Stream 详细信息
    const info = await redis.xinfo('STREAM', STREAM_KEY)
    const infoObj = {}
    for (let i = 0; i < info.length; i += 2) {
      infoObj[info[i]] = info[i + 1]
    }

    console.log('Stream Details:')
    console.log(`  First Entry ID: ${infoObj['first-entry'] ? infoObj['first-entry'][0] : 'N/A'}`)
    console.log(`  Last Entry ID: ${infoObj['last-entry'] ? infoObj['last-entry'][0] : 'N/A'}`)
    console.log(`  Consumer Groups: ${infoObj.groups || 0}\n`)

    // 消费者组信息
    if (infoObj.groups > 0) {
      console.log('Consumer Groups:')
      const groups = await redis.xinfo('GROUPS', STREAM_KEY)

      for (let i = 0; i < groups.length; i++) {
        const group = groups[i]
        const groupObj = {}
        for (let j = 0; j < group.length; j += 2) {
          groupObj[group[j]] = group[j + 1]
        }

        console.log(`\n  Group: ${groupObj.name}`)
        console.log(`    Consumers: ${groupObj.consumers}`)
        console.log(`    Pending: ${groupObj.pending}`)
        console.log(`    Last Delivered ID: ${groupObj['last-delivered-id']}`)

        // 消费者详情
        if (groupObj.consumers > 0) {
          const consumers = await redis.xinfo('CONSUMERS', STREAM_KEY, groupObj.name)
          console.log('    Consumer Details:')

          for (let k = 0; k < consumers.length; k++) {
            const consumer = consumers[k]
            const consumerObj = {}
            for (let l = 0; l < consumer.length; l += 2) {
              consumerObj[consumer[l]] = consumer[l + 1]
            }

            console.log(`      - ${consumerObj.name}`)
            console.log(`        Pending: ${consumerObj.pending}`)
            console.log(`        Idle: ${Math.round(consumerObj.idle / 1000)}s`)
          }
        }
      }
    }

    // 最新 5 条消息
    console.log('\n📬 Latest 5 Messages:')
    const latest = await redis.xrevrange(STREAM_KEY, '+', '-', 'COUNT', 5)

    if (latest.length === 0) {
      console.log('  No messages')
    } else {
      for (const [messageId, fields] of latest) {
        const data = {}
        for (let i = 0; i < fields.length; i += 2) {
          data[fields[i]] = fields[i + 1]
        }

        try {
          const event = JSON.parse(data.data)
          console.log(`\n  ${messageId}`)
          console.log(`    Event ID: ${event.eventId}`)
          console.log(`    Model: ${event.usage.model}`)
          console.log(`    Cost: $${event.cost.total.toFixed(6)}`)
          console.log(`    Time: ${event.timestamp}`)
        } catch (e) {
          console.log(`\n  ${messageId} (Parse Error)`)
        }
      }
    }
  } catch (error) {
    console.error('❌ Failed to get queue info:', error.message)
    process.exit(1)
  }
}

/**
 * 清空队列(危险操作)
 */
async function clearQueue() {
  console.log('⚠️  WARNING: This will delete all messages in the queue!')
  console.log(`   Stream: ${STREAM_KEY}`)

  // 简单的确认机制
  const readline = require('readline')
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })

  rl.question('Type "yes" to confirm: ', async (answer) => {
    if (answer.toLowerCase() === 'yes') {
      try {
        await redis.del(STREAM_KEY)
        console.log('✅ Queue cleared successfully')
      } catch (error) {
        console.error('❌ Failed to clear queue:', error.message)
      }
    } else {
      console.log('❌ Operation cancelled')
    }
    rl.close()
    redis.quit()
  })
}

// ========================================
// CLI 处理
// ========================================

async function main() {
  const command = process.argv[2] || 'info'

  console.log('🔧 Billing Events Test Tool\n')

  try {
    switch (command) {
      case 'publish':
        await publishTestEvent()
        break

      case 'consume':
        await consumeTestEvents()
        break

      case 'info':
        await showQueueInfo()
        break

      case 'clear':
        await clearQueue()
        return // clearQueue 会自己关闭连接

      default:
        console.error(`❌ Unknown command: ${command}`)
        console.log('\nAvailable commands:')
        console.log('  publish  - Publish a test event')
        console.log('  consume  - Consume events (test mode)')
        console.log('  info     - Show queue status')
        console.log('  clear    - Clear the queue (dangerous)')
        process.exit(1)
    }

    await redis.quit()
  } catch (error) {
    console.error('💥 Fatal error:', error)
    await redis.quit()
    process.exit(1)
  }
}

main()