-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
73 lines (59 loc) · 2.65 KB
/
worker.js
File metadata and controls
73 lines (59 loc) · 2.65 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
/**
* Worker Entry Point
*
* Runs RabbitMQ consumers for AI analysis and alert jobs.
* Separate process from the API server — no HTTP or Socket.io.
* Communicates with the API process via Redis Pub/Sub.
*/
import env from './src/config/env.js';
import { connectDB, disconnectDB } from './src/config/db.js';
import { initRedis, disconnectRedis } from './src/config/redis.js';
import { connectRabbitMQ, disconnectRabbitMQ } from './src/config/rabbitmq.js';
import { initEmailTransporter } from './src/services/email.service.js';
import { startAnalysisWorker } from './src/workers/analysis.worker.js';
import { startAlertWorker } from './src/workers/alert.worker.js';
import { startNotificationWorker } from './src/workers/notification.worker.js';
import { startAnalyticsEventWorker } from './src/workers/analyticsEvent.worker.js';
import logger from './src/utils/logger.js';
async function startWorker() {
try {
// 1. Connect to MongoDB (workers need to read/write analysis results)
await connectDB(env.MONGO_URI);
// 2. Connect to Redis (caching, Pub/Sub publishing, distributed locks)
await initRedis(env);
// 3. Connect to RabbitMQ
await connectRabbitMQ(env.RABBITMQ_URL);
// 4. Initialize email transporter (alert worker sends emails)
initEmailTransporter();
// 5. Start consumers
await startAnalysisWorker();
await startAlertWorker();
await startNotificationWorker();
await startAnalyticsEventWorker();
logger.info('🔧 LexAI Worker started — consuming analysis + alert + notification + analytics queues');
// ─── Graceful Shutdown ────────────────────────────────────────
const shutdown = async (signal) => {
logger.info(`\n${signal} received. Shutting down worker...`);
await Promise.allSettled([
disconnectDB(),
disconnectRedis(),
disconnectRabbitMQ(),
]);
logger.info('Worker shutdown complete. 👋');
process.exit(0);
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('unhandledRejection', (reason) => {
logger.error('Worker unhandled rejection:', reason);
});
process.on('uncaughtException', (err) => {
logger.error('Worker uncaught exception:', err);
process.exit(1);
});
} catch (err) {
logger.error('Failed to start worker:', err);
process.exit(1);
}
}
startWorker();