-
-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathupdates-worker.js
More file actions
300 lines (250 loc) · 9 KB
/
updates-worker.js
File metadata and controls
300 lines (250 loc) · 9 KB
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
require('dotenv').config({ path: './.env' })
const fs = require('fs')
const { Telegraf } = require('telegraf')
const { createRedisClient } = require('./utils/redis')
const { db } = require('./database')
const { stats } = require('./middlewares')
// Cache config at startup
let cachedConfig = {}
try {
if (fs.existsSync('./config.json')) {
cachedConfig = JSON.parse(fs.readFileSync('./config.json', 'utf8'))
}
} catch (error) {
console.error('Error loading config:', error.message)
}
const logWithTimestamp = (message) => {
const workerId = process.env.pm_id || process.pid
console.log(`[${new Date().toISOString()}] [WORKER-${workerId}] ${message}`)
}
const errorWithTimestamp = (message, ...args) => {
const workerId = process.env.pm_id || process.pid
console.error(`[${new Date().toISOString()}] [WORKER-${workerId}] ${message}`, ...args)
}
class TelegramProcessor {
constructor () {
this.bot = new Telegraf(process.env.BOT_TOKEN, {
handlerTimeout: 30000
})
// Main Redis connection for queue and stats
this.redis = createRedisClient({
retryDelayOnFailover: 100,
maxRetriesPerRequest: 3
})
// Separate connection for TDLib pub/sub
this.tdlibRedis = createRedisClient({
retryDelayOnFailover: 100,
maxRetriesPerRequest: 3
})
this.isProcessing = false
this.processedCount = 0
this.errorCount = 0
this.concurrentLimit = 50 // Process up to 50 updates concurrently per worker
this.activePromises = new Set() // Track active processing promises
this.workerId = process.env.WORKER_INDEX || process.env.pm_id || process.pid
this.workerIndex = process.env.WORKER_INDEX !== undefined ? parseInt(process.env.WORKER_INDEX) : (this.workerId % 3)
this.queueName = `telegram:updates:worker:${this.workerIndex}`
this.pendingTDLibRequests = new Map() // Track pending TDLib requests
this.setupRedisEvents()
this.setupBot()
}
setupRedisEvents () {
this.redis.on('connect', () => {
logWithTimestamp('Connected to Redis')
})
this.redis.on('error', (error) => {
errorWithTimestamp('Redis error:', error.message)
})
// Setup TDLib response handler once
this.tdlibRedis.on('message', (channel, message) => {
if (channel === 'tdlib:responses') {
try {
const response = JSON.parse(message)
const pending = this.pendingTDLibRequests.get(response.id)
if (pending) {
this.pendingTDLibRequests.delete(response.id)
clearTimeout(pending.timeout)
if (response.error) {
pending.reject(new Error(response.error))
} else {
pending.resolve(response.result)
}
}
} catch (error) {
// Ignore parse errors
}
}
})
}
createTDLibProxy () {
// Create proxy that sends TDLib requests through Redis
return new Proxy({}, {
get: (target, prop) => {
return (...args) => {
return new Promise((resolve, reject) => {
const requestId = `${this.workerId}-${Date.now()}-${Math.random()}`
// Send request through Redis
const request = {
id: requestId,
method: prop,
args: args
}
// Set timeout
const timeout = setTimeout(() => {
this.pendingTDLibRequests.delete(requestId)
reject(new Error(`TDLib ${prop} timeout`))
}, 5000)
// Store pending request
this.pendingTDLibRequests.set(requestId, { resolve, reject, timeout })
// Publish request
this.redis.publish('tdlib:requests', JSON.stringify(request))
})
}
}
})
}
setupBot () {
// Idempotent boot-time seed of the quote counter. $setOnInsert is a no-op
// once the document exists, so concurrent workers racing here is safe.
db.ready.then(() =>
db.Counter.findOneAndUpdate(
{ _id: 'quote' },
{ $setOnInsert: { seq: 0 } },
{ upsert: true }
)
).catch(err => {
errorWithTimestamp('[boot] failed to seed Counter{_id:quote}', err.message || err)
})
// Set up database and config context
this.bot.use(async (ctx, next) => {
ctx.db = db
ctx.config = cachedConfig
return next()
})
// TDLib proxy through Redis IPC (like old architecture)
this.bot.use(async (ctx, next) => {
ctx.tdlib = this.createTDLibProxy()
return next()
})
// Add stats middleware
this.bot.use(stats.middleware())
// Add main handler
const handler = require('./handler')
this.bot.use(handler)
// Error handling
this.bot.catch((err, ctx) => {
this.errorCount++
errorWithTimestamp('Bot error:', err.message)
})
}
async processUpdate (updateData) {
try {
const update = JSON.parse(updateData)
// Add processing timestamp
update._processor_started = Date.now()
// Process through bot
await this.bot.handleUpdate(update)
this.processedCount++
// Update global processed counter
await this.redis.incr('telegram:processed_count')
// Don't log each update - only batch stats
} catch (error) {
this.errorCount++
errorWithTimestamp('Error processing update:', error.message)
// Track error globally
await this.redis.incr('telegram:error_count')
}
}
async startProcessing () {
if (this.isProcessing) {
return
}
this.isProcessing = true
logWithTimestamp(`Starting concurrent processing (limit: ${this.concurrentLimit})...`)
while (this.isProcessing) {
try {
// Only get new update if we have capacity
if (this.activePromises.size < this.concurrentLimit) {
const result = await this.redis.brpop(this.queueName, 1)
if (result && result[1]) {
// Start processing concurrently (don't await)
const processPromise = this.processUpdate(result[1])
.then(() => {
this.activePromises.delete(processPromise)
})
.catch((error) => {
this.activePromises.delete(processPromise)
errorWithTimestamp('Concurrent processing error:', error.message)
})
this.activePromises.add(processPromise)
}
} else {
// Wait for at least one promise to complete
await Promise.race(this.activePromises)
}
} catch (error) {
errorWithTimestamp('Processing loop error:', error.message)
await new Promise(resolve => setTimeout(resolve, 100))
}
}
// Wait for all active promises to complete before stopping
if (this.activePromises.size > 0) {
logWithTimestamp(`Waiting for ${this.activePromises.size} active processes to complete...`)
await Promise.allSettled(this.activePromises)
}
}
async start () {
try {
// Wait for database to be ready before processing
logWithTimestamp('Waiting for MongoDB connection...')
await db.ready
logWithTimestamp('MongoDB connected')
await this.redis.connect()
await this.tdlibRedis.connect()
// Subscribe to TDLib responses once after connection
await this.tdlibRedis.subscribe('tdlib:responses')
logWithTimestamp(`Starting Telegram processor (Worker ${this.workerId}[${this.workerIndex}] -> ${this.queueName})...`)
// Start processing loop
this.startProcessing()
// Worker stats every 10 seconds
setInterval(async () => {
try {
const queueSize = await this.redis.llen(this.queueName)
const totalProcessed = await this.redis.get('telegram:processed_count') || 0
const totalErrors = await this.redis.get('telegram:error_count') || 0
const activeCount = this.activePromises.size
logWithTimestamp(`⚡ [${this.workerIndex}] | Queue: ${queueSize} | Processed: ${totalProcessed} | Errors: ${totalErrors} | Active: ${activeCount}/${this.concurrentLimit}`)
} catch (error) {
errorWithTimestamp('Stats error:', error.message)
}
}, 10000) // Every 10 seconds
logWithTimestamp('Processor started successfully')
} catch (error) {
errorWithTimestamp('Failed to start processor:', error.message)
process.exit(1)
}
}
async stop () {
logWithTimestamp('Stopping processor...')
this.isProcessing = false
await this.redis.quit()
await this.tdlibRedis.quit()
logWithTimestamp('Processor stopped')
}
}
// Create and start processor
const processor = new TelegramProcessor()
// Graceful shutdown
process.once('SIGINT', () => processor.stop())
process.once('SIGTERM', () => processor.stop())
// Start the processor
processor.start()
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
errorWithTimestamp('Uncaught Exception:', error.message)
processor.stop()
process.exit(1)
})
process.on('unhandledRejection', (reason, promise) => {
errorWithTimestamp('Unhandled Rejection at:', promise, 'reason:', reason)
})