Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express'),
- cluster = require('cluster'),
- net = require('net'),
- sio = require('socket.io'),
- sio_redis = require('socket.io-redis'),
- farmhash = require('farmhash'),
- bodyParser = require('body-parser'),
- mysql = require('mysql');
- let handle = require('./controllers/apicontroller.js');
- var port = 8081,
- num_processes = require('os').cpus().length;
- var pool = mysql.createPool({
- connectionLimit : 150,
- host: "",
- user: "",
- password: "",
- database: ""
- });
- if (cluster.isMaster) {
- // This stores our workers. We need to keep them to be able to reference
- // them based on source IP address. It's also useful for auto-restart,
- // for example.
- var workers = [];
- // Helper function for spawning worker at index 'i'.
- var spawn = function(i) {
- workers[i] = cluster.fork();
- // Optional: Restart worker on exit
- workers[i].on('exit', function(code, signal) {
- console.log('respawning worker', i);
- spawn(i);
- });
- };
- // Spawn workers.
- for (var i = 0; i < num_processes; i++) {
- spawn(i);
- }
- // Helper function for getting a worker index based on IP address.
- // This is a hot path so it should be really fast. The way it works
- // is by converting the IP address to a number by removing non numeric
- // characters, then compressing it to the number of slots we have.
- //
- // Compared against "real" hashing (from the sticky-session code) and
- // "real" IP number conversion, this function is on par in terms of
- // worker index distribution only much faster.
- var worker_index = function(ip, len) {
- return farmhash.fingerprint32(ip[i]) % len; // Farmhash is the fastest and works with IPv6, too
- };
- // Create the outside facing server listening on our port.
- var server = net.createServer({ pauseOnConnect: true }, function(connection) {
- // We received a connection and need to pass it to the appropriate
- // worker. Get the worker for this connection's source IP and pass
- // it the connection.
- var worker = workers[worker_index(connection.remoteAddress, num_processes)];
- worker.send('sticky-session:connection', connection);
- }).listen(port);
- } else {
- var app = new express();
- process.setMaxListeners(0);
- app.use(bodyParser.json());
- app.use(function(req, res, next) {
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.header("Access-Control-Allow-Credentials: true");
- res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
- next();
- });
- app.post('/api/v1/relay', function(request, response){
- //check if coming from Laravel --
- if(request.body['channel'] == 'lf0DKd0159fD##'){
- goingTo.updateMyApps(request, response, io);
- }else{
- console.log('Worker ' + cluster.worker.id + ': Processing from na-regional')
- //check customers subscription
- let key = request.body['public_key']
- let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
- pool.getConnection(function(err, connection) {
- // Use the connection
- connection.query(queryingString, [key], function(err, result, fields) {
- if (err) throw err;
- if(request.body['public_key'] !== result[0]['public_key'] ||
- request.body['private_key'] !== result[0]['private_key'] ||
- !request.body['channel'] || !request.body['event']){
- //log this to a file later get origin for tracking
- console.log('bad request from: ');
- return response.sendStatus(400);
- }
- //get the user id of this customers
- var identifier = result[0]['users_app_id'];
- var customer_id = result[0]['user_id'];
- handle.thisRequest(request, response, io, connection,
- identifier, customer_id, app);
- });
- // And done with the connection.
- connection.release();
- });
- }
- });
- //for load testing
- app.get('/loaderio-721652caf56e83ad1cf084c6984fa5c4/', function(request, response){
- response.send('loaderio-721652caf56e83ad1cf084c6984fa5c4');
- });
- // Don't expose our internal server to the outside.
- var server = app.listen(0, 'localhost'),
- io = sio(server);
- // Tell Socket.IO to use the redis adapter. By default, the redis
- // server is assumed to be on localhost:6379. You don't have to
- // specify them explicitly unless you want to change them.
- io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
- // Here you might use Socket.IO middleware for authorization etc.
- // Listen to messages sent from the master. Ignore everything else.
- process.on('message', function(message, connection) {
- if (message !== 'sticky-session:connection') {
- return;
- }
- // Emulate a connection event on the server by emitting the
- // event with the connection the master sent us.
- server.emit('connection', connection);
- io.sockets.on('connection', function (socket) {
- var origin = socket.request.headers['origin'];
- var status= "connection";
- console.log('A client has connected to ' + process.id + ' From: ' + origin);
- io.emit('demo-2', 'hello');
- //track.customersConnections(origin, status);
- socket.once('disconnect', function () {
- var origin = socket.request.headers['origin'];
- var status = "disconnection";
- console.log('A client has disconnected from ' + process.id + '. From: ' + origin);
- //track.customersConnections(origin, status);
- });
- });
- connection.resume();
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement