const tooBusyMiddleware = function (req, res, next) { if (toobusy()) { res.status(code.TOO_MANY_REQUESTS).send(tooBusyString); } else { next(); } };
app.use(function(req, res, next) { if (toobusy()) { res.status(503).send("The web application is too busy to serve this request. Please try again."); } else { next(); } });
middleware.busyCheck = function(req, res, next) { if (global.env === 'production' && (!meta.config.hasOwnProperty('eventLoopCheckEnabled') || parseInt(meta.config.eventLoopCheckEnabled, 10) === 1) && toobusy()) { res.status(503).type('text/html').sendFile(path.join(__dirname, '../../public/503.html')); } else { next(); } };
app.use(function (req, res, next) { if (toobusy()) { res.send(503, "I'm busy right now, sorry."); } else { next(); } });
this.ioServer.use((socket, next) => { try { // reject new connections if the server is too busy if (toobusy()) throw new nova.TooBusyError(); // get and parse auth data from handshake const query = socket.handshake.query; const authInputs = util_1.parseAuthHeader(query['authorization'] || query['Authorization']); const authData = this.authExecutor.authenticator.decode(authInputs); const requestor = { ip: socket.handshake.address, auth: authData }; // run authentication executor and mark socket as authenticated this.authExecutor.execute({ authenticator: this.context.authenticator }, requestor) .then((socketOwnerId) => { socket.join(socketOwnerId, function () { socket[SocketListener_1.symRequestorInfo] = requestor; next(); }); }) .catch((error) => { this.emit(ERROR_EVENT, error); next(error); }); } catch (error) { this.emit(ERROR_EVENT, error); next(error); } });
app.use(function(req, res, next) { if (toobusy()) { res.send(503, "The server is busy right now, please try your request again."); } else { next(); } });
return function expressToobusy(req, res, next) { if (toobusy()) { res.status(503).send("Server is too busy. Please, try again later."); } else { next(); } }
function handleRequest (log, path, referer, limit, origin, maxSize, validator, filter, mapper, forwarder, request, response) { var requestPath, remoteAddress, state; logRequest(log, request); if (toobusy()) { return fail(log, request, response, 503, 'Server too busy'); } requestPath = getRequestPath(request); remoteAddress = getRemoteAddress(request); if (!checkRequest(log, path, referer, limit, requestPath, remoteAddress, request, response)) { return; } response.setHeader('Access-Control-Allow-Origin', getAccessControlOrigin(request.headers, origin)); state = { body: '' }; request.on('data', receive.bind(null, log, state, maxSize, request, response)); request.on('end', send.bind(null, log, state, remoteAddress, validator, filter, mapper, forwarder, request, response)); }
app.use(function (req, res, next) { if (toobusy()) { response.errorServiceUnavailable(res); } else { next(); } });
app.use(function (req, res, next) { if (toobusy()) { res.send(503, "No chats for you! Come back - one year!!! Very busy right now, sorry."); } else { next(); } });
app.use(function(req, res, next) { if (toobusy()) { res.send(503, "Sorry, either we're too popular or someone is DDoS:ing (Server is overloaded)"); } else { next(); } });
return function (data, callback) { // check if the server is too busy if (toobusy()) { const error = new nova.TooBusyError(); setImmediate(onerror, error); if (callback) { callback(error); } return; } // build inputs and run the executor const inputs = Object.assign({}, config.defaults, data); const requestor = socket[exports.symRequestorInfo]; executor.execute(inputs, requestor) .then((result) => { if (callback) { callback(undefined); } }) .catch((error) => { setImmediate(onerror, error); if (callback) { callback(error); } }); };
middleware.busyCheck = function busyCheck(req, res, next) { if (global.env === 'production' && meta.config.eventLoopCheckEnabled && toobusy()) { analytics.increment('errors:503'); res.status(503).type('text/html').sendFile(path.join(__dirname, '../../public/503.html')); } else { setImmediate(next); } };
mockson.router.use(function(req, res, next) { if (mockson.options.toobusy && toobusy()) { res.send(503, "Opppppppppps..... I'm busy right now, sorry."); } else { next(); } });
app.use(function(req, res, next) { if (toobusy()) { log.warn("tooBusy"); res.json(503, { status: "failure", reason: "too busy"}); } else { next(); } });
server.app.use(function (req, res, next) { if (config.get('toobusy.enabled') && toobusy()) { res.statusCode = 503; return res.end('HTTP Error 503 - Server Busy') } else { next(); } });
export default (req: $Request, res: $Response, next: $Next) => { const maxLag: number | string = process.env.APP_EVENT_QUEUE_LAG_THRESHOLD || 70; toobusy.maxLag(Number(maxLag)); if (toobusy()) { next(new Error(serverMessages.tooBusy)); } else next(); };
app.use(function (aReq, aRes, aNext) { // check if we're toobusy if (toobusy()) { statusCodePage(aReq, aRes, aNext, { statusCode: 503, statusMessage: 'We\'re busy right now. Try again later.', }); } else { aNext(); } });
p.shouldThrottleRequest = function(req) { this.metrics.trackRequest(req); if (toobusy() === true) { if (this.metrics.isBadActor(req) === true || (this.options.userLag && toobusy.lag() >= this.options.userLag)) { return true; // yes, throttle user } } // do not throttle user return false; };
function onRequest(request, response) { if (toobusy()) { logger.info('Server too busy. Aborting.'); response.writeHead(503, {'Content-Type': 'text/plain'}); response.end(); return; } else { var tilerequest = new Tilerequest(request, response); tilerequest.getTile(); tilerequest = null; } }
newConnection : function (socket){ var self = this, closeSocket, handleData; if (toobusy()) { socket.destroy(); Server.debug('Server is busy, ' + _.size(this.clients) + ' connections'); this.emit('busy'); } else { socket = new classes.Client(socket, true); closeSocket = (function (socket){ return function closeSocket(){ self.closeConnection(socket); }; })(socket); handleData = (function (socket){ return function handleData(buffer){ self.handleData(socket, buffer); }; })(socket); Server.debug('(' + socket.id + ') New connection'); this.clients[socket.id] = socket; socket.on('end', closeSocket); socket.on('error', closeSocket); socket.socket.on('data', handleData); this.emit('connection', socket); } },
function onRequest(request, response) { if (toobusy()) { logger.info('Server too busy. Aborting.'); headers["Content-Type"] = "text/plain; charset=utf-8"; response.writeHead(503, headers); response.end(); return; } else { var query = url.parse(request.url, true); var params = query.query; // escape input parameters to avoid sql injections for (var key in params) { params[key] = params[key].trim().replace("%", "").replace("*", "").replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) { switch (char) { case "\0": return "\\0"; case "\x08": return "\\b"; case "\x09": return "\\t"; case "\x1a": return "\\z"; case "\n": return "\\n"; case "\r": return "\\r"; case "\"": case "'": case "\\": case "%": return "\\"+char; } }); } var requestType = query.pathname.substr(1); logger.info('Received '+requestType+' request with params '+JSON.stringify(params)); logger.trace('Connecting to database...'); pool.connect(function(err, client, done) { if (err) { logger.error('Fetching client from database pool failed: ' + err); headers["Content-Type"] = "text/plain; charset=utf-8"; response.writeHead(500, headers); response.end(); return; } // if valid request if (configuration.queries.indexOf(requestType) > -1) { var sqlquery = eval(requestType+"(params)"); if (!sqlquery) { done(); headers["Content-Type"] = "text/plain; charset=utf-8"; response.writeHead(200, headers); response.end("[]"); logger.error("Invalid parameters: "+JSON.stringify(params)); return; } client.query(sqlquery, function(err, data) { // release client back to the pool done(); if (err) { logger.warn('An error occurred during '+requestType+' request: "'+err+'" Aborting.'); headers["Content-Type"] = "text/plain; charset=utf-8"; response.writeHead(500, headers); response.end(); return; } logger.trace('Returning response...'); // parse GeoJSON database response to object if (data.rows[0] && data.rows[0].geometry) for (i=0; i<data.rows.length; i++) data.rows[i].geometry = JSON.parse(data.rows[i].geometry); if (data.rows.length == 0) data.rows = {}; headers["Content-Type"] = "application/json; charset=utf-8"; response.writeHead(200, headers); if (params.callback) response.end(params.callback+'('+JSON.stringify(data.rows)+')'); else response.end(JSON.stringify(data.rows)); logger.trace('Finished request.'); }); } else { done(); headers["Content-Type"] = "text/plain; charset=utf-8"; response.writeHead(200, headers); response.end("[]"); if (requestType != "favicon.ico") logger.error("Invalid request: "+requestType); return; } }); } }
// handles the +req+ by routing to the request to the appropriate module function requestHandler(req, res) { req.url = url.parse(req.url, true); req.url.query = req.url.query || {}; req.url.path_list = path_list(req.url.pathname); req.id = request_id(); req.start = Date.now(); var local_path = req.url.path_list[0]; logging.debug(req.id, req.method, req.url.href); toobusy.maxLag(200); if (toobusy() && !process.env.TRAVIS) { response(req, res, { status: -1, body: "Server is over capacity :/", err: "Too busy", code: 503, }); return; } if (req.method === "GET" || req.method === "HEAD") { try { switch (local_path) { case "": routes.index(req, function(result) { response(req, res, result); }); break; case "avatars": routes.avatars(req, function(result) { response(req, res, result); }); break; case "skins": routes.skins(req, function(result) { response(req, res, result); }); break; case "renders": routes.renders(req, function(result) { response(req, res, result); }); break; case "capes": routes.capes(req, function(result) { response(req, res, result); }); break; default: asset_request(req, function(result) { response(req, res, result); }); } } catch(e) { var error = JSON.stringify(req.headers) + "\n" + e.stack; response(req, res, { status: -1, body: config.server.debug_enabled ? error : "Internal Server Error", err: error, }); } } else { response(req, res, { status: -2, body: "Method Not Allowed", code: 405, }); } }