Files
next.js/test/e2e/opentelemetry/instrumentation/instrumentation-custom-server.ts
f5f2660cba fix: support root span attributes with a custom server (#85521)
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

Fixes #85520

When there is an active context from a custom server, the handleRequest
span is not marked as a root span. As a result next.js does not track
any root span attributes on the handleRequest span.
Because the custom server does not know what route was matched by next
and next is not tracking the route that matched this makes observability
very challenging for users of a custom server.

This PR changes the isRootSpan logic to treat the handleRequest span as
a root span if there is not already a nextjs root span for the request
instead of whether there is any active span.

---------

Co-authored-by: JJ Kasper <[email protected]>
2025-11-07 15:43:26 -08:00

108 lines
2.8 KiB
TypeScript

import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
import {
ExportResult,
ExportResultCode,
hrTimeToMicroseconds,
} from '@opentelemetry/core'
import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base'
interface SerializedSpan {
runtime: string | undefined
traceId: string
parentId: string | undefined
traceState: string | undefined
name: string
id: string
kind: number
timestamp: number
duration: number
attributes: Record<string, unknown>
status: { code: number; message?: string }
events: ReadableSpan['events']
links: ReadableSpan['links']
}
const serializeSpan = (span: ReadableSpan): SerializedSpan => ({
runtime: process.env.NEXT_RUNTIME,
traceId: span.spanContext().traceId,
parentId: span.parentSpanId,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: hrTimeToMicroseconds(span.startTime),
duration: hrTimeToMicroseconds(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
})
class TestExporter implements SpanExporter {
private port: string
constructor(port: string) {
this.port = port
}
async export(
spans: ReadableSpan[],
resultCallback: (result: ExportResult) => void
): Promise<void> {
try {
const response = await fetch(`http://localhost:${this.port}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(spans.map(serializeSpan)),
})
try {
await response.arrayBuffer()
} catch (e) {
// ignore
}
if (response.status >= 400) {
console.warn('WARN: TestExporter: response status:', response.status)
return resultCallback({
code: ExportResultCode.FAILED,
error: new Error(`http status ${response.status}`),
})
}
} catch (e) {
console.warn('WARN: TestExporter: error:', e)
return resultCallback({
code: ExportResultCode.FAILED,
error: e as Error,
})
}
resultCallback({ code: ExportResultCode.SUCCESS })
}
shutdown(): Promise<void> {
return Promise.resolve()
}
}
export function register() {
const provider = new NodeTracerProvider({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'custom-server-test',
}),
})
const port = process.env.TEST_OTEL_COLLECTOR_PORT
if (!port) {
throw new Error('TEST_OTEL_COLLECTOR_PORT is not set')
}
provider.addSpanProcessor(new SimpleSpanProcessor(new TestExporter(port)))
provider.register()
}