Unverified Commit 93bb22ad authored by Alex Langenfeld's avatar Alex Langenfeld Committed by GitHub

Preserve committed app route response status during fallback (#98649)

### What?

A follow up to https://github.com/vercel/next.js/pull/94979, now we
check if response headers have already been sent before trying to send a
`500` response when falling back.

### Why?

To get streaming respnses that already sent status `200` headers from
reporting as `500`s in telemetry.

### How?

Skip the fallback `500` status response if headers have already been
sent.

---------
Signed-off-by: 's avatarAlex Langenfeld <alex.langenfeld@vercel.com>
parent 6130a493
......@@ -502,12 +502,31 @@ export async function handler(
// If this is during static generation, throw the error again.
if (isIsr) throw err
// Otherwise, send a 500 response.
await sendResponse(
nodeNextReq,
nodeNextRes,
new Response(null, { status: 500 })
)
// Otherwise, send a 500 response unless the original response has
// already committed. In that case, preserve its status code for
// telemetry while still recording the failure and terminating a response
// that the failed pipeline left open.
if (res.headersSent) {
if (currentSpan) {
const error =
err instanceof Error ? err : new Error('Unknown app route error')
currentSpan.recordException(error)
currentSpan.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
})
currentSpan.setAttribute('error.type', error.name)
}
if (!res.writableEnded && !res.destroyed) {
res.end()
}
} else {
await sendResponse(
nodeNextReq,
nodeNextRes,
new Response(null, { status: 500 })
)
}
return
} finally {
;(() => {
......
import { revalidateTag } from 'next/cache'
export function GET() {
revalidateTag('reject-after-headers', 'max')
return new Response('committed')
}
export const dynamic = 'force-dynamic'
export function GET() {
const encoder = new TextEncoder()
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode('committed'))
setTimeout(() => {
controller.error(new Error('app route stream error'))
}, 50)
},
})
)
}
export const dynamic = 'force-dynamic'
......@@ -45,6 +45,14 @@ async function main() {
const handlers: [RegExp, string][] = [
[/^\/api\/app\/param\/data$/, 'app/api/app/[param]/data/route.js'],
[/^\/api\/app\/param\/error$/, 'app/api/app/[param]/error/route.js'],
[
/^\/api\/app\/param\/revalidation-error$/,
'app/api/app/[param]/revalidation-error/route.js',
],
[
/^\/api\/app\/param\/stream-error$/,
'app/api/app/[param]/stream-error/route.js',
],
[/^\/api\/app\/param\/status$/, 'app/api/app/[param]/status/route.js'],
[/^\/app\/param\/loading\/error$/, 'app/app/[param]/loading/error/page.js'],
[/^\/app\/param\/loading\/page1$/, 'app/app/[param]/loading/page1/page.js'],
......@@ -99,6 +107,22 @@ async function main() {
createServer((req, res) => {
const method = req.method || 'GET'
const pathname = parse(req.url || '/', false).pathname || '/'
if (pathname === '/api/app/param/revalidation-error/reject') {
const rejectRevalidation = (globalThis as any)[
Symbol.for('next.test.reject-revalidation')
]
if (typeof rejectRevalidation !== 'function') {
res.statusCode = 409
res.end('No pending revalidation')
return
}
rejectRevalidation()
res.statusCode = 204
res.end()
return
}
const handler = resolveHandler<EntrypointHandler>(handlers, pathname)
const middlewareHandler = resolveHandler<MiddlewareHandler>(
middlewareHandlers,
......@@ -152,7 +176,11 @@ async function main() {
}
}
return await handler(req, res, { waitUntil })
return await handler(
req,
res,
pathname === '/api/app/param/revalidation-error' ? {} : { waitUntil }
)
}
// Simulate a custom parent span around direct entrypoint invocation.
......
const {
default: FileSystemCache,
} = require('next/dist/server/lib/incremental-cache/file-system-cache')
const REJECT_REVALIDATION = Symbol.for('next.test.reject-revalidation')
module.exports = class IncrementalCacheHandler extends FileSystemCache {
async revalidateTag(tags, durations) {
if (tags.includes('reject-after-headers')) {
return new Promise((_, reject) => {
globalThis[REJECT_REVALIDATION] = () => {
delete globalThis[REJECT_REVALIDATION]
reject(new Error('revalidation failed after headers'))
}
})
}
return super.revalidateTag(tags, durations)
}
}
export function onRequestError(error: unknown) {
if (
error instanceof Error &&
error.cause instanceof Error &&
error.cause.message === 'app route stream error'
) {
console.log('[instrumentation] observed app route stream error')
}
}
export async function register() {
const { register: registerForTest } = await import('./instrumentation-test')
......
module.exports = {}
module.exports = {
cacheHandler: require.resolve('./incremental-cache-handler'),
}
......@@ -616,6 +616,95 @@ describe.each(
])
})
it('should preserve the committed status when a route response stream errors', async () => {
const response = await next.fetch(
'/api/app/param/stream-error',
env.fetchInit
)
expect(response.status).toBe(200)
await expect(response.text()).rejects.toThrow()
await retry(() => {
expect(next.cliOutput).toContain(
'[instrumentation] observed app route stream error'
)
})
await expectTrace(getCollector(), [
{
name: 'GET /api/app/[param]/stream-error',
attributes: {
'http.method': 'GET',
'http.route': '/api/app/[param]/stream-error',
'http.status_code': 200,
'http.target': '/api/app/param/stream-error',
'next.route': '/api/app/[param]/stream-error',
'next.span_name': 'GET /api/app/[param]/stream-error',
'next.span_type': 'BaseServer.handleRequest',
'error.type': 'Error',
},
kind: 1,
status: { code: 2, message: 'failed to pipe response' },
traceId: env.span.traceId,
parentId: env.span.rootParentId,
spans: [
{
name: 'executing api route (app) /api/app/[param]/stream-error',
attributes: {
'next.route': '/api/app/[param]/stream-error',
'next.span_name':
'executing api route (app) /api/app/[param]/stream-error',
'next.span_type': 'AppRouteRouteHandlers.runHandler',
},
kind: 0,
status: { code: 0 },
},
...(useDirectEntrypointHandler
? []
: [
{
name: 'resolve page components',
attributes: {
'next.route': '/api/app/[param]/stream-error',
'next.span_name': 'resolve page components',
'next.span_type':
'NextNodeServer.findPageComponents',
},
kind: 0,
status: { code: 0 },
},
]),
{
name: 'start response',
attributes: {
'next.span_name': 'start response',
'next.span_type': 'NextNodeServer.startResponse',
},
kind: 0,
status: { code: 0 },
},
],
},
])
})
if (useDirectEntrypointHandler && env.name === 'root context') {
it('should end a committed response when pending revalidation fails', async () => {
const response = await next.fetch(
'/api/app/param/revalidation-error'
)
expect(response.status).toBe(200)
const rejectResponse = await next.fetch(
'/api/app/param/revalidation-error/reject'
)
expect(rejectResponse.status).toBe(204)
await expect(response.text()).resolves.toBe('committed')
})
}
it('should record accurate status code for non-200 route handler responses', async () => {
await next.fetch('/api/app/param/status', env.fetchInit)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment