Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hide internal fetches OTel traces in dev mode and assert duplicate OTel spans are present only in dev mode #47822

Merged
merged 17 commits into from Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/next/src/server/api-utils/node.ts
Expand Up @@ -529,6 +529,7 @@ export async function apiResolver(
res.once('pipe', () => (wasPiped = true))
}

getTracer().getRootSpanAttributes()?.set('next.route', page)
// Call API route method
const apiRouteResult = await getTracer().trace(
NodeSpan.runHandler,
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/server/app-render/app-render.tsx
Expand Up @@ -1226,6 +1226,7 @@ export async function renderToHTMLOrFlight(
)
}

getTracer().getRootSpanAttributes()?.set('next.route', pathname)
const bodyResult = getTracer().wrap(
AppRenderSpan.getBodyResult,
{
Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/server/base-server.ts
Expand Up @@ -543,6 +543,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
'http.method': method,
'http.target': req.url,
},
// We will fire this from the renderer worker
hideSpan: this.serverOptions.dev && this.isRouterWorker,
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
Expand All @@ -568,11 +570,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {

const route = rootSpanAttributes.get('next.route')
if (route) {
const newName = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': newName,
})
span.updateName(`${method} ${route}`)
span.updateName(newName)
}
})
)
Expand Down
12 changes: 4 additions & 8 deletions packages/next/src/server/dev/next-dev-server.ts
Expand Up @@ -136,7 +136,7 @@ export default class DevServer extends Server {
private edgeFunctions?: RoutingItem[]
private verifyingTypeScript?: boolean
private usingTypeScript?: boolean
private originalFetch?: typeof fetch
private originalFetch: typeof fetch
private staticPathsCache: LRUCache<
string,
UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>
Expand Down Expand Up @@ -187,7 +187,7 @@ export default class DevServer extends Server {
Error.stackTraceLimit = 50
} catch {}
super({ ...options, dev: true })
this.persistPatchedGlobals()
this.originalFetch = global.fetch
this.renderOpts.dev = true
this.renderOpts.appDirDevErrorLogger = (err: any) =>
this.logErrorWithOriginalStack(err, 'app-dir')
Expand Down Expand Up @@ -1257,7 +1257,7 @@ export default class DevServer extends Server {
private async invokeIpcMethod(method: string, args: any[]): Promise<any> {
const ipcPort = process.env.__NEXT_PRIVATE_ROUTER_IPC_PORT
if (ipcPort) {
const res = await fetch(
const res = await this.originalFetch(
`http://${this.hostname}:${ipcPort}?method=${
method as string
}&args=${encodeURIComponent(JSON.stringify(args))}`
Expand Down Expand Up @@ -1703,12 +1703,8 @@ export default class DevServer extends Server {
return nextInvoke as NonNullable<typeof result>
}

private persistPatchedGlobals(): void {
this.originalFetch = global.fetch
}

private restorePatchedGlobals(): void {
global.fetch = this.originalFetch!
global.fetch = this.originalFetch
}

protected async ensurePage(opts: {
Expand Down
Expand Up @@ -320,13 +320,13 @@ export class AppRouteRouteModule extends RouteModule<
}
)

const route = getPathnameFromAbsolutePath(this.resolvedPagePath)
getTracer().getRootSpanAttributes()?.set('next.route', route)
return getTracer().trace(
AppRouteRouteHandlersSpan.runHandler,
{
// TODO: propagate this pathname from route matcher
spanName: `executing api route (app) ${getPathnameFromAbsolutePath(
this.resolvedPagePath
)}`,
spanName: `executing api route (app) ${route}`,
},
() =>
handler(wrappedRequest, {
Expand Down
6 changes: 4 additions & 2 deletions packages/next/src/server/lib/trace/tracer.ts
Expand Up @@ -41,6 +41,7 @@ type TracerSpanOptions = Omit<SpanOptions, 'attributes'> & {
parentSpan?: Span
spanName?: string
attributes?: Partial<Record<AttributeNames, AttributeValue | undefined>>
hideSpan?: boolean
}

interface NextTracer {
Expand Down Expand Up @@ -201,8 +202,9 @@ class NextTracerImpl implements NextTracer {
}

if (
!NextVanillaSpanAllowlist.includes(type) &&
process.env.NEXT_OTEL_VERBOSE !== '1'
(!NextVanillaSpanAllowlist.includes(type) &&
process.env.NEXT_OTEL_VERBOSE !== '1') ||
options.hideSpan
) {
return fn()
}
Expand Down
9 changes: 7 additions & 2 deletions packages/next/src/server/next-server.ts
Expand Up @@ -1054,13 +1054,18 @@ export default class NextNodeServer extends BaseServer {
params: Params | null
isAppPath: boolean
}): Promise<FindComponentsResult | null> {
getTracer().getRootSpanAttributes()?.set('next.route', pathname)
let route = pathname
if (isAppPath) {
// When in App we get page instead of route
route = pathname.replace(/\/[^/]*$/, '')
}

return getTracer().trace(
NextNodeServerSpan.findPageComponents,
{
spanName: `resolving page into components`,
attributes: {
'next.route': pathname,
'next.route': route,
},
},
() => this.findPageComponentsImpl({ pathname, query, params, isAppPath })
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/server/render.tsx
Expand Up @@ -1361,6 +1361,7 @@ export async function renderToHTML(
}
}

getTracer().getRootSpanAttributes()?.set('next.route', renderOpts.pathname)
const documentResult = await getTracer().trace(
RenderSpan.renderDocument,
{
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/opentelemetry/instrumentation-node-test.ts
@@ -1,11 +1,11 @@
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import {
NodeTracerProvider,
SimpleSpanProcessor,
SpanExporter,
ReadableSpan,
} from '@opentelemetry/sdk-trace-node'
} from '@opentelemetry/sdk-trace-base'
import {
ExportResult,
ExportResultCode,
Expand Down
6 changes: 2 additions & 4 deletions test/e2e/opentelemetry/instrumentation-node.ts
@@ -1,9 +1,7 @@
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import {
NodeTracerProvider,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-node'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'

// You can use gRPC exporter instead
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
Expand Down