From 742d842a89604b4f28c7105aab9ec1e4aec75e4b Mon Sep 17 00:00:00 2001 From: Andrei Borza Date: Tue, 1 Dec 2026 10:48:30 +0100 Subject: [PATCH] fix(server-utils): Skip Fastify spans for ignored incoming requests Co-Authored-By: Claude Fable 5.2 --- .../integrations/fastify/instrumentation.ts | 14 ++++++-- .../fastify/instrumentation.test.ts | 33 ++++++++++++++----- 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/packages/server-utils/src/integrations/fastify/instrumentation.ts b/packages/server-utils/src/integrations/fastify/instrumentation.ts index 63e801182f50..9aa9119f7eb5 100644 --- a/packages/server-utils/src/integrations/fastify/instrumentation.ts +++ b/packages/server-utils/src/integrations/fastify/instrumentation.ts @@ -169,6 +169,13 @@ function onRequest(this: any, request: any, _reply: any, hookDone: () => void): getIsolationScope().setTransactionName(`${method} ${routeName}`); + // No active parent span means this request is being ignored (e.g. via `ignoreIncomingRequests`), + // so don't open a span that would become the root of a new trace. + if (!getActiveSpan()) { + hookDone(); + return; + } + const attributes: Record = { [SENTRY_ORIGIN]: ORIGIN, [SENTRY_OP]: HANDLER, @@ -338,10 +345,11 @@ function handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined; - // A child of an unsampled span is never sampled either, so skip creating it. Hooks that run after - // the request span ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would. + // Without a parent span the request is being ignored, and a child of an unsampled span is never + // sampled either, so skip creating the span in both cases. Hooks that run after the request span + // ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would. const effectiveParentSpan = parentSpan ?? getActiveSpan(); - if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) { + if (!effectiveParentSpan || !spanIsSampled(effectiveParentSpan)) { return handler.call(this, ...args); } diff --git a/packages/server-utils/test/integrations/fastify/instrumentation.test.ts b/packages/server-utils/test/integrations/fastify/instrumentation.test.ts index c3b1a22aeda0..9cffafa26cfd 100644 --- a/packages/server-utils/test/integrations/fastify/instrumentation.test.ts +++ b/packages/server-utils/test/integrations/fastify/instrumentation.test.ts @@ -2,7 +2,7 @@ import { channel } from 'node:diagnostics_channel'; import { SENTRY_OP } from '@sentry/conventions/attributes'; import { HANDLER, MIDDLEWARE } from '@sentry/conventions/op'; import type { Span } from '@sentry/core'; -import { setCurrentClient, spanToJSON } from '@sentry/core'; +import { setCurrentClient, spanToJSON, startSpan } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { instrumentFastify } from '../../../src/integrations/fastify/instrumentation'; import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; @@ -45,6 +45,11 @@ function createRequest(): any { return { method: 'GET', url: '/users/1', routeOptions: { url: '/users/:id' } }; } +// Fastify handles a request within the `http.server` span of the HTTP integration. +function withServerSpan(callback: () => T): T { + return startSpan({ name: 'GET' }, callback); +} + // Runs the request lifecycle the way Fastify does: every later hook runs within the `onRequest` // callback, and the instrumentation's own `onResponse` hook ends the request span before user ones. function handleRequest(): void { @@ -77,11 +82,11 @@ describe('Fastify instrumentation', () => { it('does not start spans for hooks or the route handler', () => { const startedSpans = setUpClient(0); - handleRequest(); + withServerSpan(handleRequest); - expect(startedSpans).toHaveLength(1); - expect(spanToJSON(startedSpans[0]!).name).toBe('GET /users/:id'); - expect(startedSpans[0]!.isRecording()).toBe(false); + // The server span and the request span. + expect(startedSpans).toHaveLength(2); + expect(startedSpans[1]!.isRecording()).toBe(false); }); it('calls hooks with the original `this` and arguments and returns their result', () => { @@ -90,7 +95,7 @@ describe('Fastify instrumentation', () => { const hook = vi.fn(() => 'hook result'); instance.addHook('preHandler', hook); const request = createRequest(); - registeredHooks.onRequest![0]!.call(instance, request, {}, () => {}); + withServerSpan(() => registeredHooks.onRequest![0]!.call(instance, request, {}, () => {})); const reply = {}; const done = (): void => {}; @@ -113,7 +118,7 @@ describe('Fastify instrumentation', () => { throw asyncError; }); const request = createRequest(); - registeredHooks.onRequest![0]!.call(instance, request, {}, () => {}); + withServerSpan(() => registeredHooks.onRequest![0]!.call(instance, request, {}, () => {})); expect(() => registeredHooks.preHandler![0]!.call(instance, request, {}, () => {})).toThrow(syncError); await expect(registeredHooks.onSend![0]!.call(instance, request, {}, 'payload', () => {})).rejects.toBe( @@ -126,9 +131,9 @@ describe('Fastify instrumentation', () => { it('starts spans for hooks and the route handler as children of the request span', () => { const startedSpans = setUpClient(1); - handleRequest(); + withServerSpan(handleRequest); - const [requestSpan, ...childSpans] = startedSpans.map(span => spanToJSON(span)); + const [, requestSpan, ...childSpans] = startedSpans.map(span => spanToJSON(span)); expect(requestSpan).toMatchObject({ name: 'GET /users/:id' }); expect(childSpans).toEqual([ expect.objectContaining({ @@ -153,4 +158,14 @@ describe('Fastify instrumentation', () => { ]); }); }); + + describe('on requests without an active span', () => { + it('does not start spans', () => { + const startedSpans = setUpClient(1); + + handleRequest(); + + expect(startedSpans).toEqual([]); + }); + }); });