'use strict';

const EVENT_VERSION = '1';
const MAX_LENGTH = 100;

function pubSubMetrics (pubSubMetricsBackend) {
    if (!pubSubMetricsBackend.isEnabled()) {
        return function pubSubMetricsDisabledMiddleware (req, res, next) { next(); };
    }

    return function pubSubMetricsMiddleware (req, res, next) {
        const data = getEventData(req, res);

        if (data.event) {
            pubSubMetricsBackend.sendEvent(data.event, data.attributes);
        }

        return next();
    };
}

function getEventData (req, res) {
    const event = normalizedField(req.get('Carto-Event'));
    const eventSource = normalizedField(req.get('Carto-Event-Source'));
    const eventGroupId = normalizedField(req.get('Carto-Event-Group-Id'));

    if (!event || !eventSource) {
        return [undefined, undefined];
    }

    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;
    }

    return { event, attributes };
}

function normalizedField (field) {
    if (!field) {
        return undefined;
    }

    return field.toString().trim().substr(0, MAX_LENGTH);
}

module.exports = pubSubMetrics;

@@ -1167,32 +1167,171 @@
 GroupId;%0A    %7D%0A%0A
+    const responseTime = getResponseTime(res);%0A%0A    if (responseTime) %7B%0A        attributes.response_time = responseTime.toString();%0A    %7D%0A%0A
     return %7B eve
@@ -1498,16 +1498,241 @@
 TH);%0A%7D%0A%0A
+function getResponseTime (res) %7B%0A    const profiler = res.get('X-Tiler-Profiler');%0A    let stats;%0A%0A    try %7B%0A        stats = JSON.parse(profiler);%0A    %7D catch (e) %7B%0A        return undefined;%0A    %7D%0A%0A    return stats.total;%0A%7D%0A%0A
 module.e

Add response time to pubsub events (#1155)