Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ Work in this release was contributed by @adityareddy-dev, @jpdefo, @Jxxunnn, @ph

`httpIntegration` and `httpServerSpansIntegration` now accept `onSpanEnd`, a hook that runs when the response for an incoming request finishes, before its span ends. Use it to change the span based on the response. Deno and Bun already have this option.

- **feat(cloudflare): Add incoming request span options to `httpServerIntegration`**

Cloudflare's `httpServerIntegration` now accepts `ignoreIncomingRequests`, `ignoreStaticAssets`, `spans`, `onSpanCreated` and `onSpanEnd`, with the same meaning as in the Node, Deno and Bun integrations. The callbacks receive the web `Request`.

`ignoreStaticAssets` defaults to `true`, so workers no longer create spans for `GET` requests to common static assets such as `favicon.ico`, `robots.txt` or `*.js` files. To keep these spans, set `httpServerIntegration({ ignoreStaticAssets: false })`. Request spans also follow the client's tracing configuration by default, so the SDK does not start them when tracing is disabled. If `ignoreRequestBody` throws, the request no longer fails, and the SDK skips the body.

## 11.8.0

### Important Changes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import * as Sentry from '@sentry/cloudflare';

interface Env {
SENTRY_DSN: string;
}

export default Sentry.withSentry(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: We should rather use the Vite plugin instead for new tests.

(env: Env) => ({
dsn: env.SENTRY_DSN,
tracesSampleRate: 1.0,
traceLifecycle: 'static',
integrations: [
Sentry.httpServerIntegration({
ignoreIncomingRequests: urlPath => urlPath.startsWith('/health'),
onSpanCreated: (span, request) => {
span.setAttribute('test.on_span_created', new URL(request.url).pathname);
},
onSpanEnd: (span, _request, response) => {
span.setAttribute('test.on_span_end', response.status);
},
}),
],
}),
{
async fetch(request, _env, _ctx) {
const { pathname } = new URL(request.url);

if (pathname === '/health') {
Sentry.captureMessage('Health check');
return new Response('ok');
}

if (pathname === '/favicon.ico') {
Sentry.captureMessage('Static asset');
return new Response('icon');
}

if (pathname === '/health/stream') {
// No span for this request. The message is captured after the handler returns, while the
// body streams, so it is only sent if the SDK waits for the stream to finish.
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
async start(controller) {
controller.enqueue(encoder.encode('a'));
await new Promise(resolve => setTimeout(resolve, 50));
Sentry.captureMessage('Streamed after handler return');
controller.enqueue(encoder.encode('b'));
controller.close();
},
});
return new Response(body, { headers: { 'content-type': 'text/event-stream' } });
}

return new Response('ok', { status: 201 });
},
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import type { Envelope, Event } from '@sentry/core';
import { expect, it } from 'vitest';
import { createRunner } from '../../../runner';

function itemOf(envelope: Envelope): { type: string; event: Event } {
const [header, event] = envelope[1][0] as [{ type: string }, Event];
return { type: header.type, event };
}

function messageEvent(message: string): (envelope: Envelope) => void {
return envelope => {
const { type, event } = itemOf(envelope);
expect(type).toBe('event');
expect(event.message).toBe(message);
};
}

// The `onSpanCreated` and `onSpanEnd` hooks of the worker set these attributes.
function apiTransaction(envelope: Envelope): void {
const { type, event } = itemOf(envelope);
expect(type).toBe('transaction');
expect(event.transaction).toBe('GET /api');
expect(event.contexts?.trace?.data).toEqual(
expect.objectContaining({
'test.on_span_created': '/api',
'test.on_span_end': 201,
}),
);
}

// Each test makes a request without a span, then a request with one. With `failOnUnexpected`, a
// transaction for the first request fails the test, as it arrives before the second one.

it('does not create a span for a request that ignoreIncomingRequests matches', async ({ signal }) => {
const runner = createRunner(__dirname)
.unordered()
.failOnUnexpected()
.expect(messageEvent('Health check'))
.expect(apiTransaction)
.start(signal);

await runner.makeRequest('get', '/health');
await runner.makeRequest('get', '/api');
await runner.completed();
});

it('does not create a span for a static asset request by default', async ({ signal }) => {
const runner = createRunner(__dirname)
.unordered()
.failOnUnexpected()
.expect(messageEvent('Static asset'))
.expect(apiTransaction)
.start(signal);

await runner.makeRequest('get', '/favicon.ico');
await runner.makeRequest('get', '/api');
await runner.completed();
});

it('sends events from a streamed response without a span after the stream finishes', async ({ signal }) => {
const runner = createRunner(__dirname)
.unordered()
.failOnUnexpected()
.expect(messageEvent('Streamed after handler return'))
.expect(apiTransaction)
.start(signal);

expect(await runner.makeRequest<string>('get', '/health/stream')).toBe('ab');
await runner.makeRequest('get', '/api');
await runner.completed();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "worker-name",
"compatibility_date": "2025-06-17",
"main": "index.ts",
"compatibility_flags": ["nodejs_compat"],
}
133 changes: 120 additions & 13 deletions packages/cloudflare/src/integrations/httpServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import type { Client, IntegrationFn, MaxRequestBodySize } from '@sentry/core';
import { captureBodyFromWinterCGRequest, defineIntegration, getIsolationScope } from '@sentry/core';
import type { Client, IntegrationFn, MaxRequestBodySize, Span } from '@sentry/core';
import {
captureBodyFromWinterCGRequest,
defineIntegration,
getIsolationScope,
hasSpansEnabled,
parseStringToURLObject,
safeCallback,
} from '@sentry/core';
import type { AssertTrue, CheckServerRequestOptions } from '@sentry/core/server';
import { isStaticAssetRequest } from '@sentry/core/server';
import { DEBUG_BUILD } from '../debug-build';

const INTEGRATION_NAME = 'HttpServer' as const;

Expand Down Expand Up @@ -39,6 +48,42 @@ export interface HttpServerIntegrationOptions {
* ```
*/
ignoreRequestBody?: (url: string, request: Request) => boolean;

/**
* Do not create spans for incoming requests whose URL path makes the given callback return `true`.
*
* `urlPath` is the path of the request, including the query string. `request` is the incoming
* {@link Request}. Errors thrown by the handler are still captured.
*/
ignoreIncomingRequests?: (urlPath: string, request: Request) => boolean;

/**
* Whether to automatically ignore common static asset requests (favicon.ico, robots.txt, etc.)
* when creating spans.
*
* @default `true`
*/
ignoreStaticAssets?: boolean;

/**
* Whether to create spans for incoming requests.
* Errors are still captured and request data is still attached when this is `false`.
* Defaults to the client's tracing configuration (`hasSpansEnabled`).
*/
spans?: boolean;

/**
* A hook that can be used to mutate the span for incoming requests.
* This is triggered after the span is created, before the request handler runs.
*/
onSpanCreated?: (span: Span, request: Request) => void;

/**
* A hook that can be used to mutate the span one last time before it ends.
* For a streamed response, this runs when the stream finishes.
* It is not called when the request handler throws.
*/
onSpanEnd?: (span: Span, request: Request, response: Response) => void;
Comment thread
cursor[bot] marked this conversation as resolved.
}

// Checks these options against the shared `ServerRequestOptions`. A new
Expand All @@ -49,30 +94,27 @@ type _ServerRequestOptionsCheck = AssertTrue<
HttpServerIntegrationOptions,
Request,
Response,
// Not supported yet.
| 'spans'
| 'ignoreIncomingRequests'
| 'ignoreStaticAssets'
| 'onSpanCreated'
| 'onSpanEnd'
// Not supported. A worker has no long-lived process to run the timer
// that flushes session aggregates.
| 'sessions'
| 'sessionFlushingDelayMS'
'sessions' | 'sessionFlushingDelayMS'
>
>;

interface HttpServerIntegrationInstance {
interface HttpServerIntegrationInstance extends HttpServerIntegrationOptions {
name: string;
maxRequestBodySize: MaxRequestBodySize | undefined;
ignoreRequestBody?: (url: string, request: Request) => boolean;
}

const _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {
return {
name: INTEGRATION_NAME,
maxRequestBodySize: options.maxRequestBodySize,
ignoreRequestBody: options.ignoreRequestBody,
ignoreIncomingRequests: options.ignoreIncomingRequests,
ignoreStaticAssets: options.ignoreStaticAssets ?? true,
spans: options.spans,
onSpanCreated: options.onSpanCreated,
onSpanEnd: options.onSpanEnd,
};
}) satisfies IntegrationFn;

Expand Down Expand Up @@ -122,10 +164,75 @@ export async function captureIncomingRequestBody(client: Client, request: Reques
return;
}

if (integration.ignoreRequestBody?.(request.url, request)) {
const ignoreRequestBody = integration.ignoreRequestBody;
if (
ignoreRequestBody &&
// If the filter throws, skip the body so it cannot leak data the filter was meant to hide.
safeCallback(
DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',
() => ignoreRequestBody(request.url, request),
() => true,
)
) {
return;
}

const isolationScope = getIsolationScope();
await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);
}

/**
* Whether to create a span for the incoming request, based on the HttpServer integration config.
* Called internally by `wrapRequestHandler`.
*/
export function shouldCreateIncomingRequestSpan(client: Client | undefined, request: Request): boolean {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (!client) {
return false;
}

const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);
if (!(integration?.spans ?? hasSpansEnabled(client.getOptions()))) {
return false;
}

const urlObject = parseStringToURLObject(request.url);
const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';
if (integration?.ignoreStaticAssets && request.method === 'GET' && isStaticAssetRequest(urlPath)) {
return false;
}

const ignoreIncomingRequests = integration?.ignoreIncomingRequests;
return !(
ignoreIncomingRequests &&
safeCallback(
DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',
() => ignoreIncomingRequests(urlPath, request),
() => false,
)
);
}

/**
* The `onSpanCreated` and `onSpanEnd` hooks of the HttpServer integration, guarded so that a hook
* that throws does not fail the request. Called internally by `wrapRequestHandler`.
*/
export function getIncomingRequestSpanHooks(client: Client | undefined): {
onSpanCreated: (span: Span, request: Request) => void;
onSpanEnd: (span: Span, request: Request, response: Response) => void;
} {
const integration = client?.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);
return {
onSpanCreated: (span, request) =>
safeCallback(
DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',
() => integration?.onSpanCreated?.(span, request),
() => undefined,
),
onSpanEnd: (span, request, response) =>
safeCallback(
DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',
() => integration?.onSpanEnd?.(span, request, response),
() => undefined,
),
};
}
Loading
Loading