Unverified Commit 74c6c1b6 authored by Darpan Kakadia's avatar Darpan Kakadia Committed by GitHub

fix: mark HTTP fetch failures as span errors (#99877)

## Problem

Fetch spans report HTTP failures without an error status.

## Solution

Mark recorded responses with status >= 400 as errors. Preserve response
bodies and streaming.

<!-- NEXT_JS_LLM -->
parent 93cec91d
...@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks' ...@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external' import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { CachedRouteKind } from '../response-cache'
import { createPatchedFetcher } from './patch-fetch' import { createPatchedFetcher } from './patch-fetch'
import { registerLocalSpanRecorder } from './trace/local-span-recorder' import { registerLocalSpanRecorder } from './trace/local-span-recorder'
import { import {
...@@ -163,4 +164,221 @@ describe('createPatchedFetcher', () => { ...@@ -163,4 +164,221 @@ describe('createPatchedFetcher', () => {
}), }),
]) ])
}) })
it.each(
[200, 201, 302, 399, 400, 404, 499, 500, 599, 600].flatMap((status) =>
[false, true].map((shouldTrackFetchMetrics) => ({
status,
shouldTrackFetchMetrics,
}))
)
)(
'records HTTP $status with fetch metrics=$shouldTrackFetchMetrics',
async ({ status, shouldTrackFetchMetrics }) => {
setSpanRecorderForTest((span) => spanRecords.push(span))
const originResponse = new Response('response body', {
status: Math.min(status, 599),
headers: { 'x-test-header': 'response header' },
})
if (status === 600) {
Object.defineProperty(originResponse, 'status', { value: status })
}
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockResolvedValue(originResponse)
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage: new AsyncLocalStorage<WorkUnitStore>(),
})
const workStore: Partial<WorkStore> = {
page: '/',
route: '/',
shouldTrackFetchMetrics,
}
const response = await workAsyncStorage.run(workStore as WorkStore, () =>
patchedFetch('https://example.com/api', { cache: 'no-store' })
)
expect(response).toBe(originResponse)
expect(response.status).toBe(status)
expect(response.headers.get('x-test-header')).toBe('response header')
expect(await response.text()).toBe('response body')
expect(spanRecords).toHaveLength(1)
const span = spanRecords[0]
const isHttpError = status >= 400
expect(span.status).toBe(isHttpError ? 'error' : 'ok')
expect(span.attributes?.['http.status_code']).toBe(status)
expect(span.attributes?.['error.type']).toBe(
isHttpError ? String(status) : undefined
)
expect(
(span.events ?? []).filter((event) => event.name === 'exception')
).toEqual([])
expect(span.error).toBeUndefined()
expect(workStore.fetchMetrics?.length ?? 0).toBe(
shouldTrackFetchMetrics ? 1 : 0
)
}
)
it.each([
{ cachedStatus: 404, originStatus: 200, isStale: false },
{ cachedStatus: 200, originStatus: 503, isStale: true },
])(
'classifies cached HTTP $cachedStatus with background HTTP $originStatus, stale=$isStale',
async ({ cachedStatus, originStatus, isStale }) => {
setSpanRecorderForTest((span) => spanRecords.push(span))
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockResolvedValue(
new Response('origin body', { status: originStatus })
)
const incrementalCache = {
get: jest.fn().mockResolvedValue({
isStale,
value: {
kind: CachedRouteKind.FETCH,
revalidate: 3600,
data: {
body: btoa('cached body'),
headers: {},
status: cachedStatus,
url: 'https://example.com/api',
},
},
}),
generateCacheKey: jest.fn().mockResolvedValue('test-cache-key'),
lock: jest.fn().mockResolvedValue(() => {}),
} as unknown as IncrementalCache
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage: new AsyncLocalStorage<WorkUnitStore>(),
})
const workStore: Partial<WorkStore> = {
page: '/',
route: '/',
incrementalCache,
}
const response = await workAsyncStorage.run(workStore as WorkStore, () =>
patchedFetch('https://example.com/api', { cache: 'force-cache' })
)
await Promise.all(Object.values(workStore.pendingRevalidates ?? {}))
expect(response.status).toBe(cachedStatus)
expect(await response.text()).toBe('cached body')
expect(mockFetch).toHaveBeenCalledTimes(isStale ? 1 : 0)
expect(spanRecords).toHaveLength(1)
expect(spanRecords[0].status).toBe(cachedStatus === 404 ? 'error' : 'ok')
expect(spanRecords[0].attributes?.['http.status_code']).toBe(cachedStatus)
expect(spanRecords[0].attributes?.['next.fetch.cache_status']).toBe('hit')
expect(spanRecords[0].attributes?.['error.type']).toBe(
cachedStatus === 404 ? '404' : undefined
)
expect(
(spanRecords[0].events ?? []).filter(
(event) => event.name === 'exception'
)
).toHaveLength(0)
expect(spanRecords[0].error).toBeUndefined()
}
)
it('records an HTTP error without buffering the response stream', async () => {
setSpanRecorderForTest((span) => spanRecords.push(span))
let controller!: ReadableStreamDefaultController<Uint8Array>
const readableStream = new ReadableStream<Uint8Array>({
start(streamController) {
controller = streamController
controller.enqueue(new TextEncoder().encode('stream start'))
},
})
const originResponse = new Response(readableStream, { status: 500 })
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockResolvedValue(originResponse)
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage: new AsyncLocalStorage<WorkUnitStore>(),
})
const response = await workAsyncStorage.run(
{ page: '/', route: '/' } as WorkStore,
() => patchedFetch('https://example.com/api', { cache: 'no-store' })
)
expect(response).toBe(originResponse)
expect(response.bodyUsed).toBe(false)
expect(spanRecords).toHaveLength(1)
expect(spanRecords[0].status).toBe('error')
controller.close()
expect(await response.text()).toBe('stream start')
}, 1000)
it('preserves the original exception when fetch rejects', async () => {
setSpanRecorderForTest((span) => spanRecords.push(span))
const error = new TypeError('fetch failed')
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockRejectedValue(error)
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage: new AsyncLocalStorage<WorkUnitStore>(),
})
await expect(
workAsyncStorage.run({ page: '/', route: '/' } as WorkStore, () =>
patchedFetch('https://example.com/api', { cache: 'no-store' })
)
).rejects.toBe(error)
expect(spanRecords).toHaveLength(1)
expect(spanRecords[0].status).toBe('error')
expect(spanRecords[0].attributes?.['error.type']).toBe('TypeError')
expect(spanRecords[0].events).toEqual([
expect.objectContaining({
name: 'exception',
attributes: {
'exception.type': 'TypeError',
'exception.message': 'fetch failed',
},
}),
])
})
it('returns HTTP error responses when fetch spans are disabled', async () => {
setSpanRecorderForTest((span) => spanRecords.push(span))
const originalOtelFetchDisabled = process.env.NEXT_OTEL_FETCH_DISABLED
process.env.NEXT_OTEL_FETCH_DISABLED = '1'
try {
const originResponse = new Response('response body', { status: 404 })
const mockFetch: jest.MockedFunction<typeof fetch> = jest.fn()
mockFetch.mockResolvedValue(originResponse)
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
workAsyncStorage,
workUnitAsyncStorage: new AsyncLocalStorage<WorkUnitStore>(),
})
const response = await workAsyncStorage.run(
{ page: '/', route: '/' } as WorkStore,
() => patchedFetch('https://example.com/api', { cache: 'no-store' })
)
expect(response).toBe(originResponse)
expect(await response.text()).toBe('response body')
expect(spanRecords).toEqual([])
} finally {
if (originalOtelFetchDisabled === undefined) {
delete process.env.NEXT_OTEL_FETCH_DISABLED
} else {
process.env.NEXT_OTEL_FETCH_DISABLED = originalOtelFetchDisabled
}
}
})
}) })
...@@ -9,7 +9,7 @@ import { ...@@ -9,7 +9,7 @@ import {
recordRequestInsightFetch, recordRequestInsightFetch,
} from './trace/request-insights' } from './trace/request-insights'
import { getRequestInsightsIdentity } from './trace/request-insights-identity' import { getRequestInsightsIdentity } from './trace/request-insights-identity'
import { getTracer, SpanKind } from './trace/tracer' import { getTracer, SpanKind, SpanStatusCode } from './trace/tracer'
import { import {
CACHE_ONE_YEAR_SECONDS, CACHE_ONE_YEAR_SECONDS,
INFINITE_CACHE, INFINITE_CACHE,
...@@ -186,6 +186,11 @@ function trackFetchMetric( ...@@ -186,6 +186,11 @@ function trackFetchMetric(
'next.fetch.cache_reason': metric.cacheReason, 'next.fetch.cache_reason': metric.cacheReason,
}) })
if (span && metric.status >= 400) {
span.setStatus({ code: SpanStatusCode.ERROR })
span.setAttribute('error.type', String(metric.status))
}
if (isRequestInsightsEnabled()) { if (isRequestInsightsEnabled()) {
const requestInsightsIdentity = getRequestInsightsIdentity() const requestInsightsIdentity = getRequestInsightsIdentity()
const requestInsightsRequestId = const requestInsightsRequestId =
......
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