diff --git a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts index ca34ff88baf8..e4293aa20ea9 100644 --- a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts +++ b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts @@ -21,27 +21,47 @@ describe('hono-sdk (Node)', () => { }); createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - // All cases in one test, because each `test()` starts its own Node process. - test('names each request after the route of the handler that responded', async () => { - const runner = createRunner().unordered(); - for (const { name, route } of ROUTE_NAME_CASES) { - runner.expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === name); - if (!segment) { - throw new Error(`segment for \`${name}\` not in this container`); - } - expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route }); - expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); - }, - }); - } + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ + ...ROUTE_NAME_CASES, + { method: 'get', path: '/does-not-exist', expectError: true }, + { method: 'get', path: '/' }, + { method: 'get', path: '/hello/world' }, + ]; + const runner = createRunner().expect({ + event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' }, + }); + const collectors = requests.map(({ path }) => { + const key = path; + return [ + key, + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key), + ] as const; + }); const started = runner.start(); - for (const { method, path } of ROUTE_NAME_CASES) { - await started.makeRequest(method, path); + for (const { method, path, expectError } of requests) { + await started.makeRequest(method, path, { expectError }); } await started.completed(); + return new Map(await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const))); + } + async function getScenario(key: string) { + scenario ??= runScenario(); + return (await scenario).get(key)!; + } + + test('names each request after the route of the handler that responded', async () => { + for (const { path, name, route } of ROUTE_NAME_CASES) { + const container = await getScenario(path); + const segment = container.items.find(item => item.is_segment && item.name === name); + if (!segment) { + throw new Error(`segment for \`${name}\` not in this container`); + } + expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route }); + expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); + } }); test('names an event captured in a route handler after that route', async () => { @@ -54,19 +74,12 @@ describe('hono-sdk (Node)', () => { }); test('keeps the runtime name for a request without a route', async () => { - const runner = createRunner() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment); - expect(segment?.name).toBe('GET'); - expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' }); - expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' }); - expect(segment?.attributes?.['http.route']).toBeUndefined(); - }, - }) - .start(); - runner.makeRequest('get', '/does-not-exist', { expectError: true }); - await runner.completed(); + const container = await getScenario('/does-not-exist'); + const segment = container.items.find(item => item.is_segment); + expect(segment?.name).toBe('GET'); + expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' }); + expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' }); + expect(segment?.attributes?.['http.route']).toBeUndefined(); }); test('names an event from the route handler that runs after next() after that route', async () => { @@ -93,40 +106,26 @@ describe('hono-sdk (Node)', () => { }); test('creates a segment span for a basic GET request', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'GET /', - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/'); - await runner.completed(); + const container = await getScenario('/'); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'GET /', + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + }), + }); }); test('creates a segment span with a parametrized route name', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'GET /hello/:name', - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/hello/world'); - await runner.completed(); + const container = await getScenario('/hello/world'); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'GET /hello/:name', + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + }), + }); }); test('captures an error with the correct mechanism', async () => { diff --git a/dev-packages/node-integration-tests/suites/hono/test.ts b/dev-packages/node-integration-tests/suites/hono/test.ts index d836673a101e..2ccb6a2f24f8 100644 --- a/dev-packages/node-integration-tests/suites/hono/test.ts +++ b/dev-packages/node-integration-tests/suites/hono/test.ts @@ -56,18 +56,40 @@ describe('hono auto-instrumentation', () => { }); createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - // All cases in one test, because each `test()` starts its own Node process. - test('names each request after the route of the handler that responded', async () => { + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post'; path: string; expectError?: boolean }> = [ + ...ROUTE_NAME_CASES, + { method: 'get', path: '/traced/1' }, + { method: 'get', path: '/does-not-exist', expectError: true }, + { method: 'get', path: '/' }, + { method: 'get', path: '/hello/world' }, + { method: 'get', path: '/arity-two-handler' }, + { method: 'get', path: '/test-basepath-mw/hello' }, + { method: 'get', path: '/sub/hello' }, + { method: 'get', path: '/outer/self-watering-plant' }, + ]; + const uniqueRequests = new Map(requests.map(request => [request.path, request])); const runner = createRunner().unordered(); - for (const { name, route } of ROUTE_NAME_CASES) { - runner.expect(segmentNamed(name, route)); - } - + const collectors = [...uniqueRequests.keys()].map( + path => [path, runner.collectStreamedSpansUntilSegment(span => attr(span, 'url.path') === path)] as const, + ); const started = runner.start(); - for (const { method, path } of ROUTE_NAME_CASES) { - await started.makeRequest(method, path); + for (const { method, path, expectError } of uniqueRequests.values()) { + await started.makeRequest(method, path, { expectError }); } await started.completed(); + return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); + } + async function getSpans(path: string) { + scenario ??= runScenario(); + return (await scenario).get(path)!; + } + + test('names each request after the route of the handler that responded', async () => { + for (const { path, name, route } of ROUTE_NAME_CASES) { + segmentNamed(name, route).span({ items: await getSpans(path) }); + } }); test('names an event captured in a route handler after that route', async () => { @@ -80,41 +102,25 @@ describe('hono auto-instrumentation', () => { }); test('does not rename a span that a middleware starts around the route handler', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id'); - if (!segment) { - throw new Error('segment for `GET /traced/:id` not in this container'); - } - expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1); - }, - }) - .start(); - runner.makeRequest('get', '/traced/1'); - await runner.completed(); + const container = { items: await getSpans('/traced/1') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id'); + if (!segment) { + throw new Error('segment for `GET /traced/:id` not in this container'); + } + expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1); }); test('keeps the runtime name for a request without a route', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find( - item => item.is_segment && attr(item, 'url.path') === '/does-not-exist', - ); - if (!segment) { - throw new Error('segment for `/does-not-exist` not in this container'); - } - expect(segment.name).toBe('GET'); - expect(attr(segment, 'sentry.segment.name.source')).toBe('url'); - expect(attr(segment, 'http.route')).toBeUndefined(); - }, - }) - .start(); - runner.makeRequest('get', '/does-not-exist', { expectError: true }); - await runner.completed(); + const container = { items: await getSpans('/does-not-exist') }; + + const segment = container.items.find(item => item.is_segment && attr(item, 'url.path') === '/does-not-exist'); + if (!segment) { + throw new Error('segment for `/does-not-exist` not in this container'); + } + expect(segment.name).toBe('GET'); + expect(attr(segment, 'sentry.segment.name.source')).toBe('url'); + expect(attr(segment, 'http.route')).toBeUndefined(); }); test('names an event from the route handler that runs after next() after that route', async () => { @@ -141,39 +147,25 @@ describe('hono auto-instrumentation', () => { }); test('creates a transaction for a basic GET request', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /'); - if (!segment) { - throw new Error('segment for `GET /` not in this container'); - } - expect(op(segment)).toBe('http.server'); - expect(segment.status).toBe('ok'); - }, - }) - .start(); - runner.makeRequest('get', '/'); - await runner.completed(); + const container = { items: await getSpans('/') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /'); + if (!segment) { + throw new Error('segment for `GET /` not in this container'); + } + expect(op(segment)).toBe('http.server'); + expect(segment.status).toBe('ok'); }); test('creates a transaction with a parametrized route name', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name'); - if (!segment) { - throw new Error('segment for `GET /hello/:name` not in this container'); - } - expect(op(segment)).toBe('http.server'); - expect(attr(segment, 'sentry.segment.name.source')).toBe('route'); - }, - }) - .start(); - runner.makeRequest('get', '/hello/world'); - await runner.completed(); + const container = { items: await getSpans('/hello/world') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name'); + if (!segment) { + throw new Error('segment for `GET /hello/:name` not in this container'); + } + expect(op(segment)).toBe('http.server'); + expect(attr(segment, 'sentry.segment.name.source')).toBe('route'); }); test('captures an error with the correct mechanism', async () => { @@ -221,97 +213,67 @@ describe('hono auto-instrumentation', () => { }); test('does not wrap a route handler declared with an unused next param as middleware', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler'); - if (!segment) { - throw new Error('segment for `GET /arity-two-handler` not in this container'); - } - // The arity-2 handler is the route handler (last in its method+path group), so it must not - // produce a middleware span. - const middlewareSpans = container.items.filter(item => op(item) === 'middleware'); - expect(middlewareSpans).toHaveLength(0); - }, - }) - .start(); - runner.makeRequest('get', '/arity-two-handler'); - await runner.completed(); + const container = { items: await getSpans('/arity-two-handler') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler'); + if (!segment) { + throw new Error('segment for `GET /arity-two-handler` not in this container'); + } + // The arity-2 handler is the route handler (last in its method+path group), so it must not + // produce a middleware span. + const middlewareSpans = container.items.filter(item => op(item) === 'middleware'); + expect(middlewareSpans).toHaveLength(0); }); test('creates a middleware span for .use() on a .basePath() clone', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find( - item => item.is_segment && item.name === 'GET /test-basepath-mw/hello', - ); - if (!segment) { - throw new Error('segment for `GET /test-basepath-mw/hello` not in this container'); - } - const middlewareSpan = container.items.find( - item => op(item) === 'middleware' && item.name === 'basepathMiddleware', - ); - expect(middlewareSpan).toBeDefined(); - expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono'); - }, - }) - .start(); - runner.makeRequest('get', '/test-basepath-mw/hello'); - await runner.completed(); + const container = { items: await getSpans('/test-basepath-mw/hello') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /test-basepath-mw/hello'); + if (!segment) { + throw new Error('segment for `GET /test-basepath-mw/hello` not in this container'); + } + const middlewareSpan = container.items.find( + item => op(item) === 'middleware' && item.name === 'basepathMiddleware', + ); + expect(middlewareSpan).toBeDefined(); + expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono'); }); test('does not create a middleware span for the Sentry middleware in a mounted sub-app', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello'); - if (!segment) { - throw new Error('segment for `GET /sub/hello` not in this container'); - } - const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); - // The sub-app's user middleware is traced … - expect(middlewareNames).toContain('subMiddleware'); - // … but the sub-app's own auto-registered Sentry middleware must not appear as a span - // (it is copied into the parent at mount time and must stay unwrapped). - expect(middlewareNames).not.toContain(''); - }, - }) - .start(); - runner.makeRequest('get', '/sub/hello'); - await runner.completed(); + const container = { items: await getSpans('/sub/hello') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello'); + if (!segment) { + throw new Error('segment for `GET /sub/hello` not in this container'); + } + const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); + // The sub-app's user middleware is traced … + expect(middlewareNames).toContain('subMiddleware'); + // … but the sub-app's own auto-registered Sentry middleware must not appear as a span + // (it is copied into the parent at mount time and must stay unwrapped). + expect(middlewareNames).not.toContain(''); }); test('traces an internal .request() call without the inner app re-instrumenting the request', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - // Transaction is named after the outer route, not the internal one. - const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId'); - if (!segment) { - throw new Error('segment for `GET /outer/:itemId` not in this container'); - } + const container = { items: await getSpans('/outer/self-watering-plant') }; - // The internal dispatch is traced with the raw inner path — the inner app's Sentry - // middleware must not re-name it to the parametrized route. - const internalRequestSpans = container.items.filter( - item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request', - ); - expect(internalRequestSpans).toHaveLength(1); - expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant'); + // Transaction is named after the outer route, not the internal one. + const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId'); + if (!segment) { + throw new Error('segment for `GET /outer/:itemId` not in this container'); + } - // The inner app's Sentry middleware must not add a middleware span. - const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); - expect(middlewareNames).not.toContain(''); - }, - }) - .start(); - runner.makeRequest('get', '/outer/self-watering-plant'); - await runner.completed(); + // The internal dispatch is traced with the raw inner path — the inner app's Sentry + // middleware must not re-name it to the parametrized route. + const internalRequestSpans = container.items.filter( + item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request', + ); + expect(internalRequestSpans).toHaveLength(1); + expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant'); + + // The inner app's Sentry middleware must not add a middleware span. + const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); + expect(middlewareNames).not.toContain(''); }); test('captures an error thrown inside an internal .request() even when the outer handler degrades to 200', async () => { diff --git a/dev-packages/node-integration-tests/suites/tracing/fastify/test.ts b/dev-packages/node-integration-tests/suites/tracing/fastify/test.ts index aa54d6195b7e..17b3b5c45d5d 100644 --- a/dev-packages/node-integration-tests/suites/tracing/fastify/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/fastify/test.ts @@ -7,62 +7,89 @@ describe('fastify v5 auto-instrumentation', () => { }); createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ + { method: 'get', path: '/test-transaction' }, + { method: 'get', path: '/test-outgoing-fetch/123' }, + ]; + const runner = createRunner(); + const collectors = requests.map(({ path }) => { + const key = path; + return [ + key, + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key), + ] as const; + }); + const responses = new Map } | undefined>(); + const started = runner.start(); + for (const { method, path, expectError } of requests) { + responses.set( + path, + await started.makeRequest<{ headers: Record }>(method, path, { expectError }), + ); + } + await started.completed(); + return new Map( + await Promise.all( + collectors.map(async ([key, spans]) => [key, { items: await spans, response: responses.get(key) }] as const), + ), + ); + } + async function getScenario(key: string) { + scenario ??= runScenario(); + return (await scenario).get(key)!; + } + test('creates segment span with fastify hook, request-handler and manual spans', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe('GET /test-transaction'); + const container = await getScenario('/test-transaction'); + expect(container.items.find(item => item.is_segment)?.name).toBe('GET /test-transaction'); - expect(container.items).toContainEqual( - expect.objectContaining({ - attributes: expect.objectContaining({ - 'fastify.type': { type: 'string', value: 'hook' }, - 'sentry.op': { type: 'string', value: 'middleware' }, - 'sentry.origin': { type: 'string', value: 'auto.http.fastify' }, - }), - }), - ); + expect(container.items).toContainEqual( + expect.objectContaining({ + attributes: expect.objectContaining({ + 'fastify.type': { type: 'string', value: 'hook' }, + 'sentry.op': { type: 'string', value: 'middleware' }, + 'sentry.origin': { type: 'string', value: 'auto.http.fastify' }, + }), + }), + ); - // Route-level hooks have no `op`, so the span name falls back to `${hook} - ${handler}` - // using the original hook identifier (not the prefixed `hook.name` attribute). - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'preHandler - routePreHandler', - attributes: expect.objectContaining({ - 'fastify.type': { type: 'string', value: 'route-hook' }, - 'hook.callback.name': { type: 'string', value: 'routePreHandler' }, - 'sentry.origin': { type: 'string', value: 'auto.http.fastify' }, - }), - }), - ); + // Route-level hooks have no `op`, so the span name falls back to `${hook} - ${handler}` + // using the original hook identifier (not the prefixed `hook.name` attribute). + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'preHandler - routePreHandler', + attributes: expect.objectContaining({ + 'fastify.type': { type: 'string', value: 'route-hook' }, + 'hook.callback.name': { type: 'string', value: 'routePreHandler' }, + 'sentry.origin': { type: 'string', value: 'auto.http.fastify' }, + }), + }), + ); - // The request span and the route handler span are both named after the route. - const handlerSpans = container.items.filter(item => item.attributes['sentry.op']?.value === 'handler'); - expect(handlerSpans).toHaveLength(2); - for (const span of handlerSpans) { - expect(span.name).toBe('/test-transaction'); - // The name has to stay in step with the attribute it comes from. - expect(span.attributes['http.route']?.value).toBe('/test-transaction'); - expect(span.attributes['sentry.origin']?.value).toBe('auto.http.fastify'); - } + // The request span and the route handler span are both named after the route. + const handlerSpans = container.items.filter(item => item.attributes['sentry.op']?.value === 'handler'); + expect(handlerSpans).toHaveLength(2); + for (const span of handlerSpans) { + expect(span.name).toBe('/test-transaction'); + // The name has to stay in step with the attribute it comes from. + expect(span.attributes['http.route']?.value).toBe('/test-transaction'); + expect(span.attributes['sentry.origin']?.value).toBe('auto.http.fastify'); + } - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'test-span', - attributes: expect.objectContaining({ 'sentry.origin': { type: 'string', value: 'manual' } }), - }), - ); - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'child-span', - attributes: expect.objectContaining({ 'sentry.origin': { type: 'string', value: 'manual' } }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/test-transaction'); - await runner.completed(); + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'test-span', + attributes: expect.objectContaining({ 'sentry.origin': { type: 'string', value: 'manual' } }), + }), + ); + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'child-span', + attributes: expect.objectContaining({ 'sentry.origin': { type: 'string', value: 'manual' } }), + }), + ); }); test('captures errors thrown in route handlers', async () => { @@ -100,8 +127,7 @@ describe('fastify v5 auto-instrumentation', () => { }); test('propagates trace data to outgoing requests within a request handler', async () => { - const runner = createRunner().start(); - const response = await runner.makeRequest<{ headers: Record }>('get', '/test-outgoing-fetch/123'); + const { response } = await getScenario('/test-outgoing-fetch/123'); expect(response?.headers?.['sentry-trace']).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-1$/); expect(response?.headers?.['baggage']).toEqual(expect.any(String)); diff --git a/dev-packages/node-integration-tests/suites/tracing/hapi/test.ts b/dev-packages/node-integration-tests/suites/tracing/hapi/test.ts index c608ea2cbfac..59be2069fe1b 100644 --- a/dev-packages/node-integration-tests/suites/tracing/hapi/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/hapi/test.ts @@ -34,95 +34,96 @@ describe('hapi auto-instrumentation', () => { ] as const; createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - test('should record the request method for multi-method and wildcard routes.', async () => { - const runner = createRunner().unordered(); - for (const { method, path } of MULTI_METHOD_REQUESTS) { - const httpMethod = method.toUpperCase(); - runner.expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe(`${httpMethod} ${path}`); + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ + ...MULTI_METHOD_REQUESTS, + { method: 'get', path: '/' }, + { method: 'get', path: '/plugin-route' }, + ]; + const runner = createRunner(); + const collectors = requests.map(({ method, path }) => { + const key = `${method.toUpperCase()} ${path}`; + return [key, runner.collectStreamedSpansUntilSegment(key)] as const; + }); - const routerSpans = container.items.filter(item => item.attributes[SENTRY_OP]?.value === ROUTER); - expect(routerSpans).toHaveLength(1); - expect(routerSpans[0]?.name).toBe(path); - expect(routerSpans[0]?.attributes[HTTP_REQUEST_METHOD]).toEqual({ type: 'string', value: httpMethod }); - }, - }); + const started = runner.start(); + for (const { method, path, expectError } of requests) { + await started.makeRequest(method, path, { expectError }); } + await started.completed(); + return new Map(await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const))); + } + async function getScenario(key: string) { + scenario ??= runScenario(); + return (await scenario).get(key)!; + } - const started = runner.start(); + test('should record the request method for multi-method and wildcard routes.', async () => { for (const { method, path } of MULTI_METHOD_REQUESTS) { - await started.makeRequest(method, path); + const httpMethod = method.toUpperCase(); + const container = await getScenario(`${httpMethod} ${path}`); + expect(container.items.find(item => item.is_segment)?.name).toBe(`${httpMethod} ${path}`); + + const routerSpans = container.items.filter(item => item.attributes[SENTRY_OP]?.value === ROUTER); + expect(routerSpans).toHaveLength(1); + expect(routerSpans[0]?.name).toBe(path); + expect(routerSpans[0]?.attributes[HTTP_REQUEST_METHOD]).toEqual({ type: 'string', value: httpMethod }); } - await started.completed(); }); test('should auto-instrument `@hapi/hapi` package.', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe('GET /'); + const container = await getScenario('GET /'); + expect(container.items.find(item => item.is_segment)?.name).toBe('GET /'); - // Router spans are named after the route alone, without the `GET ` prefix. - expect(container.items).toContainEqual( - expect.objectContaining({ - name: '/', - status: 'ok', - attributes: expect.objectContaining({ - 'http.route': { type: 'string', value: '/' }, - 'http.request.method': { type: 'string', value: 'GET' }, - 'hapi.type': { type: 'string', value: 'router' }, - 'sentry.origin': { type: 'string', value: origin }, - 'sentry.op': { type: 'string', value: 'router' }, - }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/'); - await runner.completed(); + // Router spans are named after the route alone, without the `GET ` prefix. + expect(container.items).toContainEqual( + expect.objectContaining({ + name: '/', + status: 'ok', + attributes: expect.objectContaining({ + 'http.route': { type: 'string', value: '/' }, + 'http.request.method': { type: 'string', value: 'GET' }, + 'hapi.type': { type: 'string', value: 'router' }, + 'sentry.origin': { type: 'string', value: origin }, + 'sentry.op': { type: 'string', value: 'router' }, + }), + }), + ); }); test('should instrument plugin routes and server extensions.', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe('GET /plugin-route'); + const container = await getScenario('GET /plugin-route'); + expect(container.items.find(item => item.is_segment)?.name).toBe('GET /plugin-route'); - const handlerSpan = container.items.find(item => item.attributes['sentry.op']?.value === 'handler'); - expect(handlerSpan).toMatchObject({ - // The route alone, without the `GET ` prefix the static name carried. - name: '/plugin-route', - attributes: expect.objectContaining({ - // The name has to stay in step with the attribute it comes from. - 'http.route': { type: 'string', value: '/plugin-route' }, - 'hapi.type': { type: 'string', value: 'plugin' }, - 'hapi.plugin.name': { type: 'string', value: 'testPlugin' }, - 'sentry.op': { type: 'string', value: 'handler' }, - 'sentry.origin': { type: 'string', value: origin }, - }), - }); + const handlerSpan = container.items.find(item => item.attributes['sentry.op']?.value === 'handler'); + expect(handlerSpan).toMatchObject({ + // The route alone, without the `GET ` prefix the static name carried. + name: '/plugin-route', + attributes: expect.objectContaining({ + // The name has to stay in step with the attribute it comes from. + 'http.route': { type: 'string', value: '/plugin-route' }, + 'hapi.type': { type: 'string', value: 'plugin' }, + 'hapi.plugin.name': { type: 'string', value: 'testPlugin' }, + 'sentry.op': { type: 'string', value: 'handler' }, + 'sentry.origin': { type: 'string', value: origin }, + }), + }); - // Spans of other ops keep their names. - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'ext - onPreResponse', - attributes: expect.objectContaining({ - [HAPI_TYPE]: { type: 'string', value: 'server.ext' }, - [HAPI_EXT_TYPE]: { type: 'string', value: 'onPreResponse' }, - // oxlint-disable-next-line typescript/no-deprecated - [SERVER_EXT_TYPE]: { type: 'string', value: 'onPreResponse' }, - 'sentry.op': { type: 'string', value: 'middleware' }, - 'sentry.origin': { type: 'string', value: origin }, - }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/plugin-route'); - await runner.completed(); + // Spans of other ops keep their names. + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'ext - onPreResponse', + attributes: expect.objectContaining({ + [HAPI_TYPE]: { type: 'string', value: 'server.ext' }, + [HAPI_EXT_TYPE]: { type: 'string', value: 'onPreResponse' }, + // oxlint-disable-next-line typescript/no-deprecated + [SERVER_EXT_TYPE]: { type: 'string', value: 'onPreResponse' }, + 'sentry.op': { type: 'string', value: 'middleware' }, + 'sentry.origin': { type: 'string', value: origin }, + }), + }), + ); }); test('should handle returned plain errors in routes.', async () => { diff --git a/dev-packages/node-integration-tests/suites/tracing/koa/test.ts b/dev-packages/node-integration-tests/suites/tracing/koa/test.ts index 4a9f99364a3a..1a9433b73b6d 100644 --- a/dev-packages/node-integration-tests/suites/tracing/koa/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/koa/test.ts @@ -38,66 +38,81 @@ describe('koa auto-instrumentation', () => { 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ + { method: 'get', path: '/' }, + { method: 'get', path: '/test-param/123' }, + ]; + const runner = createRunner(); + const collectors = requests.map(({ path }) => { + const key = path; + return [ + key, + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key), + ] as const; + }); + + const started = runner.start(); + for (const { method, path, expectError } of requests) { + await started.makeRequest(method, path, { expectError }); + } + await started.completed(); + return new Map( + await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const)), + ); + } + async function getScenario(key: string) { + scenario ??= runScenario(); + return (await scenario).get(key)!; + } + test('should auto-instrument `koa` router and middleware layers.', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe('GET /'); + const container = await getScenario('/'); + expect(container.items.find(item => item.is_segment)?.name).toBe('GET /'); - // Router layer span (from `@koa/router`), carrying the matched route. - expect(container.items).toContainEqual( - expect.objectContaining({ - name: '/', - attributes: expect.objectContaining({ - 'http.route': { type: 'string', value: '/' }, - 'koa.type': { type: 'string', value: 'router' }, - 'sentry.op': { type: 'string', value: 'router' }, - 'sentry.origin': { type: 'string', value: origin }, - }), - }), - ); + // Router layer span (from `@koa/router`), carrying the matched route. + expect(container.items).toContainEqual( + expect.objectContaining({ + name: '/', + attributes: expect.objectContaining({ + 'http.route': { type: 'string', value: '/' }, + 'koa.type': { type: 'string', value: 'router' }, + 'sentry.op': { type: 'string', value: 'router' }, + 'sentry.origin': { type: 'string', value: origin }, + }), + }), + ); - // Plain middleware span. - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'simpleMiddleware', - attributes: expect.objectContaining({ - 'koa.type': { type: 'string', value: 'middleware' }, - 'code.function.name': { type: 'string', value: 'simpleMiddleware' }, - 'sentry.op': { type: 'string', value: 'middleware' }, - 'sentry.origin': { type: 'string', value: origin }, - }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/'); - await runner.completed(); + // Plain middleware span. + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'simpleMiddleware', + attributes: expect.objectContaining({ + 'koa.type': { type: 'string', value: 'middleware' }, + 'code.function.name': { type: 'string', value: 'simpleMiddleware' }, + 'sentry.op': { type: 'string', value: 'middleware' }, + 'sentry.origin': { type: 'string', value: origin }, + }), + }), + ); }); test('should assign a parameterized segment name.', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)?.name).toBe('GET /test-param/:id'); + const container = await getScenario('/test-param/123'); + expect(container.items.find(item => item.is_segment)?.name).toBe('GET /test-param/:id'); - expect(container.items).toContainEqual( - expect.objectContaining({ - name: '/test-param/:id', - attributes: expect.objectContaining({ - 'http.route': { type: 'string', value: '/test-param/:id' }, - 'koa.type': { type: 'string', value: 'router' }, - 'sentry.op': { type: 'string', value: 'router' }, - 'sentry.origin': { type: 'string', value: origin }, - }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/test-param/123'); - await runner.completed(); + expect(container.items).toContainEqual( + expect.objectContaining({ + name: '/test-param/:id', + attributes: expect.objectContaining({ + 'http.route': { type: 'string', value: '/test-param/:id' }, + 'koa.type': { type: 'string', value: 'router' }, + 'sentry.op': { type: 'string', value: 'router' }, + 'sentry.origin': { type: 'string', value: origin }, + }), + }), + ); }); test('should capture errors thrown in routes via the koa error handler.', async () => {