2020-02-20 18:48:32 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const EVENT_VERSION = '1';
|
2020-02-26 20:24:46 +08:00
|
|
|
const MAX_LENGTH = 100;
|
2020-02-20 18:48:32 +08:00
|
|
|
|
|
|
|
function pubSubMetrics (pubSubMetricsBackend) {
|
|
|
|
if (!pubSubMetricsBackend.isEnabled()) {
|
2020-04-27 17:41:37 +08:00
|
|
|
return function pubSubMetricsDisabledMiddleware (req, res, next) {
|
|
|
|
next();
|
|
|
|
};
|
2020-02-20 18:48:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return function pubSubMetricsMiddleware (req, res, next) {
|
2020-04-27 17:41:37 +08:00
|
|
|
res.on('finish', () => {
|
|
|
|
const { event, attributes } = getEventData(req, res);
|
2020-02-20 18:48:32 +08:00
|
|
|
|
2020-04-27 17:41:37 +08:00
|
|
|
if (event) {
|
|
|
|
pubSubMetricsBackend.sendEvent(event, attributes);
|
|
|
|
}
|
|
|
|
});
|
2020-02-20 18:48:32 +08:00
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function getEventData (req, res) {
|
2020-02-26 20:24:46 +08:00
|
|
|
const event = normalizedField(req.get('Carto-Event'));
|
|
|
|
const eventSource = normalizedField(req.get('Carto-Event-Source'));
|
|
|
|
const eventGroupId = normalizedField(req.get('Carto-Event-Group-Id'));
|
2020-02-20 18:48:32 +08:00
|
|
|
|
|
|
|
if (!event || !eventSource) {
|
2020-04-27 16:58:37 +08:00
|
|
|
return { event: undefined, attributes: undefined };
|
2020-02-20 18:48:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const attributes = {
|
|
|
|
event_source: eventSource,
|
|
|
|
user_id: res.locals.userId,
|
|
|
|
response_code: res.statusCode.toString(),
|
|
|
|
source_domain: req.hostname,
|
|
|
|
event_time: new Date().toISOString(),
|
|
|
|
event_version: EVENT_VERSION
|
|
|
|
};
|
|
|
|
|
|
|
|
if (eventGroupId) {
|
|
|
|
attributes.event_group_id = eventGroupId;
|
|
|
|
}
|
|
|
|
|
2020-03-10 18:40:01 +08:00
|
|
|
const responseTime = getResponseTime(res);
|
|
|
|
|
|
|
|
if (responseTime) {
|
|
|
|
attributes.response_time = responseTime.toString();
|
|
|
|
}
|
|
|
|
|
2020-02-20 18:48:32 +08:00
|
|
|
return { event, attributes };
|
|
|
|
}
|
|
|
|
|
2020-02-26 20:24:46 +08:00
|
|
|
function normalizedField (field) {
|
2020-02-27 00:41:41 +08:00
|
|
|
if (!field) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2020-02-27 00:44:53 +08:00
|
|
|
|
2020-02-26 21:50:41 +08:00
|
|
|
return field.toString().trim().substr(0, MAX_LENGTH);
|
2020-02-26 20:24:46 +08:00
|
|
|
}
|
|
|
|
|
2020-03-10 18:40:01 +08:00
|
|
|
function getResponseTime (res) {
|
|
|
|
const profiler = res.get('X-Tiler-Profiler');
|
|
|
|
let stats;
|
|
|
|
|
|
|
|
try {
|
|
|
|
stats = JSON.parse(profiler);
|
|
|
|
} catch (e) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
return stats.total;
|
|
|
|
}
|
|
|
|
|
2020-02-20 18:48:32 +08:00
|
|
|
module.exports = pubSubMetrics;
|