|
| 1 | +const dotenv = require('dotenv'); |
| 2 | +const cluster =require('cluster'); |
| 3 | +const http = require('http'); |
| 4 | +const getPort = require('get-port'); // TODO: Replace with "port-finder"? |
| 5 | +const os = require('os'); |
| 6 | +const createApp = require('./src/app.js'); |
| 7 | + |
| 8 | +dotenv.config(); // Load environment vars |
| 9 | + |
| 10 | +// Load app config.ini |
| 11 | +const DEFAULT_PORT = process.env.APP_PORT || process.env.PORT || 4000; // Configure server default PORT |
| 12 | +const MAX_TIMEOUT = 30 * 60 *1000; // Configure server max hard timeout 30m |
| 13 | +const NUM_CPUS = os.cpus().length || 1; // Configure number of threads |
| 14 | + |
| 15 | +var server, app, port = null; |
| 16 | + |
| 17 | +const events = { |
| 18 | + onInit: () => { |
| 19 | + console.log(`Node.js template Private API ${process.pid} - listening on port %s`, port); |
| 20 | + |
| 21 | + if (process.emit) { |
| 22 | + process.emit('ready'); |
| 23 | + } |
| 24 | + }, |
| 25 | + onShutdown: () => { |
| 26 | + if (!app || !app.locals) { |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + app.locals.discovery.unregister() |
| 31 | + .then(() => { |
| 32 | + console.log('Service unregistred!'); |
| 33 | + process.exit(0); |
| 34 | + }) |
| 35 | + .catch(console.error); |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +if (cluster.isMaster) { |
| 40 | + console.log(`Node.js template Private API ${process.pid} - master`); |
| 41 | + |
| 42 | + for (let i = 0; i < NUM_CPUS; i++) { |
| 43 | + cluster.fork(); |
| 44 | + } |
| 45 | + |
| 46 | + cluster.on('exit', (worker, code, signal) => { |
| 47 | + console.log(`worker ${worker.process.pid} died`); |
| 48 | + }); |
| 49 | + |
| 50 | + cluster.on('disconnect', () => { |
| 51 | + console.log('worker disconnected'); |
| 52 | + }); |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Bootstrap app |
| 57 | + */ |
| 58 | +const main = async () => { |
| 59 | + const getPortOptions = { |
| 60 | + port: parseInt(DEFAULT_PORT) |
| 61 | + }; |
| 62 | + |
| 63 | + port = 4000; |
| 64 | + |
| 65 | + /* |
| 66 | + if (!port) { |
| 67 | + port = await getPort(getPortOptions); |
| 68 | + } |
| 69 | + */ |
| 70 | + |
| 71 | + app = createApp(port); |
| 72 | + server = http.createServer(app); |
| 73 | + server.setTimeout(MAX_TIMEOUT); |
| 74 | + server.listen(port, events.onInit); |
| 75 | +}; |
| 76 | + |
| 77 | +process.on('SIGHUP', events.onShutdown); |
| 78 | +process.on('SIGINT', events.onShutdown); |
| 79 | +process.on('SIGTERM', events.onShutdown); |
| 80 | + |
| 81 | +if (!cluster.isMaster) { |
| 82 | + main(); |
| 83 | +} |
0 commit comments