Merge branch 'hotfix/21.56.9' into master
[gitter.git] / server / web / middlewares / pending-request.js
blob2875309345cd5e4ca8b7114b6b3484f6de2f634a
1 'use strict';
3 var onHeaders = require('on-headers');
4 var env = require('gitter-web-env');
5 var logger = env.logger;
6 var config = env.config;
8 var statsd = env.createStatsClient({
9 prefix: config.get('stats:statsd:prefix'),
10 includeNodeVersionTags: true
11 });
13 var TIMEOUT = 60 * 1000;
15 function getRouteTag(req) {
16 // This is put here by the identify-route middleware
17 if (req.routeIdentifier) {
18 return req.routeIdentifier;
21 // Fallback to the old method...
22 var path = req.route && req.route.path;
23 if (!path) {
24 return;
27 path = path
28 .replace(/(\.:format\?|\([^\)]*\))/g, '')
29 .replace(/:/g, '_')
30 .replace(/[^\w\-\/]/g, '');
32 return path;
35 function getUserId(req) {
36 var user = req.user;
37 if (!user) return;
39 return user.id || user._id; // Learn objects or not
42 function getClientId(req) {
43 var authInfo = req.authInfo;
44 if (!authInfo) return;
45 var client = authInfo.client;
46 if (!client) return;
47 return client.id || client._id;
50 module.exports = function(req, res, next) {
51 var timeout;
53 function reportDroppedRequest() {
54 var userId = getUserId(req);
55 var clientId = getClientId(req);
56 var routeTag = getRouteTag(req);
57 var method = req.method;
59 logger.warn('HTTP request still pending after ' + TIMEOUT + 'ms', {
60 routeIdentifier: routeTag,
61 userId: userId,
62 clientId: clientId,
63 method: method,
64 path: req.originalUrl,
65 body: req.body
66 });
68 var tags = ['method:' + method];
69 if (routeTag) {
70 tags.push('route:' + routeTag);
73 statsd.increment('http.request.pending', 1, tags);
76 function clearDroppedRequestTimeout() {
77 clearTimeout(timeout);
80 timeout = setTimeout(reportDroppedRequest, TIMEOUT);
82 onHeaders(res, clearDroppedRequestTimeout);
83 next();