-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(cloudflare): Support tracing for queue producer #20529
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JPeer264
wants to merge
1
commit into
develop
Choose a base branch
from
jp/cloudflare-queues
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
dev-packages/cloudflare-integration-tests/suites/queue/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import type { MessageBatch, Queue } from '@cloudflare/workers-types'; | ||
| import * as Sentry from '@sentry/cloudflare'; | ||
|
|
||
| interface Env { | ||
| SENTRY_DSN: string; | ||
| MY_QUEUE: Queue<{ trigger?: 'error'; payload?: string }>; | ||
| } | ||
|
|
||
| export default Sentry.withSentry( | ||
| (env: Env) => ({ | ||
| dsn: env.SENTRY_DSN, | ||
| tracesSampleRate: 1, | ||
| }), | ||
| { | ||
| async fetch(request, env) { | ||
| const url = new URL(request.url); | ||
|
|
||
| if (url.pathname === '/enqueue/error') { | ||
| await env.MY_QUEUE.send({ trigger: 'error' }); | ||
| return new Response('enqueued error'); | ||
| } | ||
|
|
||
| if (url.pathname === '/enqueue/ok') { | ||
| await env.MY_QUEUE.send({ payload: 'hello' }); | ||
| return new Response('enqueued ok'); | ||
| } | ||
|
|
||
| if (url.pathname === '/enqueue/batch') { | ||
| await env.MY_QUEUE.sendBatch([ | ||
| { body: { payload: 'one' } }, | ||
| { body: { payload: 'two' } }, | ||
| { body: { payload: 'three' } }, | ||
| ]); | ||
| return new Response('enqueued batch'); | ||
| } | ||
|
|
||
| return new Response('not found', { status: 404 }); | ||
| }, | ||
| async queue(batch: MessageBatch<{ trigger?: 'error'; payload?: string }>) { | ||
| for (const message of batch.messages) { | ||
| if (message.body.trigger === 'error') { | ||
| throw new Error('Boom from queue handler'); | ||
| } | ||
| } | ||
| }, | ||
| } as ExportedHandler<Env>, | ||
| ); |
128 changes: 128 additions & 0 deletions
128
dev-packages/cloudflare-integration-tests/suites/queue/test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import type { Envelope } from '@sentry/core'; | ||
| import { expect, it } from 'vitest'; | ||
| import { createRunner } from '../../runner'; | ||
|
|
||
| function envelopeItemType(envelope: Envelope): string | undefined { | ||
| return envelope[1][0]?.[0]?.type as string | undefined; | ||
| } | ||
|
|
||
| function envelopeItem(envelope: Envelope): Record<string, unknown> { | ||
| return envelope[1][0]![1] as Record<string, unknown>; | ||
| } | ||
|
|
||
| function findPublishSpan(envelope: Envelope): Record<string, unknown> | undefined { | ||
| if (envelopeItemType(envelope) !== 'transaction') return undefined; | ||
| const tx = envelopeItem(envelope); | ||
| const spans = (tx.spans as Array<Record<string, unknown>>) || []; | ||
| return spans.find(s => (s.op as string) === 'queue.publish'); | ||
| } | ||
|
|
||
| function isConsumerTransaction(envelope: Envelope): boolean { | ||
| if (envelopeItemType(envelope) !== 'transaction') return false; | ||
| const tx = envelopeItem(envelope); | ||
| return tx.transaction === 'process test-queue'; | ||
| } | ||
|
|
||
| it('captures errors thrown by the queue handler with the correct mechanism', async ({ signal }) => { | ||
| const runner = createRunner(__dirname) | ||
| .ignore('transaction') | ||
| .expect((envelope: Envelope) => { | ||
| expect(envelopeItemType(envelope)).toBe('event'); | ||
| const event = envelopeItem(envelope); | ||
| expect(event).toMatchObject({ | ||
| level: 'error', | ||
| exception: { | ||
| values: [ | ||
| { | ||
| type: 'Error', | ||
| value: 'Boom from queue handler', | ||
| mechanism: { type: 'auto.faas.cloudflare.queue', handled: false }, | ||
| }, | ||
| ], | ||
| }, | ||
| }); | ||
| }) | ||
| .start(signal); | ||
|
|
||
| await runner.makeRequest('post', '/enqueue/error'); | ||
| await runner.completed(); | ||
| }); | ||
|
|
||
| it('emits a queue.publish span on env.MY_QUEUE.send and a queue.process transaction on the consumer', async ({ | ||
| signal, | ||
| }) => { | ||
| const runner = createRunner(__dirname) | ||
| .unordered() | ||
| .expect((envelope: Envelope) => { | ||
| // Producer transaction must contain a queue.publish child span | ||
| const publishSpan = findPublishSpan(envelope); | ||
| expect(publishSpan).toBeDefined(); | ||
| expect(publishSpan).toMatchObject({ | ||
| op: 'queue.publish', | ||
| description: 'send MY_QUEUE', | ||
| data: expect.objectContaining({ | ||
| 'messaging.system': 'cloudflare', | ||
| 'messaging.destination.name': 'MY_QUEUE', | ||
| 'messaging.operation.type': 'send', | ||
| 'messaging.operation.name': 'send', | ||
| 'sentry.origin': 'auto.faas.cloudflare.queue', | ||
| }), | ||
| }); | ||
| }) | ||
| .expect((envelope: Envelope) => { | ||
| expect(isConsumerTransaction(envelope)).toBe(true); | ||
| const tx = envelopeItem(envelope); | ||
| const trace = (tx.contexts as Record<string, Record<string, unknown>>).trace as Record<string, unknown>; | ||
| expect(trace).toMatchObject({ | ||
| op: 'queue.process', | ||
| origin: 'auto.faas.cloudflare.queue', | ||
| data: expect.objectContaining({ | ||
| 'messaging.system': 'cloudflare', | ||
| 'messaging.destination.name': 'test-queue', | ||
| 'messaging.operation.type': 'process', | ||
| 'messaging.operation.name': 'process', | ||
| 'messaging.batch.message_count': 1, | ||
| 'faas.trigger': 'pubsub', | ||
| }), | ||
| }); | ||
| }) | ||
| .start(signal); | ||
|
|
||
| await runner.makeRequest('post', '/enqueue/ok'); | ||
| await runner.completed(); | ||
| }); | ||
|
|
||
| it('emits a queue.publish span with batch attributes on env.MY_QUEUE.sendBatch', async ({ signal }) => { | ||
| const runner = createRunner(__dirname) | ||
| .unordered() | ||
| .expect((envelope: Envelope) => { | ||
| const publishSpan = findPublishSpan(envelope); | ||
| expect(publishSpan).toBeDefined(); | ||
| expect(publishSpan).toMatchObject({ | ||
| op: 'queue.publish', | ||
| description: 'send MY_QUEUE', | ||
| data: expect.objectContaining({ | ||
| 'messaging.system': 'cloudflare', | ||
| 'messaging.destination.name': 'MY_QUEUE', | ||
| 'messaging.operation.type': 'send', | ||
| 'messaging.operation.name': 'send', | ||
| 'messaging.batch.message_count': 3, | ||
| 'sentry.origin': 'auto.faas.cloudflare.queue', | ||
| }), | ||
| }); | ||
| }) | ||
| .expect((envelope: Envelope) => { | ||
| expect(isConsumerTransaction(envelope)).toBe(true); | ||
| const tx = envelopeItem(envelope); | ||
| const trace = (tx.contexts as Record<string, Record<string, unknown>>).trace as Record<string, unknown>; | ||
| expect(trace).toMatchObject({ | ||
| data: expect.objectContaining({ | ||
| 'messaging.batch.message_count': 3, | ||
| }), | ||
| }); | ||
| }) | ||
| .start(signal); | ||
|
|
||
| await runner.makeRequest('post', '/enqueue/batch'); | ||
| await runner.completed(); | ||
| }); |
22 changes: 22 additions & 0 deletions
22
dev-packages/cloudflare-integration-tests/suites/queue/wrangler.jsonc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| { | ||
| "name": "worker-name", | ||
| "compatibility_date": "2025-06-17", | ||
| "main": "index.ts", | ||
| "compatibility_flags": ["nodejs_compat"], | ||
| "queues": { | ||
| "producers": [ | ||
| { | ||
| "queue": "test-queue", | ||
| "binding": "MY_QUEUE", | ||
| }, | ||
| ], | ||
| "consumers": [ | ||
| { | ||
| "queue": "test-queue", | ||
| "max_batch_size": 10, | ||
| "max_batch_timeout": 1, | ||
| "max_retries": 0, | ||
| }, | ||
| ], | ||
| }, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
101 changes: 101 additions & 0 deletions
101
packages/cloudflare/src/instrumentations/worker/instrumentQueueProducer.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import type { MessageSendRequest, Queue, QueueSendBatchOptions, QueueSendOptions } from '@cloudflare/workers-types'; | ||
| import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core'; | ||
|
|
||
| const ORIGIN = 'auto.faas.cloudflare.queue'; | ||
|
|
||
| function startPublishSpan<T>( | ||
| options: { | ||
| bindingName: string; | ||
| bodySize: number | undefined; | ||
| messageCount?: number; | ||
| }, | ||
| callback: () => T, | ||
| ): T { | ||
| const { bindingName, bodySize, messageCount } = options; | ||
|
|
||
| return startSpan( | ||
| { | ||
| op: 'queue.publish', | ||
| name: `send ${bindingName}`, | ||
| attributes: { | ||
| 'messaging.system': 'cloudflare', | ||
| 'messaging.destination.name': bindingName, | ||
| 'messaging.operation.type': 'send', | ||
| 'messaging.operation.name': 'send', | ||
| ...(messageCount !== undefined && { 'messaging.batch.message_count': messageCount }), | ||
| 'messaging.message.body.size': bodySize, | ||
| [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'queue.publish', | ||
| [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN, | ||
| }, | ||
| }, | ||
| callback, | ||
| ); | ||
| } | ||
|
|
||
| function getBodySize(body: unknown): number | undefined { | ||
| if (body == null) { | ||
| return undefined; | ||
| } | ||
|
|
||
| if (typeof body === 'string') { | ||
| return new TextEncoder().encode(body).byteLength; | ||
| } | ||
|
|
||
| if (body instanceof ArrayBuffer) { | ||
| return body.byteLength; | ||
| } | ||
|
|
||
| if (ArrayBuffer.isView(body)) { | ||
| return body.byteLength; | ||
| } | ||
|
|
||
| try { | ||
| return new TextEncoder().encode(JSON.stringify(body)).byteLength; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Wraps a Queue producer binding to create `queue.publish` spans on | ||
| * `send` and `sendBatch` calls. | ||
| * | ||
| * The queue's own name is not available on the binding object, so we use | ||
| * the env binding key (e.g. `MY_QUEUE`) as `messaging.destination.name`. | ||
| */ | ||
| export function instrumentQueueProducer<T extends Queue>(queue: T, bindingName: string): T { | ||
| return new Proxy(queue, { | ||
| get(target, prop, receiver) { | ||
| if (prop === 'send') { | ||
| const original = Reflect.get(target, prop, receiver) as Queue['send']; | ||
|
|
||
| return function (this: unknown, message: unknown, options?: QueueSendOptions): Promise<void> { | ||
| return startPublishSpan({ bindingName, bodySize: getBodySize(message) }, () => | ||
| Reflect.apply(original, target, [message, options]), | ||
| ); | ||
| }; | ||
| } | ||
|
|
||
| if (prop === 'sendBatch') { | ||
| const original = Reflect.get(target, prop, receiver) as Queue['sendBatch']; | ||
| return function ( | ||
| this: unknown, | ||
| messages: Iterable<MessageSendRequest>, | ||
| options?: QueueSendBatchOptions, | ||
| ): Promise<void> { | ||
| const messageArray = Array.from(messages); | ||
| const totalBodySize = messageArray.reduce<number>((acc, m) => { | ||
| const size = getBodySize(m.body); | ||
| return size === undefined ? acc : acc + size; | ||
| }, 0); | ||
|
|
||
| return startPublishSpan({ bindingName, bodySize: totalBodySize, messageCount: messageArray.length }, () => | ||
| Reflect.apply(original, target, [messageArray, options]), | ||
| ); | ||
| }; | ||
| } | ||
|
|
||
| return Reflect.get(target, prop, receiver); | ||
| }, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sendBatch reports body size 0 instead of undefined
Low Severity
The
sendBatchbody size calculation usesreducewith an initial value of0, sototalBodySizeis always anumber(minimum 0). When all messages have unsizable bodies (e.g., null or circular references),totalBodySizewill be0andmessaging.message.body.sizegets set to0. This is inconsistent withsend, which correctly passesundefinedfromgetBodySizewhen the body can't be sized, causing the attribute to be omitted. ThesendBatchpath emits a misleading0instead.Reviewed by Cursor Bugbot for commit b9b0533. Configure here.