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

Fix telemetry span duration for request spans #70908

Open
wants to merge 3 commits into
base: canary
Choose a base branch
from
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
26 changes: 20 additions & 6 deletions packages/next/src/server/api-utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IncomingMessage } from 'http'
import type { IncomingMessage, ServerResponse } from 'http'
import type { BaseNextRequest } from '../base-http'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { NextApiResponse } from '../../shared/lib/utils'
Expand All @@ -20,19 +20,33 @@ export type __ApiPreviewProps = {
previewModeSigningKey: string
}

export function wrapApiHandler<T extends (...args: any[]) => any>(
page: string,
handler: T
): T {
export function wrapApiHandler<
T extends (
...args: [req: IncomingMessage, res: ServerResponse, ...any[]]
) => any,
>(page: string, handler: T): T {
return ((...args) => {
getTracer().setRootSpanAttribute('next.route', page)
// Call API route method
return getTracer().trace(
NodeSpan.runHandler,
{
spanName: `executing api route (pages) ${page}`,
manualSpanEnd: true,
},
() => handler(...args)
(span) => {
if (span) {
const res = args[1]
res.end = new Proxy(res.end, {
apply(target, thisArg, argArray) {
Copy link
Member

Choose a reason for hiding this comment

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

Is there no res.on('end', ...)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Correct me if I am wrong, but res.on('end') will not work on Vercel because the underlying lambdas freeze on res.end() which happens before res.on('end').

If that is not the case anymore it would be amazing because it would simplify the code here a lot.

span.end()
return target.apply(thisArg, argArray as any)
},
})
}

return handler(...args)
}
)
}) as T
}
Expand Down
7 changes: 7 additions & 0 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -897,9 +897,16 @@ export default abstract class Server<
'http.method': method,
'http.target': req.url,
},
manualSpanEnd: true,
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
res.onClose(() => {
if (span) {
span.end()
}
})

if (!span) return

const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
Expand Down
24 changes: 17 additions & 7 deletions packages/next/src/server/lib/trace/tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function isBubbledError(error: unknown): error is BubbledError {
return error instanceof BubbledError
}

const closeSpanWithError = (span: Span, error?: Error) => {
const recordErrorOnSpan = (span: Span, error?: Error) => {
if (isBubbledError(error) && error.bubble) {
span.setAttribute('next.bubble', true)
} else {
Expand All @@ -58,14 +58,14 @@ const closeSpanWithError = (span: Span, error?: Error) => {
}
span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message })
}
span.end()
}

type TracerSpanOptions = Omit<SpanOptions, 'attributes'> & {
parentSpan?: Span
spanName?: string
attributes?: Partial<Record<AttributeNames, AttributeValue | undefined>>
hideSpan?: boolean
manualSpanEnd?: boolean
}

interface NextTracer {
Expand Down Expand Up @@ -332,6 +332,12 @@ class NextTracerImpl implements NextTracer {
}
}

const endSpan = () => {
if (!options.manualSpanEnd) {
span.end()
}
}

if (isRootSpan) {
rootSpanAttributesStore.set(
spanId,
Expand All @@ -345,32 +351,36 @@ class NextTracerImpl implements NextTracer {
}
try {
if (fn.length > 1) {
return fn(span, (err) => closeSpanWithError(span, err))
return fn(span, (err) => {
recordErrorOnSpan(span, err)
endSpan()
})
}

const result = fn(span)
if (isThenable(result)) {
// If there's error make sure it throws
return result
.then((res) => {
span.end()
// Need to pass down the promise result,
// it could be react stream response with error { error, stream }
return res
})
.catch((err) => {
closeSpanWithError(span, err)
recordErrorOnSpan(span, err)
endSpan()
throw err
})
.finally(onCleanup)
} else {
span.end()
endSpan()
onCleanup()
}

return result
} catch (err: any) {
closeSpanWithError(span, err)
recordErrorOnSpan(span, err)
endSpan()
onCleanup()
throw err
}
Expand Down
Loading