import { newContext } from "../context/context";
import { withTracing } from "./context";
import _ from "lodash";
export const 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
export const AMAZON_REQUEST_TRACING_HEADER = "X-Amzn-Trace-Id";
export const AMAZON_REQUEST_TRACING_FIELD = "Root";
export const sqsTracing = (ctx, message) => {
    var _a;
    const tracing = (_a = message.MessageAttributes) === null || _a === void 0 ? void 0 : _a[MESSAGE_TRACING_ATTRIBUTE];
    if (!tracing || !tracing.StringValue) {
        return ctx;
    }
    return withTracing(ctx, tracing.StringValue);
};
export const lambdaSqsTracing = (ctx, record) => {
    var _a;
    const tracing = (_a = record.messageAttributes) === null || _a === void 0 ? void 0 : _a[MESSAGE_TRACING_ATTRIBUTE];
    if (!tracing || !tracing.stringValue) {
        return ctx;
    }
    return withTracing(ctx, tracing.stringValue);
};
const parseHeader = (header, fieldDelimiter, separator) => {
    const ret = {};
    for (const field of _.split(header, fieldDelimiter)) {
        const tokens = _.split(field, separator);
        if (tokens.length == 2) {
            ret[tokens[0]] = tokens[1];
        }
    }
    return ret;
};
export const expressTracing = (req, response, next) => {
    if (!req.ctx) {
        req.ctx = newContext();
    }
    const fields = parseHeader((req.get(AMAZON_REQUEST_TRACING_HEADER) || ""), ";", "=");
    if (fields === null || fields === void 0 ? void 0 : fields[AMAZON_REQUEST_TRACING_FIELD]) {
        req.ctx = withTracing(req.ctx, fields[AMAZON_REQUEST_TRACING_FIELD]);
    }
    next();
};
//# sourceMappingURL=middleware.js.map