Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ const mockFetch: typeof fetch = async () =>
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
traceLifecycle: 'static',
tracesSampleRate: 1.0,
dataCollection: { genAI: { inputs: true, outputs: true } },
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@ import {
GEN_AI_USAGE_INPUT_TOKENS,
GEN_AI_USAGE_OUTPUT_TOKENS,
GEN_AI_USAGE_TOTAL_TOKENS,
SENTRY_SDK_NAME,
SENTRY_SDK_VERSION,
SENTRY_SEGMENT_ID,
SENTRY_SEGMENT_NAME,
SENTRY_TRACE_LIFECYCLE,
} from '@sentry/conventions/attributes';
import { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT } from '@sentry/core';
import { createRunner } from '../../../runner';
import { getSpanOp, getSpansFromEnvelope } from '../../../spanUtils';

// This test runs the `@anthropic-ai/sdk` on the Workers runtime (with a
// canned fetch) to verify the instrumentation works end-to-end on Cloudflare,
Expand All @@ -23,14 +30,14 @@ it('traces a basic message creation request with the anthropic SDK', async ({ si
const runner = createRunner(__dirname)
.ignore('event')
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1] as any;
expect(transactionEvent.transaction).toBe('GET /');
const spans = getSpansFromEnvelope(envelope);
const segmentSpan = spans.find(span => span.is_segment);
expect(segmentSpan?.name).toBe('GET /');

const container = envelope[1]?.[1]?.[1] as any;
expect(container).toBeDefined();
expect(container.items).toHaveLength(1);
const genAiSpans = spans.filter(span => getSpanOp(span)?.startsWith('gen_ai.'));
expect(genAiSpans).toHaveLength(1);

expect(container.items[0]).toEqual({
expect(genAiSpans[0]).toEqual({
trace_id: expect.any(String),
span_id: expect.any(String),
parent_span_id: expect.any(String),
Expand Down Expand Up @@ -58,6 +65,12 @@ it('traces a basic message creation request with the anthropic SDK', async ({ si
[GEN_AI_USAGE_INPUT_TOKENS]: { value: 10, type: 'integer' },
[GEN_AI_USAGE_OUTPUT_TOKENS]: { value: 15, type: 'integer' },
[GEN_AI_USAGE_TOTAL_TOKENS]: { value: 25, type: 'integer' },
[SENTRY_TRACE_LIFECYCLE]: { value: 'stream', type: 'string' },
[SENTRY_SEGMENT_NAME]: { value: segmentSpan!.name, type: 'string' },
[SENTRY_SEGMENT_ID]: { value: segmentSpan!.span_id, type: 'string' },
[SENTRY_SDK_NAME]: { value: 'sentry.javascript.cloudflare', type: 'string' },
[SENTRY_SDK_VERSION]: { value: SDK_VERSION, type: 'string' },
[SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { value: 'production', type: 'string' },
},
});
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ import * as Sentry from '@sentry/cloudflare';

interface Env {
SENTRY_DSN: string;
STREAMED?: string;
DB: D1Database;
}

export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
traceLifecycle: env.STREAMED === 'true' ? 'stream' : 'static',

tracesSampleRate: 1.0,
}),
{
Expand Down
295 changes: 97 additions & 198 deletions dev-packages/cloudflare-integration-tests/suites/tracing/d1/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import type { Envelope, SerializedStreamedSpanContainer } from '@sentry/core';
import { expect, it } from 'vitest';
import type { Envelope, SerializedStreamedSpan } from '@sentry/core';
import {
SDK_VERSION,
SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT,
Expand All @@ -14,213 +14,112 @@ import {
SENTRY_TRACE_LIFECYCLE,
} from '@sentry/conventions/attributes';
import { createRunner } from '../../../runner';
import { getSpanOp, getSpansFromEnvelope } from '../../../spanUtils';

it('D1 database queries create spans with correct attributes', async ({ signal }) => {
const runner = createRunner(__dirname)
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1];
expect(transactionEvent).toEqual(
expect.objectContaining({
type: 'transaction',
transaction: 'GET /init',
spans: [
{
data: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.query',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',
'db.system.name': 'cloudflare-d1',
'db.operation.name': 'exec',
'db.query.text': 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)',
'db.query.summary': 'CREATE TABLE users',
},
description: 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)',
op: 'db.query',
origin: 'auto.db.cloudflare.d1',
status: 'ok',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: expect.any(String),
},
{
data: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.query',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',
'db.system.name': 'cloudflare-d1',
'db.operation.name': 'run',
'db.query.text': 'INSERT INTO users (name) VALUES (?)',
'db.query.summary': 'INSERT users',
'cloudflare.d1.duration': expect.any(Number),
'cloudflare.d1.rows_read': expect.any(Number),
'cloudflare.d1.rows_written': expect.any(Number),
},
description: 'INSERT INTO users (name) VALUES (?)',
op: 'db.query',
origin: 'auto.db.cloudflare.d1',
status: 'ok',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: expect.any(String),
},
],
}),
);
})
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1];
expect(transactionEvent).toEqual(
expect.objectContaining({
type: 'transaction',
transaction: 'GET /query',
spans: [
{
data: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.query',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',
'db.system.name': 'cloudflare-d1',
'db.operation.name': 'first',
'db.query.text': 'SELECT * FROM users WHERE name = ?',
'db.query.summary': 'SELECT users',
},
description: 'SELECT * FROM users WHERE name = ?',
op: 'db.query',
origin: 'auto.db.cloudflare.d1',
status: 'ok',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: expect.any(String),
},
],
}),
);
})
.start(signal);

await runner.makeRequest('get', '/init');
await runner.makeRequest('get', '/query');
await runner.completed();
});
/** The `db.query` spans of an envelope, paired with the segment span they belong to. */
function getD1Spans(envelope: Envelope): {
segmentSpan: SerializedStreamedSpan;
d1Spans: SerializedStreamedSpan[];
} {
const spans = getSpansFromEnvelope(envelope);
const segmentSpan = spans.find(span => span.is_segment);
expect(segmentSpan).toBeDefined();

describe('with span streaming enabled', () => {
function getSpanContainer(envelope: Envelope): SerializedStreamedSpanContainer {
const spanItem = envelope[1].find(item => item[0].type === 'span');
expect(spanItem).toBeDefined();
return spanItem![1] as SerializedStreamedSpanContainer;
}
return {
segmentSpan: segmentSpan!,
d1Spans: spans.filter(span => getSpanOp(span) === 'db.query'),
};
}

/** The `db.query` spans of an envelope, paired with the segment span they belong to. */
function getD1Spans(envelope: Envelope): {
segmentSpan: SerializedStreamedSpanContainer['items'][number];
d1Spans: SerializedStreamedSpanContainer['items'];
} {
const items = getSpanContainer(envelope).items;
const segmentSpan = items.find(item => item.is_segment);
expect(segmentSpan).toBeDefined();
function commonAttributes(segmentSpan: SerializedStreamedSpan): SerializedStreamedSpan['attributes'] {
return {
[SENTRY_TRACE_LIFECYCLE]: { type: 'string', value: 'stream' },
[SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.cloudflare' },
[SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION },
[SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpan.span_id },
[SENTRY_SEGMENT_NAME]: { type: 'string', value: segmentSpan.name },
[SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' },
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'db.query' },
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.db.cloudflare.d1' },
'db.system.name': { type: 'string', value: 'cloudflare-d1' },
};
}

return {
segmentSpan: segmentSpan!,
d1Spans: items.filter(item => item.attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP]?.value === 'db.query'),
};
}
function commonSpanProps(segmentSpan: SerializedStreamedSpan): Record<string, unknown> {
return {
is_segment: false,
parent_span_id: segmentSpan.span_id,
span_id: expect.stringMatching(/^[\da-f]{16}$/),
trace_id: segmentSpan.trace_id,
start_timestamp: expect.any(Number),
end_timestamp: expect.any(Number),
status: 'ok',
};
}

function commonAttributes(
segmentSpan: SerializedStreamedSpanContainer['items'][number],
): SerializedStreamedSpanContainer['items'][number]['attributes'] {
return {
[SENTRY_TRACE_LIFECYCLE]: { type: 'string', value: 'stream' },
[SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.cloudflare' },
[SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION },
[SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpan.span_id },
[SENTRY_SEGMENT_NAME]: { type: 'string', value: segmentSpan.name },
[SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' },
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'db.query' },
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.db.cloudflare.d1' },
'db.system.name': { type: 'string', value: 'cloudflare-d1' },
};
}
// `cloudflare.d1.duration` is only an integer when the query happens to take a whole
// number of milliseconds, so the type can't be pinned down.
const NUMBER_ATTRIBUTE = { type: expect.stringMatching(/^(?:integer|double)$/), value: expect.any(Number) };

function commonSpanProps(segmentSpan: SerializedStreamedSpanContainer['items'][number]): Record<string, unknown> {
return {
is_segment: false,
parent_span_id: segmentSpan.span_id,
span_id: expect.stringMatching(/^[\da-f]{16}$/),
trace_id: segmentSpan.trace_id,
start_timestamp: expect.any(Number),
end_timestamp: expect.any(Number),
status: 'ok',
};
}

// `cloudflare.d1.duration` is only an integer when the query happens to take a whole
// number of milliseconds, so the type can't be pinned down.
const NUMBER_ATTRIBUTE = { type: expect.stringMatching(/^(?:integer|double)$/), value: expect.any(Number) };

it('names D1 query spans after their query summary', async ({ signal }) => {
const runner = createRunner(__dirname)
.withWranglerArgs('--var', 'STREAMED:true')
.expect(envelope => {
const { segmentSpan, d1Spans } = getD1Spans(envelope);
// With span streaming, the server span name is low cardinality, so the request the
// envelope belongs to is only identifiable through `url.path`.
expect(segmentSpan.name).toBe('GET');
expect(segmentSpan.attributes['url.path']).toEqual({ type: 'string', value: '/init' });
it('names D1 query spans after their query summary', async ({ signal }) => {
const runner = createRunner(__dirname)
.expect(envelope => {
const { segmentSpan, d1Spans } = getD1Spans(envelope);
// With span streaming, the server span name is low cardinality, so the request the
// envelope belongs to is only identifiable through `url.path`.
expect(segmentSpan.name).toBe('GET');
expect(segmentSpan.attributes['url.path']).toEqual({ type: 'string', value: '/init' });

expect(d1Spans).toEqual([
{
name: 'CREATE TABLE users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'exec' },
'db.query.text': {
type: 'string',
value: 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)',
},
'db.query.summary': { type: 'string', value: 'CREATE TABLE users' },
expect(d1Spans).toEqual([
{
name: 'CREATE TABLE users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'exec' },
'db.query.text': {
type: 'string',
value: 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)',
},
...commonSpanProps(segmentSpan),
'db.query.summary': { type: 'string', value: 'CREATE TABLE users' },
},
{
name: 'INSERT users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'run' },
'db.query.text': { type: 'string', value: 'INSERT INTO users (name) VALUES (?)' },
'db.query.summary': { type: 'string', value: 'INSERT users' },
'cloudflare.d1.duration': NUMBER_ATTRIBUTE,
'cloudflare.d1.rows_read': NUMBER_ATTRIBUTE,
'cloudflare.d1.rows_written': NUMBER_ATTRIBUTE,
},
...commonSpanProps(segmentSpan),
...commonSpanProps(segmentSpan),
},
{
name: 'INSERT users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'run' },
'db.query.text': { type: 'string', value: 'INSERT INTO users (name) VALUES (?)' },
'db.query.summary': { type: 'string', value: 'INSERT users' },
'cloudflare.d1.duration': NUMBER_ATTRIBUTE,
'cloudflare.d1.rows_read': NUMBER_ATTRIBUTE,
'cloudflare.d1.rows_written': NUMBER_ATTRIBUTE,
},
]);
})
.expect(envelope => {
const { segmentSpan, d1Spans } = getD1Spans(envelope);
expect(segmentSpan.name).toBe('GET');
expect(segmentSpan.attributes['url.path']).toEqual({ type: 'string', value: '/query' });
...commonSpanProps(segmentSpan),
},
]);
})
.expect(envelope => {
const { segmentSpan, d1Spans } = getD1Spans(envelope);
expect(segmentSpan.name).toBe('GET');
expect(segmentSpan.attributes['url.path']).toEqual({ type: 'string', value: '/query' });

expect(d1Spans).toEqual([
{
name: 'SELECT users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'first' },
'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE name = ?' },
'db.query.summary': { type: 'string', value: 'SELECT users' },
},
...commonSpanProps(segmentSpan),
expect(d1Spans).toEqual([
{
name: 'SELECT users',
attributes: {
...commonAttributes(segmentSpan),
'db.operation.name': { type: 'string', value: 'first' },
'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE name = ?' },
'db.query.summary': { type: 'string', value: 'SELECT users' },
},
]);
})
.start(signal);
...commonSpanProps(segmentSpan),
},
]);
})
.start(signal);

await runner.makeRequest('get', '/init');
await runner.makeRequest('get', '/query');
await runner.completed();
});
await runner.makeRequest('get', '/init');
await runner.makeRequest('get', '/query');
await runner.completed();
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ interface Env {
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
traceLifecycle: 'static',
tracesSampleRate: 1.0,
}),
{
Expand Down
Loading
Loading