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'),
- farmhash = require('farmhash'),
- bodyParser = require('body-parser'),
- mysql = require('mysql'),
- RateLimiter = require('limiter').RateLimiter;
- const redis = require('redis').createClient;
- const adapter = require('socket.io-redis');
- const pub = redis('6379', '', {
- auth_pass: ""
- });
- const sub = redis('6379', '', {
- auth_pass: ""
- });
- const sandboxPlan = 7;
- const smallPlan = 15;
- const mediumPlan = 50;
- const largePlan = 125;
- const xLargePlan = 250;
- var sandBoxLimiter = new RateLimiter(sandboxPlan, 'second', true); // fire CB immediately
- var smallLimiter = new RateLimiter(smallPlan, 'second', true); // fire CB immediately
- var mediumLimiter = new RateLimiter(mediumPlan, 'second', true); // fire CB immediately
- var largeLimiter = new RateLimiter(largePlan, 'second', true); // fire CB immediately
- var xLargeLimiter = new RateLimiter(xLargePlan, 'second', true); // fire CB immediately
- let handle = require('./controllers/apicontroller.js');
- let track = require('./controllers/useagecontroller.js');
- var port = 8081,
- num_processes = require('os').cpus().length;
- var pool = mysql.createPool({
- connectionLimit: 200,
- host: "",
- user: "na-regional",
- password: "",
- database: "pushthis"
- });
- 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);
- });
- workers[i].on('disconnect', function(worker) {
- console.log(workers[i].process.pid + 'disconnected -- rip')
- })
- workers[i].on('online', (worker) => {
- console.log(workers[i].process.pid);
- })
- };
- // 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(n) {
- return Math.floor(Math.random() * n)
- };
- // Create the outside facing server listening on our port.
- var server = net.createServer({
- pauseOnConnect: true
- }, function(connection) {
- var worker = workers[worker_index(num_processes)];
- worker.send('sticky-session:connection', connection);
- }).listen(port);
- } else {
- process.setMaxListeners(0);
- // Note we don't use a port here because the master listens on it for us.
- var app = new express();
- app.use(bodyParser.json({
- type: 'application/json',
- limit: 12000
- }))
- 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', function(request, response) {
- console.log('Worker ' + process.pid + ': Processing from na-regional')
- //check customers subscription
- let key = request.body['key']
- let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
- //grab connection from pool
- pool.getConnection(function(err, connection) {
- // Use the connection
- connection.query(queryingString, [key], function(err, result, fields) {
- //if no customer is returned, response send message
- if (result.length < 1 ||
- request.body['secret'] !== result[0]['private_key']) {
- message = {
- 'status': '400',
- 'message': 'Bad Request',
- 'message': 'The server encountered an message when processing the request. Please ensure your keys are correct.'
- };
- return response.type('json').status(400).send(message);
- }
- //get the user id of this customers
- var identifier = result[0]['users_app_id'];
- var customer_id = result[0]['user_id'];
- //proceed with request..
- handle.thisRequest(request, response, io, connection,
- identifier, customer_id, app, sandBoxLimiter,
- smallLimiter, mediumLimiter, largeLimiter,
- xLargeLimiter, sandboxPlan, smallPlan,
- mediumPlan, largePlan, xLargePlan);
- });
- // And done with the connection.
- connection.release();
- });
- });
- app.post('/auth', function(request, response){
- console.log('Worker ' + process.pid + ': Processing from na-regional')
- //check customers subscription
- let key = request.body['key']
- let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
- //grab connection from pool
- pool.getConnection(function(err, connection) {
- // Use the connection
- connection.query(queryingString, [key], function(err, result, fields) {
- //if no customer is returned, response send message
- if (result.length < 1 ||
- request.body['secret'] !== result[0]['private_key']) {
- message = {
- 'status': '400',
- 'message': 'Bad Request',
- 'message': 'The server encountered an message when processing the request. Please ensure your keys are correct.'
- };
- return response.type('json').status(400).send(message);
- }
- //get the user id of this customers
- var identifier = result[0]['users_app_id'];
- var customer_id = result[0]['user_id'];
- //proceed with request..
- handle.thisAuthorization(request, response, io, connection,
- identifier, customer_id, app, sandBoxLimiter,
- smallLimiter, mediumLimiter, largeLimiter,
- xLargeLimiter, sandboxPlan, smallPlan,
- mediumPlan, largePlan, xLargePlan);
- });
- // And done with the connection.
- connection.release();
- });
- });
- app.get('*', function(request, response) {
- message = {
- 'status': '404',
- 'message': request.ip + ' has been noticed and logged.',
- 'message': 'This is a network address, use Pushthis.io for more information.'
- };
- return response.type('json').status(400).send(message);
- })
- // 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 the
- io.adapter(adapter({ pubClient: pub, subClient: sub}));
- // 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);
- connection.resume();
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement