Unverified Commit 31b78bbe authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add Instant Insights request timing (#95958)

## Summary

- record deferred Instant Insights work as a separate typed Request
Insights item
- keep validation spans, fetches, timing, and live updates separate from
the foreground request
- label Instant Insights consistently in DevTools and CLI output
- stack this observability change on #95939, which moves validation off
the navigation response path

## Verification

- `pnpm jest --runInBand
packages/next/src/server/lib/trace/request-insights.test.ts
packages/next/src/server/lib/trace/local-span-recorder.test.ts
packages/next/src/next-devtools/dev-overlay/components/request-insights/trace-viewer.test.ts
packages/next/src/next-devtools/dev-overlay/shared.test.ts`
- `NEXT_SKIP_ISOLATE=1 NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/development/app-dir/request-insights/request-insights.test.ts`
- `NEXT_SKIP_ISOLATE=1 NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-webpack
test/development/app-dir/request-insights/request-insights.test.ts`
- `pnpm --filter=next types`

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarDavid Ilie <david@davidilie.com>
parent 33a09d53
......@@ -5,6 +5,7 @@ import type {
RequestInsight,
RequestInsightsSnapshot,
} from '../next-devtools/shared/request-insights'
import { getRequestInsightKind } from '../next-devtools/shared/request-insights'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import {
......@@ -77,10 +78,13 @@ export async function nextRequestInsights(
for (const request of visibleRequests) {
const route = request.route ?? request.url ?? request.requestId
const kind = getRequestInsightKind(request)
const duration = formatDuration(request.durationMs)
console.log(`${route} ${duration} ${request.status ?? 'pending'}`)
console.log(
` request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`
`${kind === 'instant-insights' ? `Instant Insights · ${route}` : route} ${duration} ${request.status ?? 'pending'}`
)
console.log(
` kind ${kind} request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`
)
const visibleFetches = request.fetches.slice(0, DEFAULT_FETCH_LIMIT)
......
......@@ -89,6 +89,16 @@
white-space: nowrap;
}
.request-insights-item-context {
min-width: 0;
overflow: hidden;
color: var(--color-gray-900);
font-size: var(--size-11);
font-weight: 400;
text-overflow: ellipsis;
white-space: nowrap;
}
.request-insights-duration,
.request-insights-meta {
color: var(--color-gray-900);
......
import { useMemo, useState } from 'react'
import type {
RequestInsight,
RequestInsightFetch,
import {
getRequestInsightKey,
getRequestInsightKind,
type RequestInsight,
type RequestInsightFetch,
} from '../../../shared/request-insights'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { CopyButton } from '../copy-button'
import { formatDuration } from './format-duration'
import { getActiveRequestId, isPageLoadRequest } from './request-list'
import { getActiveRequestKey, isPageLoadRequest } from './request-list'
import {
getTraceItems,
getTracePosition,
......@@ -23,12 +25,14 @@ export function RequestInsightsPanel() {
() => [...state.requestInsights].reverse(),
[state.requestInsights]
)
const [selectedRequestId, setSelectedRequestId] = useState<string | null>(
() => getActiveRequestId(requests, null)
const [selectedRequestKey, setSelectedRequestKey] = useState<string | null>(
() => getActiveRequestKey(requests, null)
)
const activeRequestId = getActiveRequestId(requests, selectedRequestId)
const activeRequestKey = getActiveRequestKey(requests, selectedRequestKey)
const selectedRequest =
requests.find((request) => request.requestId === activeRequestId) ?? null
requests.find(
(request) => getRequestInsightKey(request) === activeRequestKey
) ?? null
const initialRequestId = self.__next_r
if (requests.length === 0) {
......@@ -42,15 +46,18 @@ export function RequestInsightsPanel() {
return (
<div className="request-insights-panel">
<div className="request-insights-list">
{requests.map((request) => (
<RequestRow
key={request.requestId}
request={request}
pageLoad={isPageLoadRequest(request, initialRequestId)}
selected={request.requestId === activeRequestId}
onSelect={() => setSelectedRequestId(request.requestId)}
/>
))}
{requests.map((request) => {
const requestKey = getRequestInsightKey(request)
return (
<RequestRow
key={requestKey}
request={request}
pageLoad={isPageLoadRequest(request, initialRequestId)}
selected={requestKey === activeRequestKey}
onSelect={() => setSelectedRequestKey(requestKey)}
/>
)
})}
</div>
{selectedRequest && <RequestDetails request={selectedRequest} />}
......@@ -69,6 +76,10 @@ function RequestRow({
selected: boolean
onSelect: () => void
}) {
const isInstantInsights =
getRequestInsightKind(request) === 'instant-insights'
const route = request.route ?? request.url ?? 'Unknown route'
return (
<button
className="request-insights-row"
......@@ -80,9 +91,11 @@ function RequestRow({
<span className="request-insights-status" data-status={request.status} />
<span className="request-insights-route">
<span className="request-insights-route-label">
{request.route ?? request.url ?? 'Unknown route'}
{isInstantInsights ? 'Instant Insights' : route}
</span>
{pageLoad ? (
{isInstantInsights ? (
<span className="request-insights-item-context">{route}</span>
) : pageLoad ? (
<span className="request-insights-page-load">Page load</span>
) : null}
</span>
......@@ -116,7 +129,9 @@ function RequestDetails({ request }: { request: RequestInsight }) {
<div className="request-insights-heading">
<div className="request-insights-title-row">
<div className="request-insights-title">
{request.route ?? request.url ?? request.requestId}
{getRequestInsightKind(request) === 'instant-insights'
? `Instant Insights · ${request.route ?? request.url ?? request.requestId}`
: (request.route ?? request.url ?? request.requestId)}
</div>
<CopyButton
actionLabel="Copy request JSON"
......@@ -159,7 +174,7 @@ function RequestOverview({
}) {
return (
<div className="request-insights-overview">
<span>Method {overview.method}</span>
{overview.method ? <span>Method {overview.method}</span> : null}
<span>Status {overview.statusLabel}</span>
<span>{overview.kind}</span>
<span>{overview.fetchSummary}</span>
......@@ -316,10 +331,13 @@ function FetchTable({ fetches }: { fetches: RequestInsightFetch[] }) {
}
function getRequestOverview(request: RequestInsight) {
const method =
getFirstStringAttribute(request, 'http.method') ??
getMethodFromName(request.spans[0]?.name) ??
'GET'
const isInstantInsights =
getRequestInsightKind(request) === 'instant-insights'
const method = isInstantInsights
? undefined
: (getFirstStringAttribute(request, 'http.method') ??
getMethodFromName(request.spans[0]?.name) ??
'GET')
const statusCode = getFirstNumberAttribute(request, 'http.status_code')
const isRsc = getFirstBooleanAttribute(request, 'next.rsc')
const erroredSpan = request.spans.find(
......@@ -344,7 +362,11 @@ function getRequestOverview(request: RequestInsight) {
method,
statusCode,
statusLabel: statusCode ?? request.status,
kind: isRsc ? 'RSC request' : 'HTML request',
kind: isInstantInsights
? 'Instant Insights'
: isRsc
? 'RSC request'
: 'HTML request',
fetchSummary: request.fetches.length
? `${request.fetches.length} fetch${request.fetches.length === 1 ? '' : 'es'}`
: 'No fetches',
......
import type { RequestInsight } from '../../../shared/request-insights'
import {
getRequestInsightKey,
getRequestInsightKind,
type RequestInsight,
} from '../../../shared/request-insights'
export function getActiveRequestId(
export function getActiveRequestKey(
requests: readonly RequestInsight[],
selectedRequestId: string | null
selectedRequestKey: string | null
): string | null {
if (
selectedRequestId !== null &&
requests.some((request) => request.requestId === selectedRequestId)
selectedRequestKey !== null &&
requests.some(
(request) => getRequestInsightKey(request) === selectedRequestKey
)
) {
return selectedRequestId
return selectedRequestKey
}
return (
requests.find((request) => request.fetches.length > 0)?.requestId ??
requests[0]?.requestId ??
null
)
const request =
requests.find((item) => item.fetches.length > 0) ?? requests[0]
return request ? getRequestInsightKey(request) : null
}
export function isPageLoadRequest(
request: Pick<RequestInsight, 'requestId'>,
request: Pick<RequestInsight, 'requestId' | 'kind'>,
initialRequestId: string | undefined
): boolean {
return request.requestId === initialRequestId
return (
getRequestInsightKind(request) === 'request' &&
request.requestId === initialRequestId
)
}
import type { RequestInsight } from '../../../shared/request-insights'
import { getActiveRequestId, isPageLoadRequest } from './request-list'
import { getActiveRequestKey, isPageLoadRequest } from './request-list'
import { getTraceItems, getTracePosition, getTraceRange } from './trace-viewer'
function createRequest(
......@@ -22,11 +22,27 @@ describe('request insights trace viewer', () => {
const selectedRequest = createRequest({ requestId: 'selected' })
const newerRequest = createRequest({ requestId: 'newer' })
expect(getActiveRequestId([selectedRequest], null)).toBe('selected')
expect(getActiveRequestKey([selectedRequest], null)).toBe(
'request:selected'
)
expect(
getActiveRequestKey([newerRequest, selectedRequest], 'request:selected')
).toBe('request:selected')
expect(getActiveRequestKey([newerRequest], 'request:selected')).toBe(
'request:newer'
)
})
it('selects request and Instant Insights items independently', () => {
const request = createRequest({ requestId: 'shared' })
const instantInsights = createRequest({
requestId: 'shared',
kind: 'instant-insights',
})
expect(
getActiveRequestId([newerRequest, selectedRequest], 'selected')
).toBe('selected')
expect(getActiveRequestId([newerRequest], 'selected')).toBe('newer')
getActiveRequestKey([request, instantInsights], 'instant-insights:shared')
).toBe('instant-insights:shared')
})
it('only marks the exact initial document request as the page load', () => {
......@@ -50,6 +66,38 @@ describe('request insights trace viewer', () => {
initialRequestId
)
).toBe(false)
expect(
isPageLoadRequest(
createRequest({
requestId: initialRequestId,
kind: 'instant-insights',
}),
initialRequestId
)
).toBe(false)
})
it('shows the Instant Insights root span in the default trace', () => {
const request = createRequest({
kind: 'instant-insights',
spans: [
{
name: 'Instant Insights',
startTime: 100,
durationMs: 50,
attributes: {
'next.span_type': 'AppRender.instantInsights',
},
},
],
})
expect(getTraceItems(request, false)).toEqual([
expect.objectContaining({
label: 'Instant Insights',
spanType: 'AppRender.instantInsights',
}),
])
})
it('orders spans by their recorded parent-child hierarchy', () => {
......
......@@ -42,6 +42,7 @@ const DEFAULT_VISIBLE_SPAN_TYPES = new Set([
'AppRender.waitForRSC',
'AppRender.renderToNodeFizzStream',
'AppRender.waitForHTMLCompletion',
'AppRender.instantInsights',
FETCH_SPAN_TYPE,
'NextNodeServer.waitForFirstResponseChunk',
'NextNodeServer.startResponse',
......
......@@ -5,12 +5,49 @@ import {
createRuntimeBodyError,
createRuntimeBodyErrorInNavigation,
} from '../../server/app-render/blocking-route-messages'
import { getInstantErrorRoute, routeTemplateMatchesPath } from './shared'
import {
getInstantErrorRoute,
routeTemplateMatchesPath,
updateRequestInsights,
} from './shared'
import type { RequestInsight } from '../shared/request-insights'
const STATIC_ROUTE = '/example'
const DYNAMIC_ROUTE_TEMPLATE = '/posts/[slug]'
const CATCH_ALL_ROUTE_TEMPLATE = '/docs/[...slug]'
function createRequestInsight(
kind: RequestInsight['kind'],
durationMs: number
): RequestInsight {
return {
requestId: 'shared-request',
kind,
htmlRequestId: 'shared-html',
route: '/dashboard',
startTime: 100,
durationMs,
status: 'ok',
spans: [],
fetches: [],
}
}
describe('updateRequestInsights', () => {
it('updates request kinds independently when request IDs match', () => {
const request = createRequestInsight('request', 25)
const instantInsights = createRequestInsight('instant-insights', 50)
const updatedInstantInsights = createRequestInsight('instant-insights', 75)
expect(
updateRequestInsights(
updateRequestInsights([request], instantInsights),
updatedInstantInsights
)
).toEqual([request, updatedInstantInsights])
})
})
describe('getInstantErrorRoute', () => {
it('returns the route for an in-navigation runtime body error', () => {
expect(
......
......@@ -12,6 +12,7 @@ import type {
RequestInsight,
RequestInsightsSnapshot,
} from '../shared/request-insights'
import { getRequestInsightKey } from '../shared/request-insights'
import { readInstantNavCookieState } from './components/instant-navs/instant-nav-cookie'
import { isBlockingRouteInNavError } from './container/errors'
import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic'
......@@ -119,6 +120,18 @@ export const ACTION_INSTANT_ERRORS_CLEAR = 'instant-errors-clear'
export const ACTION_REQUEST_INSIGHTS_SNAPSHOT = 'request-insights-snapshot'
export const ACTION_REQUEST_INSIGHTS_UPDATE = 'request-insights-update'
export function updateRequestInsights(
currentRequests: readonly RequestInsight[],
insight: RequestInsight
): RequestInsight[] {
const insightKey = getRequestInsightKey(insight)
const requests = currentRequests.filter(
(request) => getRequestInsightKey(request) !== insightKey
)
requests.push(insight)
return requests.slice(-100)
}
export const STORAGE_KEY_PANEL_POSITION_PREFIX =
'__nextjs-dev-tools-panel-position'
export const STORE_KEY_PANEL_SIZE_PREFIX = '__nextjs-dev-tools-panel-size'
......@@ -607,11 +620,13 @@ export function useErrorOverlayReducer(
return { ...state, requestInsights: action.snapshot.requests }
}
case ACTION_REQUEST_INSIGHTS_UPDATE: {
const requests = state.requestInsights.filter(
(request) => request.requestId !== action.insight.requestId
)
requests.push(action.insight)
return { ...state, requestInsights: requests.slice(-100) }
return {
...state,
requestInsights: updateRequestInsights(
state.requestInsights,
action.insight
),
}
}
default: {
return state
......
import type { RequestInsightKind } from '../../shared/lib/request-insights'
export {
getRequestInsightKey,
getRequestInsightKind,
type RequestInsightIdentity,
type RequestInsightKind,
} from '../../shared/lib/request-insights'
type RequestInsightAttributeValue =
| string
| number
......@@ -44,6 +53,7 @@ export type RequestInsightFetch = {
export type RequestInsight = {
requestId: string
kind?: RequestInsightKind
htmlRequestId: string
route?: string
url?: string
......
......@@ -8,6 +8,7 @@ import {
isRequestInsightsEnabled,
recordRequestInsightFetch,
} from './trace/request-insights'
import { getRequestInsightsIdentity } from './trace/request-insights-identity'
import { getTracer, SpanKind } from './trace/tracer'
import {
CACHE_ONE_YEAR_SECONDS,
......@@ -146,24 +147,32 @@ function trackFetchMetric(
'next.fetch.cache_reason': metric.cacheReason,
})
if (isRequestInsightsEnabled() && workStore.requestId) {
recordRequestInsightFetch(
{
requestId: workStore.requestId,
htmlRequestId: workStore.htmlRequestId,
route: workStore.route,
},
{
url: metric.url,
method: metric.method,
statusCode: metric.status,
startTime: metric.start,
durationMs: metric.end - metric.start,
cacheStatus: metric.cacheStatus,
cacheReason: metric.cacheReason,
index: metric.idx,
}
)
if (isRequestInsightsEnabled()) {
const requestInsightsIdentity = getRequestInsightsIdentity()
const requestInsightsRequestId =
requestInsightsIdentity?.requestId ?? workStore.requestId
if (requestInsightsRequestId) {
recordRequestInsightFetch(
{
requestId: requestInsightsRequestId,
kind: requestInsightsIdentity?.kind,
htmlRequestId:
requestInsightsIdentity?.htmlRequestId ?? workStore.htmlRequestId,
route: workStore.route,
},
{
url: metric.url,
method: metric.method,
statusCode: metric.status,
startTime: metric.start,
durationMs: metric.end - metric.start,
cacheStatus: metric.cacheStatus,
cacheReason: metric.cacheReason,
index: metric.idx,
}
)
}
}
if (!workStore.shouldTrackFetchMetrics) {
......
......@@ -89,6 +89,7 @@ enum AppRenderSpan {
fetch = 'AppRender.fetch',
waitShellReady = 'AppRender.waitShellReady',
renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',
instantInsights = 'AppRender.instantInsights',
}
enum RouterSpan {
......
......@@ -8,6 +8,10 @@ import { SpanStatusCode, trace } from 'next/dist/compiled/@opentelemetry/api'
import { createLocalSpan } from './local-span-recorder'
import { runWithRequestInsightsIdentity } from './request-insights-identity'
import { setSpanRecorderForTest, type SpanStoreRecord } from './span-store'
import {
workAsyncStorage,
type WorkStore,
} from '../../app-render/work-async-storage.external'
const originalDevServer = process.env.__NEXT_DEV_SERVER
const spanRecords: SpanStoreRecord[] = []
......@@ -143,6 +147,38 @@ describe('local recording span', () => {
])
})
it('uses a nested Instant Insights identity instead of the work store identity', () => {
const workStore = {
requestId: 'work-request',
htmlRequestId: 'work-html',
route: '/dashboard',
} as WorkStore
workAsyncStorage.run(workStore, () => {
runWithRequestInsightsIdentity(
{
requestId: 'originating-request',
kind: 'instant-insights',
htmlRequestId: 'originating-html',
url: '/dashboard',
},
() => {
const span = createLocalSpan({ name: 'Instant Insights' })
span.end()
}
)
})
expect(spanRecords).toEqual([
expect.objectContaining({
requestId: 'originating-request',
requestInsightKind: 'instant-insights',
htmlRequestId: 'originating-html',
route: '/dashboard',
}),
])
})
it('records explicit performance timestamps', () => {
const startTime = performance.now() - 10
const span = createLocalSpan({
......
......@@ -13,6 +13,7 @@ import {
type SpanStoreEvent,
type SpanStoreLink,
} from './span-store'
import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'
export { isLocalSpanRecordingEnabled } from './span-store'
......@@ -112,6 +113,7 @@ function getLocalSpanAsyncStorage(): AsyncLocalStorage<Span> {
type RequestIdentity = {
requestId?: string
requestInsightKind?: RequestInsightKind
htmlRequestId?: string
route?: string
url?: string
......@@ -301,6 +303,7 @@ class LocalRecordingSpan implements Span {
spanId: this.spanContextValue.spanId,
parentSpanId: this.parentSpanId,
requestId: this.requestIdentity.requestId,
requestInsightKind: this.requestIdentity.requestInsightKind,
htmlRequestId: this.requestIdentity.htmlRequestId,
route:
getStringAttribute(recordAttributes, 'next.route') ??
......@@ -494,9 +497,10 @@ function getCurrentRequestIdentity(): RequestIdentity {
workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined
return {
requestId: workStore?.requestId ?? requestInsightsIdentity?.requestId,
requestId: requestInsightsIdentity?.requestId ?? workStore?.requestId,
requestInsightKind: requestInsightsIdentity?.kind,
htmlRequestId:
workStore?.htmlRequestId ?? requestInsightsIdentity?.htmlRequestId,
requestInsightsIdentity?.htmlRequestId ?? workStore?.htmlRequestId,
route: workStore?.route,
url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,
}
......
import type { AsyncLocalStorage } from 'async_hooks'
import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'
import { createAsyncLocalStorage } from '../../app-render/async-local-storage'
export type RequestInsightsIdentity = {
requestId: string
kind?: RequestInsightKind
htmlRequestId: string
url: string | undefined
}
......
......@@ -185,6 +185,80 @@ describe('request insights', () => {
)
})
it('keeps request and Instant Insights data separate for the same request ID', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const listener = jest.fn()
const unsubscribe = subscribeRequestInsights(listener)
recordSpan({
name: 'GET /dashboard',
requestId: 'req_shared',
htmlRequestId: 'html_shared',
route: '/dashboard',
startTime: 100,
durationMs: 40,
status: 'ok',
attributes: {
'next.span_type': 'BaseServer.handleRequest',
},
})
recordSpan({
name: 'Instant Insights',
requestId: 'req_shared',
requestInsightKind: 'instant-insights',
htmlRequestId: 'html_shared',
route: '/dashboard',
startTime: 150,
durationMs: 75,
status: 'ok',
attributes: {
'next.span_type': 'AppRender.instantInsights',
},
})
recordRequestInsightFetch(
{
requestId: 'req_shared',
kind: 'instant-insights',
htmlRequestId: 'html_shared',
route: '/dashboard',
},
{
url: 'https://example.com/validation-data',
startTime: 175,
durationMs: 10,
}
)
expect(getRequestInsightsSnapshot().requests).toEqual([
expect.objectContaining({
requestId: 'req_shared',
kind: 'request',
startTime: 100,
durationMs: 40,
fetches: [],
}),
expect.objectContaining({
requestId: 'req_shared',
kind: 'instant-insights',
startTime: 150,
durationMs: 75,
fetches: [
expect.objectContaining({
url: 'https://example.com/validation-data',
}),
],
}),
])
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({ kind: 'request' })
)
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({ kind: 'instant-insights' })
)
unsubscribe()
})
it('does not treat aggregate client component loading as a trace span', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
......
......@@ -4,6 +4,11 @@ import type {
RequestInsightFetch,
RequestInsightsSnapshot,
} from '../../../next-devtools/shared/request-insights'
import type { RequestInsightKind } from '../../../shared/lib/request-insights'
import {
getRequestInsightKey,
getRequestInsightKind,
} from '../../../shared/lib/request-insights'
import type { SpanStoreRecord } from './span-store'
export { isRequestInsightsEnabled } from './span-store'
......@@ -15,6 +20,7 @@ const CLIENT_COMPONENT_LOADING_SPAN_TYPE =
type RequestInsightsListener = (insight: RequestInsight) => void
type RequestInsightIdentity = {
requestId?: string
kind?: RequestInsightKind
htmlRequestId?: string
route?: string
url?: string
......@@ -56,7 +62,13 @@ class InMemoryRequestInsightsStore {
}
const insight = this.getOrCreateRequest(
span,
{
requestId: span.requestId,
kind: span.requestInsightKind,
htmlRequestId: span.htmlRequestId,
route: span.route,
url: span.url,
},
span.startTime ?? span.timestamp
)
......@@ -114,7 +126,7 @@ class InMemoryRequestInsightsStore {
getSnapshot(): RequestInsightsSnapshot {
return {
requests: this.requestOrder
.map((requestId) => this.requests.get(requestId))
.map((insightKey) => this.requests.get(insightKey))
.filter((request): request is RequestInsight => request !== undefined),
}
}
......@@ -138,15 +150,16 @@ class InMemoryRequestInsightsStore {
durationMs: number | undefined,
isRequestSpan: boolean
): void {
const insightKey = getRequestInsightKey(insight)
if (isRequestSpan && durationMs !== undefined) {
const requestTiming = { startTime, durationMs }
this.requestTimings.set(insight.requestId, requestTiming)
this.requestTimings.set(insightKey, requestTiming)
insight.startTime = requestTiming.startTime
insight.durationMs = requestTiming.durationMs
return
}
const requestTiming = this.requestTimings.get(insight.requestId)
const requestTiming = this.requestTimings.get(insightKey)
if (requestTiming) {
insight.startTime = requestTiming.startTime
insight.durationMs = requestTiming.durationMs
......@@ -170,11 +183,16 @@ class InMemoryRequestInsightsStore {
startTime: number
): RequestInsight {
const requestId = identity.requestId!
let insight = this.requests.get(requestId)
const insightKey = getRequestInsightKey({
requestId,
kind: identity.kind,
})
let insight = this.requests.get(insightKey)
if (!insight) {
insight = {
requestId,
kind: getRequestInsightKind(identity),
htmlRequestId: identity.htmlRequestId ?? requestId,
route: identity.route,
url: sanitizeUrl(identity.url),
......@@ -183,8 +201,8 @@ class InMemoryRequestInsightsStore {
spans: [],
fetches: [],
}
this.requests.set(requestId, insight)
this.requestOrder.push(requestId)
this.requests.set(insightKey, insight)
this.requestOrder.push(insightKey)
this.trim()
}
......@@ -217,10 +235,10 @@ class InMemoryRequestInsightsStore {
private trim(): void {
while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {
const requestId = this.requestOrder.shift()
if (requestId) {
this.requests.delete(requestId)
this.requestTimings.delete(requestId)
const insightKey = this.requestOrder.shift()
if (insightKey) {
this.requests.delete(insightKey)
this.requestTimings.delete(insightKey)
}
}
}
......
import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'
import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'
export type SpanStoreAttributes = Record<string, AttributeValue>
......@@ -24,6 +25,7 @@ export type SpanStoreRecord = {
spanId?: string
parentSpanId?: string
requestId?: string
requestInsightKind?: RequestInsightKind
htmlRequestId?: string
route?: string
url?: string
......
export type RequestInsightKind = 'request' | 'instant-insights'
export type RequestInsightIdentity = {
requestId: string
kind?: RequestInsightKind
}
export function getRequestInsightKind(
insight: Pick<RequestInsightIdentity, 'kind'>
): RequestInsightKind {
return insight.kind ?? 'request'
}
export function getRequestInsightKey(insight: RequestInsightIdentity): string {
return `${getRequestInsightKind(insight)}:${insight.requestId}`
}
export const instant = { level: 'experimental-error' }
export default function Page() {
return <p>instant insights</p>
}
......@@ -3,8 +3,12 @@
*/
const nextConfig = {
distDir: 'build',
cacheComponents: true,
experimental: {
requestInsights: true,
instantInsights: {
validationLevel: 'manual-warning',
},
},
}
......
......@@ -5,11 +5,13 @@ import { retry } from 'next-test-utils'
type RequestInsight = {
requestId: string
kind?: 'request' | 'instant-insights'
htmlRequestId: string
route: string
startTime: number
status: 'ok'
spans: Array<{
name?: string
attributes?: Record<string, string | number | boolean>
}>
fetches: Array<{
......@@ -119,10 +121,59 @@ describe('request insights', () => {
})
})
it('records Instant Insights separately from its originating request', async () => {
await next.render('/instant-insights')
await retry(async () => {
const snapshot = (await next
.fetch('/_next/development/request-insights')
.then((response) => response.json())) as {
requests: RequestInsight[]
}
const routeInsights = snapshot.requests.filter(
(request) => request.route === '/instant-insights'
)
const instantInsights = routeInsights.find(
(request) => request.kind === 'instant-insights'
)
const request = routeInsights.find(
(item) =>
(item.kind === undefined || item.kind === 'request') &&
item.requestId === instantInsights?.requestId
)
expect(instantInsights).toEqual(
expect.objectContaining({
kind: 'instant-insights',
durationMs: expect.any(Number),
status: 'ok',
})
)
expect(instantInsights?.htmlRequestId).toBe(request?.htmlRequestId)
expect(
instantInsights?.spans.some(
(span) =>
span.attributes?.['next.span_type'] ===
'AppRender.instantInsights' && span.name === 'Instant Insights'
)
).toBe(true)
expect(
request?.spans.some(
(span) =>
span.attributes?.['next.span_type'] === 'AppRender.instantInsights'
)
).toBe(false)
})
})
it('uses the development endpoint and reports truncated output', async () => {
const { result, requestedPaths } = await runWithResponse(
{
requests: [createRequest(1), createRequest(2), createRequest(3, 7)],
requests: [
createRequest(1),
createRequest(2),
{ ...createRequest(3, 7), kind: 'instant-insights' },
],
},
['--limit', '1']
)
......@@ -133,6 +184,8 @@ describe('request insights', () => {
'Showing 1 of 3 retained requests (newest first).'
)
expect(result.stdout).toContain('/route-3')
expect(result.stdout).toContain('Instant Insights · /route-3')
expect(result.stdout).toContain('kind instant-insights')
expect(result.stdout).not.toContain('/route-2')
expect(result.stdout).toContain('showing first 5 of 7 fetches')
expect(result.stdout).toContain('https://example.com/fetch-4')
......
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