"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.expressTracing = exports.lambdaSqsTracing = exports.sqsTracing = exports.AMAZON_REQUEST_TRACING_FIELD = exports.AMAZON_REQUEST_TRACING_HEADER = exports.MESSAGE_TRACING_ATTRIBUTE = void 0;
const context_1 = require("../context/context");
const context_2 = require("./context");
const lodash_1 = __importDefault(require("lodash"));
exports.MESSAGE_TRACING_ATTRIBUTE = "X-Trace-Id";
// https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-request-tracing.html
// X-Amzn-Trace-Id: Root=1-63441c4a-abcdef012345678912345678
exports.AMAZON_REQUEST_TRACING_HEADER = "X-Amzn-Trace-Id";
exports.AMAZON_REQUEST_TRACING_FIELD = "Root";
const sqsTracing = (ctx, message) => {
    var _a;
    const tracing = (_a = message.MessageAttributes) === null || _a === void 0 ? void 0 : _a[exports.MESSAGE_TRACING_ATTRIBUTE];
    if (!tracing || !tracing.StringValue) {
        return ctx;
    }
    return (0, context_2.withTracing)(ctx, tracing.StringValue);
};
exports.sqsTracing = sqsTracing;
const lambdaSqsTracing = (ctx, record) => {
    var _a;
    const tracing = (_a = record.messageAttributes) === null || _a === void 0 ? void 0 : _a[exports.MESSAGE_TRACING_ATTRIBUTE];
    if (!tracing || !tracing.stringValue) {
        return ctx;
    }
    return (0, context_2.withTracing)(ctx, tracing.stringValue);
};
exports.lambdaSqsTracing = lambdaSqsTracing;
const parseHeader = (header, fieldDelimiter, separator) => {
    const ret = {};
    for (const field of lodash_1.default.split(header, fieldDelimiter)) {
        const tokens = lodash_1.default.split(field, separator);
        if (tokens.length == 2) {
            ret[tokens[0]] = tokens[1];
        }
    }
    return ret;
};
const expressTracing = (req, response, next) => {
    if (!req.ctx) {
        req.ctx = (0, context_1.newContext)();
    }
    const fields = parseHeader((req.get(exports.AMAZON_REQUEST_TRACING_HEADER) || ""), ";", "=");
    if (fields === null || fields === void 0 ? void 0 : fields[exports.AMAZON_REQUEST_TRACING_FIELD]) {
        req.ctx = (0, context_2.withTracing)(req.ctx, fields[exports.AMAZON_REQUEST_TRACING_FIELD]);
    }
    next();
};
exports.expressTracing = expressTracing;
//# sourceMappingURL=middleware.js.map