Skip to content

Commit

Permalink
Merge pull request #11 from Steffen911/feat/10-use-producer-context-i…
Browse files Browse the repository at this point in the history
…n-consumer

Add flag to use producer context as consumer parent
  • Loading branch information
unflxw authored Oct 8, 2024
2 parents c88bb5c + 9fb5762 commit f836455
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 47 deletions.
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ registerInstrumentations({

## Configuration options

| Name | Type | Default value | Description |
| ----------------------------- | --------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `emitCreateSpansForBulk` | `boolean` | `true` | Whether to emit a create span for each individual job enqueued by `Queue.addBulk` or `FlowProducer.addBulk`. The span representing the overall bulk operation is emitted regardless. |
| `emitCreateSpansForFlow` | `boolean` | `true` | Whether to emit a create span for each individual job enqueued by `FlowProducer.add` or `FlowProducer.addBulk`. The span representing the overall flow operation is emitted regardless. |
| `requireParentSpanForPublish` | `boolean` | `false` | Whether to omit emitting a publish span (and the create child spans for it, for bulk and flow operations) when there is no parent span, meaning that the span created would be the root span of a new trace. |
| Name | Type | Default value | Description |
| ------------------------------------ | --------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `emitCreateSpansForBulk` | `boolean` | `true` | Whether to emit a create span for each individual job enqueued by `Queue.addBulk` or `FlowProducer.addBulk`. The span representing the overall bulk operation is emitted regardless. |
| `emitCreateSpansForFlow` | `boolean` | `true` | Whether to emit a create span for each individual job enqueued by `FlowProducer.add` or `FlowProducer.addBulk`. The span representing the overall flow operation is emitted regardless. |
| `requireParentSpanForPublish` | `boolean` | `false` | Whether to omit emitting a publish span (and the create child spans for it, for bulk and flow operations) when there is no parent span, meaning that the span created would be the root span of a new trace. |
| `useProducerContextAsConsumerParent` | `boolean` | `false` | Whether to use the producer context as the parent for the consumer span. Consumer and Producer will share the same TraceId in this case. |

## Emitted spans

Expand Down
19 changes: 12 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

85 changes: 50 additions & 35 deletions src/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,17 @@ export interface BullMQInstrumentationConfig extends InstrumentationConfig {
/** Require a parent span in order to create a producer span
* (a span for the enqueueing of one or more jobs) -- defaults to `false` */
requireParentSpanForPublish?: boolean;

/** Whether to use the producer context as the parent for the consumer span.
* Consumer and Producer will share the same TraceId in this case. Defaults to `false` */
useProducerContextAsConsumerParent?: boolean;
}

export const defaultConfig: Required<BullMQInstrumentationConfig> = {
emitCreateSpansForBulk: true,
emitCreateSpansForFlow: true,
requireParentSpanForPublish: false,
useProducerContextAsConsumerParent: false,
// unused by `configFor` but required for the type
enabled: true,
};
Expand Down Expand Up @@ -446,42 +451,52 @@ export class BullMQInstrumentation extends InstrumentationBase {
const producerContext = propagation.extract(currentContext, job.opts);

const spanName = `${job.queueName} ${operationType}`;
const span = tracer.startSpan(spanName, {
attributes: BullMQInstrumentation.dropInvalidAttributes({
[SemanticAttributes.MESSAGING_SYSTEM]:
BullMQAttributes.MESSAGING_SYSTEM,
[SemanticAttributes.MESSAGING_CONSUMER_ID]: workerName,
[SemanticAttributes.MESSAGING_MESSAGE_ID]: job.id,
[SemanticAttributes.MESSAGING_OPERATION]: operationType,
[BullMQAttributes.MESSAGING_OPERATION_NAME]: operationName,
[BullMQAttributes.JOB_NAME]: job.name,
[BullMQAttributes.JOB_ATTEMPTS]: job.attemptsMade,
[BullMQAttributes.JOB_TIMESTAMP]: job.timestamp,
[BullMQAttributes.JOB_DELAY]: job.delay,
[BullMQAttributes.JOB_REPEAT_KEY]: job.repeatJobKey,
...BullMQInstrumentation.attrMap(
BullMQAttributes.JOB_OPTS,
job.opts,
const span = tracer.startSpan(
spanName,
{
attributes: BullMQInstrumentation.dropInvalidAttributes({
[SemanticAttributes.MESSAGING_SYSTEM]:
BullMQAttributes.MESSAGING_SYSTEM,
[SemanticAttributes.MESSAGING_CONSUMER_ID]: workerName,
[SemanticAttributes.MESSAGING_MESSAGE_ID]: job.id,
[SemanticAttributes.MESSAGING_OPERATION]: operationType,
[BullMQAttributes.MESSAGING_OPERATION_NAME]: operationName,
[BullMQAttributes.JOB_NAME]: job.name,
[BullMQAttributes.JOB_ATTEMPTS]: job.attemptsMade,
[BullMQAttributes.JOB_TIMESTAMP]: job.timestamp,
[BullMQAttributes.JOB_DELAY]: job.delay,
[BullMQAttributes.JOB_REPEAT_KEY]: job.repeatJobKey,
...BullMQInstrumentation.attrMap(
BullMQAttributes.JOB_OPTS,
job.opts,
),
[SemanticAttributes.MESSAGING_DESTINATION]: job.queueName,
[BullMQAttributes.WORKER_CONCURRENCY]: this.opts?.concurrency,
[BullMQAttributes.WORKER_LOCK_DURATION]: this.opts?.lockDuration,
[BullMQAttributes.WORKER_LOCK_RENEW]: this.opts?.lockRenewTime,
[BullMQAttributes.WORKER_RATE_LIMIT_MAX]: this.opts?.limiter?.max,
[BullMQAttributes.WORKER_RATE_LIMIT_DURATION]:
this.opts?.limiter?.duration,
// Limit by group keys was removed in bullmq 3.x
[BullMQAttributes.WORKER_RATE_LIMIT_GROUP]: (
this.opts?.limiter as any
)?.groupKey,
}),
kind: SpanKind.CONSUMER,
links: BullMQInstrumentation.dropInvalidLinks(
instrumentation.configFor("useProducerContextAsConsumerParent")
? []
: [
{
context: trace.getSpanContext(producerContext),
},
],
),
[SemanticAttributes.MESSAGING_DESTINATION]: job.queueName,
[BullMQAttributes.WORKER_CONCURRENCY]: this.opts?.concurrency,
[BullMQAttributes.WORKER_LOCK_DURATION]: this.opts?.lockDuration,
[BullMQAttributes.WORKER_LOCK_RENEW]: this.opts?.lockRenewTime,
[BullMQAttributes.WORKER_RATE_LIMIT_MAX]: this.opts?.limiter?.max,
[BullMQAttributes.WORKER_RATE_LIMIT_DURATION]:
this.opts?.limiter?.duration,
// Limit by group keys was removed in bullmq 3.x
[BullMQAttributes.WORKER_RATE_LIMIT_GROUP]: (
this.opts?.limiter as any
)?.groupKey,
}),
kind: SpanKind.CONSUMER,
links: BullMQInstrumentation.dropInvalidLinks([
{
context: trace.getSpanContext(producerContext),
},
]),
});
},
instrumentation.configFor("useProducerContextAsConsumerParent")
? producerContext
: currentContext,
);

const consumerContext = trace.setSpan(currentContext, span);

Expand Down
36 changes: 36 additions & 0 deletions test/instrumentation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,42 @@ describe("bullmq", () => {
assertSpanParent(insideJobSpan!, workerJobSpan!);
});

it("should set the producer context as active when useProducerContextAsConsumerParent true", async () => {
instrumentation.setConfig({ useProducerContextAsConsumerParent: true });

const [processor, processorDone] = getWait();

const q = new Queue("queueName", { connection });
const w = new Worker(
"queueName",
async () => {
processorDone();
return { completed: new Date().toTimeString() };
},
{ connection },
);
await w.waitUntilReady();

await q.add("testJob", { test: "yes" });

await processor;
await w.close();

const spans = memoryExporter.getFinishedSpans();
const producerJobSpan = spans.find((span) =>
span.name.includes("queueName publish"),
);
assert.notStrictEqual(producerJobSpan, undefined);
const workerJobSpan = spans.find((span) =>
span.name.includes("queueName process"),
);
assert.notStrictEqual(workerJobSpan, undefined);

assertSpanParent(workerJobSpan!, producerJobSpan!);

assert.ok(workerJobSpan!.links.length === 0);
});

it("should capture events from the processor", async () => {
const [processor, processorDone] = getWait();

Expand Down

0 comments on commit f836455

Please sign in to comment.