2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-10-07 16:01:18 +08:00
|
|
|
const Profiler = require('../../stats/profiler-proxy');
|
2017-10-05 23:06:31 +08:00
|
|
|
const debug = require('debug')('windshaft:cartodb:stats');
|
2017-10-08 01:02:26 +08:00
|
|
|
const onHeaders = require('on-headers');
|
2017-10-05 23:06:31 +08:00
|
|
|
|
2018-03-02 01:12:07 +08:00
|
|
|
module.exports = function stats (options) {
|
2017-10-05 23:06:31 +08:00
|
|
|
const { enabled = true, statsClient } = options;
|
|
|
|
|
2018-03-02 01:12:07 +08:00
|
|
|
return function statsMiddleware (req, res, next) {
|
2017-10-05 23:06:31 +08:00
|
|
|
req.profiler = new Profiler({
|
|
|
|
statsd_client: statsClient,
|
|
|
|
profile: enabled
|
|
|
|
});
|
|
|
|
|
2017-10-08 01:02:26 +08:00
|
|
|
onHeaders(res, () => res.set('X-Tiler-Profiler', req.profiler.toJSONString()));
|
2017-10-05 23:06:31 +08:00
|
|
|
|
2017-10-08 01:02:26 +08:00
|
|
|
res.on('finish', () => {
|
|
|
|
try {
|
|
|
|
// May throw due to dns, see: http://github.com/CartoDB/Windshaft/issues/166
|
|
|
|
req.profiler.sendStats();
|
|
|
|
} catch (err) {
|
2019-10-22 01:07:24 +08:00
|
|
|
debug('error sending profiling stats: ' + err);
|
2017-10-08 01:02:26 +08:00
|
|
|
}
|
2017-10-05 23:06:31 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
2017-10-08 01:16:15 +08:00
|
|
|
};
|