@azure/service-bus
Version:
Azure Service Bus SDK for JavaScript
101 lines • 3.33 kB
JavaScript
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { toSpanOptions, tracingClient } from "./tracing";
/**
* @internal
*/
export const TRACEPARENT_PROPERTY = "Diagnostic-Id";
/**
* Instruments an AMQP message with a proper `Diagnostic-Id` for tracing.
*
* @hidden
*/
export function instrumentMessage(message, options, entityPath, host, operation) {
// check if the event has already been instrumented
const previouslyInstrumented = Boolean(message.applicationProperties?.[TRACEPARENT_PROPERTY]);
if (previouslyInstrumented) {
return {
message,
spanContext: undefined,
};
}
const { span: messageSpan, updatedOptions } = tracingClient.startSpan("message", options, toSpanOptions({ entityPath, host }, operation, "producer"));
try {
if (!messageSpan.isRecording()) {
return {
message,
spanContext: undefined,
};
}
const traceParent = tracingClient.createRequestHeaders(updatedOptions.tracingOptions?.tracingContext)["traceparent"];
if (traceParent) {
// create a copy so the original isn't modified
message = {
...message,
applicationProperties: {
...message.applicationProperties,
[TRACEPARENT_PROPERTY]: traceParent,
},
};
}
return {
message,
spanContext: updatedOptions.tracingOptions?.tracingContext,
};
}
finally {
messageSpan.end();
}
}
/**
* Extracts the `SpanContext` from an `ServiceBusMessage` if the context exists.
* @param message - An individual `ServiceBusMessage` object.
* @internal
*/
export function extractSpanContextFromServiceBusMessage(message) {
if (!message.applicationProperties || !message.applicationProperties[TRACEPARENT_PROPERTY]) {
return;
}
const diagnosticId = message.applicationProperties[TRACEPARENT_PROPERTY];
return tracingClient.parseTraceparentHeader(diagnosticId);
}
/**
* Provides an iterable over messages, whether it is a single message or multiple
* messages.
*
* @param receivedMessages - A single message or a set of messages
* @internal
*/
function* getReceivedMessages(receivedMessages) {
if (!Array.isArray(receivedMessages)) {
yield receivedMessages;
}
else {
for (const message of receivedMessages) {
yield message;
}
}
}
/**
* @internal
*/
export function toProcessingSpanOptions(receivedMessages, receiver, connectionConfig, operation) {
const spanLinks = [];
for (const receivedMessage of getReceivedMessages(receivedMessages)) {
const tracingContext = extractSpanContextFromServiceBusMessage(receivedMessage);
if (tracingContext) {
spanLinks.push({
tracingContext,
attributes: {
enqueuedTime: receivedMessage.enqueuedTimeUtc?.getTime(),
},
});
}
}
return {
spanLinks,
spanKind: "consumer",
...toSpanOptions({ host: connectionConfig.host, entityPath: receiver.entityPath }, operation),
};
}
//# sourceMappingURL=instrumentServiceBusMessage.js.map