-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
57 lines (45 loc) · 1.7 KB
/
server.js
File metadata and controls
57 lines (45 loc) · 1.7 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
const cluster = require("cluster")
const os = require("os")
const env = require("./src/config/env.config")
const dns = require("dns")
// Force IPv4 resolution to prevent connection timeouts with cloud databases in Node 17+
dns.setDefaultResultOrder('ipv4first')
const { verifyConnection } = require("./src/db")
const app = require("./src/app")
const PORT = env.PORT
const NUM_CPUS = os.cpus().length
async function startWorker() {
try {
await verifyConnection()
// Start background scheduler
const SchedulerService = require("./src/services/scheduler.service");
SchedulerService.start();
const SocketService = require("./src/services/socket.service");
const http = require("http");
const server = http.createServer(app);
SocketService.init(server);
server.listen(PORT, "0.0.0.0", () => {
console.log(`Worker ${process.pid} started. Server running on http://0.0.0.0:${PORT}`)
})
} catch (error) {
console.error(`Worker ${process.pid} failed to start:`, error.message)
process.exit(1)
}
}
if (cluster.isPrimary && env.NODE_ENV === "production") {
console.log(`Primary ${process.pid} is running. Spawning ${NUM_CPUS} workers...`)
// Fork workers.
for (let i = 0; i < NUM_CPUS; i++) {
cluster.fork()
}
cluster.on("exit", (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Spawning a replacement...`)
cluster.fork()
})
} else {
// Workers or Development mode (single process)
if (env.NODE_ENV !== "production") {
console.log("Running in development mode. Skipping clustering.")
}
startWorker()
}