Advertisement
Guest User

Untitled

a guest
Nov 12th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.71 KB | None | 0 0
  1. var express = require('express'),
  2. cluster = require('cluster'),
  3. net = require('net'),
  4. sio = require('socket.io'),
  5. sio_redis = require('socket.io-redis'),
  6. farmhash = require('farmhash'),
  7. bodyParser = require('body-parser'),
  8. mysql = require('mysql');
  9. let handle = require('./controllers/apicontroller.js');
  10.  
  11. var port = 8081,
  12. num_processes = require('os').cpus().length;
  13.  
  14. var pool = mysql.createPool({
  15. connectionLimit : 150,
  16. host: "",
  17. user: "",
  18. password: "",
  19. database: ""
  20. });
  21.  
  22. if (cluster.isMaster) {
  23. // This stores our workers. We need to keep them to be able to reference
  24. // them based on source IP address. It's also useful for auto-restart,
  25. // for example.
  26. var workers = [];
  27.  
  28. // Helper function for spawning worker at index 'i'.
  29. var spawn = function(i) {
  30. workers[i] = cluster.fork();
  31.  
  32. // Optional: Restart worker on exit
  33. workers[i].on('exit', function(code, signal) {
  34. console.log('respawning worker', i);
  35. spawn(i);
  36. });
  37. };
  38.  
  39. // Spawn workers.
  40. for (var i = 0; i < num_processes; i++) {
  41. spawn(i);
  42. }
  43.  
  44. // Helper function for getting a worker index based on IP address.
  45. // This is a hot path so it should be really fast. The way it works
  46. // is by converting the IP address to a number by removing non numeric
  47. // characters, then compressing it to the number of slots we have.
  48. //
  49. // Compared against "real" hashing (from the sticky-session code) and
  50. // "real" IP number conversion, this function is on par in terms of
  51. // worker index distribution only much faster.
  52. var worker_index = function(ip, len) {
  53. return farmhash.fingerprint32(ip[i]) % len; // Farmhash is the fastest and works with IPv6, too
  54. };
  55.  
  56. // Create the outside facing server listening on our port.
  57. var server = net.createServer({ pauseOnConnect: true }, function(connection) {
  58. // We received a connection and need to pass it to the appropriate
  59. // worker. Get the worker for this connection's source IP and pass
  60. // it the connection.
  61. var worker = workers[worker_index(connection.remoteAddress, num_processes)];
  62. worker.send('sticky-session:connection', connection);
  63. }).listen(port);
  64. } else {
  65. var app = new express();
  66.  
  67. process.setMaxListeners(0);
  68.  
  69. app.use(bodyParser.json());
  70.  
  71. app.use(function(req, res, next) {
  72. res.setHeader('Access-Control-Allow-Origin', '*');
  73. res.header("Access-Control-Allow-Credentials: true");
  74. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  75. next();
  76. });
  77.  
  78. app.post('/api/v1/relay', function(request, response){
  79. //check if coming from Laravel --
  80. if(request.body['channel'] == 'lf0DKd0159fD##'){
  81. goingTo.updateMyApps(request, response, io);
  82. }else{
  83.  
  84. console.log('Worker ' + cluster.worker.id + ': Processing from na-regional')
  85.  
  86. //check customers subscription
  87. let key = request.body['public_key']
  88. let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  89.  
  90. pool.getConnection(function(err, connection) {
  91. // Use the connection
  92. connection.query(queryingString, [key], function(err, result, fields) {
  93. if (err) throw err;
  94.  
  95. if(request.body['public_key'] !== result[0]['public_key'] ||
  96. request.body['private_key'] !== result[0]['private_key'] ||
  97. !request.body['channel'] || !request.body['event']){
  98. //log this to a file later get origin for tracking
  99. console.log('bad request from: ');
  100. return response.sendStatus(400);
  101. }
  102. //get the user id of this customers
  103. var identifier = result[0]['users_app_id'];
  104. var customer_id = result[0]['user_id'];
  105. handle.thisRequest(request, response, io, connection,
  106. identifier, customer_id, app);
  107. });
  108. // And done with the connection.
  109. connection.release();
  110. });
  111. }
  112. });
  113.  
  114. //for load testing
  115. app.get('/loaderio-721652caf56e83ad1cf084c6984fa5c4/', function(request, response){
  116. response.send('loaderio-721652caf56e83ad1cf084c6984fa5c4');
  117. });
  118.  
  119. // Don't expose our internal server to the outside.
  120. var server = app.listen(0, 'localhost'),
  121. io = sio(server);
  122.  
  123. // Tell Socket.IO to use the redis adapter. By default, the redis
  124. // server is assumed to be on localhost:6379. You don't have to
  125. // specify them explicitly unless you want to change them.
  126. io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
  127.  
  128. // Here you might use Socket.IO middleware for authorization etc.
  129.  
  130. // Listen to messages sent from the master. Ignore everything else.
  131. process.on('message', function(message, connection) {
  132. if (message !== 'sticky-session:connection') {
  133. return;
  134. }
  135.  
  136. // Emulate a connection event on the server by emitting the
  137. // event with the connection the master sent us.
  138. server.emit('connection', connection);
  139. io.sockets.on('connection', function (socket) {
  140. var origin = socket.request.headers['origin'];
  141. var status= "connection";
  142. console.log('A client has connected to ' + process.id + ' From: ' + origin);
  143. io.emit('demo-2', 'hello');
  144. //track.customersConnections(origin, status);
  145.  
  146. socket.once('disconnect', function () {
  147. var origin = socket.request.headers['origin'];
  148. var status = "disconnection";
  149. console.log('A client has disconnected from ' + process.id + '. From: ' + origin);
  150. //track.customersConnections(origin, status);
  151. });
  152. });
  153. connection.resume();
  154. });
  155. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement