Advertisement
Guest User

Untitled

a guest
Dec 1st, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express'),
  2.     cluster = require('cluster'),
  3.     net = require('net'),
  4.     sio = require('socket.io'),
  5.     farmhash = require('farmhash'),
  6.     bodyParser = require('body-parser'),
  7.     mysql = require('mysql'),
  8.     RateLimiter = require('limiter').RateLimiter;
  9.  
  10. const redis = require('redis').createClient;
  11. const adapter = require('socket.io-redis');
  12. const pub = redis('6379', '', {
  13.     auth_pass: ""
  14. });
  15. const sub = redis('6379', '', {
  16.     auth_pass: ""
  17. });
  18.  
  19.  
  20. const sandboxPlan = 7;
  21. const smallPlan = 15;
  22. const mediumPlan = 50;
  23. const largePlan = 125;
  24. const xLargePlan = 250;
  25.  
  26. var sandBoxLimiter = new RateLimiter(sandboxPlan, 'second', true); // fire CB immediately
  27. var smallLimiter = new RateLimiter(smallPlan, 'second', true); // fire CB immediately
  28. var mediumLimiter = new RateLimiter(mediumPlan, 'second', true); // fire CB immediately
  29. var largeLimiter = new RateLimiter(largePlan, 'second', true); // fire CB immediately
  30. var xLargeLimiter = new RateLimiter(xLargePlan, 'second', true); // fire CB immediately
  31.  
  32. let handle = require('./controllers/apicontroller.js');
  33. let track  = require('./controllers/useagecontroller.js');
  34.  
  35. var port = 8081,
  36.     num_processes = require('os').cpus().length;
  37.  
  38. var pool = mysql.createPool({
  39.     connectionLimit: 200,
  40.     host: "",
  41.     user: "na-regional",
  42.     password: "",
  43.     database: "pushthis"
  44. });
  45.  
  46. if (cluster.isMaster) {
  47.     // This stores our workers. We need to keep them to be able to reference
  48.     // them based on source IP address. It's also useful for auto-restart,
  49.     // for example.
  50.     var workers = [];
  51.  
  52.     // Helper function for spawning worker at index 'i'.
  53.     var spawn = function(i) {
  54.         workers[i] = cluster.fork();
  55.  
  56.         // Optional: Restart worker on exit
  57.         workers[i].on('exit', function(code, signal) {
  58.             console.log('respawning worker', i);
  59.             spawn(i);
  60.         });
  61.         workers[i].on('disconnect', function(worker) {
  62.             console.log(workers[i].process.pid + 'disconnected -- rip')
  63.         })
  64.  
  65.         workers[i].on('online', (worker) => {
  66.             console.log(workers[i].process.pid);
  67.         })
  68.     };
  69.  
  70.     // Spawn workers.
  71.     for (var i = 0; i < num_processes; i++) {
  72.         spawn(i);
  73.     }
  74.  
  75.     // Helper function for getting a worker index based on IP address.
  76.     // This is a hot path so it should be really fast. The way it works
  77.     // is by converting the IP address to a number by removing non numeric
  78.     // characters, then compressing it to the number of slots we have.
  79.     //
  80.     // Compared against "real" hashing (from the sticky-session code) and
  81.     // "real" IP number conversion, this function is on par in terms of
  82.     // worker index distribution only much faster.
  83.     var worker_index = function(n) {
  84.         return Math.floor(Math.random() * n)
  85.     };
  86.  
  87.     // Create the outside facing server listening on our port.
  88.     var server = net.createServer({
  89.         pauseOnConnect: true
  90.     }, function(connection) {
  91.         var worker = workers[worker_index(num_processes)];
  92.         worker.send('sticky-session:connection', connection);
  93.     }).listen(port);
  94. } else {
  95.     process.setMaxListeners(0);
  96.     // Note we don't use a port here because the master listens on it for us.
  97.     var app = new express();
  98.  
  99.     app.use(bodyParser.json({
  100.         type: 'application/json',
  101.         limit: 12000
  102.     }))
  103.  
  104.     app.use(function(req, res, next) {
  105.         res.setHeader('Access-Control-Allow-Origin', '*');
  106.         res.header("Access-Control-Allow-Credentials: true");
  107.         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  108.         next();
  109.     });
  110.  
  111.     app.post('/api', function(request, response) {
  112.         console.log('Worker ' + process.pid + ': Processing from na-regional')
  113.  
  114.         //check customers subscription
  115.         let key = request.body['key']
  116.         let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  117.  
  118.  
  119.         //grab connection from pool
  120.         pool.getConnection(function(err, connection) {
  121.             // Use the connection
  122.             connection.query(queryingString, [key], function(err, result, fields) {
  123.  
  124.                 //if no customer is returned, response send message
  125.                 if (result.length < 1 ||
  126.                     request.body['secret'] !== result[0]['private_key']) {
  127.  
  128.                     message = {
  129.                         'status': '400',
  130.                         'message': 'Bad Request',
  131.                         'message': 'The server encountered an message when processing the request. Please ensure your keys are correct.'
  132.                     };
  133.  
  134.                     return response.type('json').status(400).send(message);
  135.                 }
  136.  
  137.                 //get the user id of this customers
  138.                 var identifier = result[0]['users_app_id'];
  139.                 var customer_id = result[0]['user_id'];
  140.  
  141.                 //proceed with request..
  142.                 handle.thisRequest(request, response, io, connection,
  143.                     identifier, customer_id, app, sandBoxLimiter,
  144.                     smallLimiter, mediumLimiter, largeLimiter,
  145.                     xLargeLimiter, sandboxPlan, smallPlan,
  146.                     mediumPlan, largePlan, xLargePlan);
  147.             });
  148.             // And done with the connection.
  149.             connection.release();
  150.         });
  151.     });
  152.  
  153.     app.post('/auth', function(request, response){
  154.       console.log('Worker ' + process.pid + ': Processing from na-regional')
  155.  
  156.       //check customers subscription
  157.       let key = request.body['key']
  158.       let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  159.  
  160.  
  161.       //grab connection from pool
  162.       pool.getConnection(function(err, connection) {
  163.           // Use the connection
  164.           connection.query(queryingString, [key], function(err, result, fields) {
  165.  
  166.               //if no customer is returned, response send message
  167.               if (result.length < 1 ||
  168.                   request.body['secret'] !== result[0]['private_key']) {
  169.  
  170.                   message = {
  171.                       'status': '400',
  172.                       'message': 'Bad Request',
  173.                       'message': 'The server encountered an message when processing the request. Please ensure your keys are correct.'
  174.                   };
  175.  
  176.                   return response.type('json').status(400).send(message);
  177.               }
  178.  
  179.               //get the user id of this customers
  180.               var identifier = result[0]['users_app_id'];
  181.               var customer_id = result[0]['user_id'];
  182.  
  183.               //proceed with request..
  184.               handle.thisAuthorization(request, response, io, connection,
  185.                   identifier, customer_id, app, sandBoxLimiter,
  186.                   smallLimiter, mediumLimiter, largeLimiter,
  187.                   xLargeLimiter, sandboxPlan, smallPlan,
  188.                   mediumPlan, largePlan, xLargePlan);
  189.           });
  190.           // And done with the connection.
  191.           connection.release();
  192.       });
  193.  
  194.     });
  195.  
  196.  
  197.     app.get('*', function(request, response) {
  198.         message = {
  199.             'status': '404',
  200.             'message': request.ip + ' has been noticed and logged.',
  201.             'message': 'This is a network address, use Pushthis.io for more information.'
  202.         };
  203.  
  204.         return response.type('json').status(400).send(message);
  205.     })
  206.  
  207.  
  208.     // Don't expose our internal server to the outside.
  209.     var server = app.listen(0, 'localhost'),
  210.         io = sio(server);
  211.  
  212.     // Tell Socket.IO to use the redis adapter. By default, the redis
  213.     // server is assumed to be on localhost:6379. You don't have to
  214.     // specify them explicitly unless you want to change the
  215.     io.adapter(adapter({ pubClient: pub, subClient: sub}));
  216.  
  217.  
  218.     // Listen to messages sent from the master. Ignore everything else.
  219.     process.on('message', function(message, connection) {
  220.         if (message !== 'sticky-session:connection') {
  221.             return;
  222.         }
  223.  
  224.         // Emulate a connection event on the server by emitting the
  225.         // event with the connection the master sent us.
  226.         server.emit('connection', connection);
  227.  
  228.         connection.resume();
  229.     });
  230. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement