forked from Ovi/DummyJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
60 lines (45 loc) · 1.8 KB
/
index.js
File metadata and controls
60 lines (45 loc) · 1.8 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
import os from 'node:os';
import cluster from 'node:cluster';
import { createRequire } from 'node:module';
import { connectDB } from './src/db/mongoose.js';
import { log, logError } from './src/helpers/logger.js';
import { handleClusterExit, handleClusterMessage, logCounts } from './src/utils/cluster.js';
import { validateEnvVar } from './src/utils/util.js';
import { setupCRONJobs } from './src/utils/cron-jobs.js';
const require = createRequire(import.meta.url);
const { version } = require('./package.json');
const { PORT = 8888, NUM_WORKERS = 1, NODE_ENV } = process.env;
const numCPUs = os.cpus().length;
const maxWorkers = Math.min(NUM_WORKERS, numCPUs);
async function setupMasterProcess() {
try {
validateEnvVar();
await connectDB();
setupCRONJobs();
logCounts();
log(`[Master] ${process.pid} running with ${maxWorkers}/${numCPUs} workers`);
log(`[Master][${NODE_ENV}] App v${version} running at http://localhost:${PORT}`);
forkWorkers(maxWorkers);
} catch (error) {
logError(`[Master] Critical error: ${error.message}`, { error: error.stack });
process.exit(1);
}
}
function forkWorkers(numWorkers) {
for (let i = 0; i < numWorkers; i++) cluster.fork();
cluster.on('exit', (worker, code, signal) => handleClusterExit(worker, code, signal));
cluster.on('message', (worker, message) => handleClusterMessage(worker, message));
}
// Main execution block
if (cluster.isMaster) {
setupMasterProcess();
} else {
await import('./worker.js');
process.on('uncaughtException', err => {
logError(`[Worker] Error in worker ${process.pid}: ${err.message}`, { error: err.stack });
// Send the full stack trace to the master process
process.send({ type: 'error', error: err.stack });
// After handling the error, let it die naturally
process.exit(1);
});
}